Teach DAGCombiner how to fold a SIGN_EXTEND_INREG of a BUILD_VECTOR of
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Turn on alias analysis during testing"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Include global information in alias analysis"));
58
59   /// Hidden option to stress test load slicing, i.e., when this option
60   /// is enabled, load slicing bypasses most of its profitability guards.
61   static cl::opt<bool>
62   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
63                     cl::desc("Bypass the profitability model of load "
64                              "slicing"),
65                     cl::init(false));
66
67 //------------------------------ DAGCombiner ---------------------------------//
68
69   class DAGCombiner {
70     SelectionDAG &DAG;
71     const TargetLowering &TLI;
72     CombineLevel Level;
73     CodeGenOpt::Level OptLevel;
74     bool LegalOperations;
75     bool LegalTypes;
76     bool ForCodeSize;
77
78     // Worklist of all of the nodes that need to be simplified.
79     //
80     // This has the semantics that when adding to the worklist,
81     // the item added must be next to be processed. It should
82     // also only appear once. The naive approach to this takes
83     // linear time.
84     //
85     // To reduce the insert/remove time to logarithmic, we use
86     // a set and a vector to maintain our worklist.
87     //
88     // The set contains the items on the worklist, but does not
89     // maintain the order they should be visited.
90     //
91     // The vector maintains the order nodes should be visited, but may
92     // contain duplicate or removed nodes. When choosing a node to
93     // visit, we pop off the order stack until we find an item that is
94     // also in the contents set. All operations are O(log N).
95     SmallPtrSet<SDNode*, 64> WorkListContents;
96     SmallVector<SDNode*, 64> WorkListOrder;
97
98     // AA - Used for DAG load/store alias analysis.
99     AliasAnalysis &AA;
100
101     /// AddUsersToWorkList - When an instruction is simplified, add all users of
102     /// the instruction to the work lists because they might get more simplified
103     /// now.
104     ///
105     void AddUsersToWorkList(SDNode *N) {
106       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
107            UI != UE; ++UI)
108         AddToWorkList(*UI);
109     }
110
111     /// visit - call the node-specific routine that knows how to fold each
112     /// particular type of node.
113     SDValue visit(SDNode *N);
114
115   public:
116     /// AddToWorkList - Add to the work list making sure its instance is at the
117     /// back (next to be processed.)
118     void AddToWorkList(SDNode *N) {
119       WorkListContents.insert(N);
120       WorkListOrder.push_back(N);
121     }
122
123     /// removeFromWorkList - remove all instances of N from the worklist.
124     ///
125     void removeFromWorkList(SDNode *N) {
126       WorkListContents.erase(N);
127     }
128
129     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
130                       bool AddTo = true);
131
132     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
133       return CombineTo(N, &Res, 1, AddTo);
134     }
135
136     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
137                       bool AddTo = true) {
138       SDValue To[] = { Res0, Res1 };
139       return CombineTo(N, To, 2, AddTo);
140     }
141
142     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
143
144   private:
145
146     /// SimplifyDemandedBits - Check the specified integer node value to see if
147     /// it can be simplified or if things it uses can be simplified by bit
148     /// propagation.  If so, return true.
149     bool SimplifyDemandedBits(SDValue Op) {
150       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
151       APInt Demanded = APInt::getAllOnesValue(BitWidth);
152       return SimplifyDemandedBits(Op, Demanded);
153     }
154
155     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
156
157     bool CombineToPreIndexedLoadStore(SDNode *N);
158     bool CombineToPostIndexedLoadStore(SDNode *N);
159     bool SliceUpLoad(SDNode *N);
160
161     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
162     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
163     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
164     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
165     SDValue PromoteIntBinOp(SDValue Op);
166     SDValue PromoteIntShiftOp(SDValue Op);
167     SDValue PromoteExtend(SDValue Op);
168     bool PromoteLoad(SDValue Op);
169
170     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
171                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
172                          ISD::NodeType ExtType);
173
174     /// combine - call the node-specific routine that knows how to fold each
175     /// particular type of node. If that doesn't do anything, try the
176     /// target-specific DAG combines.
177     SDValue combine(SDNode *N);
178
179     // Visitation implementation - Implement dag node combining for different
180     // node types.  The semantics are as follows:
181     // Return Value:
182     //   SDValue.getNode() == 0 - No change was made
183     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
184     //   otherwise              - N should be replaced by the returned Operand.
185     //
186     SDValue visitTokenFactor(SDNode *N);
187     SDValue visitMERGE_VALUES(SDNode *N);
188     SDValue visitADD(SDNode *N);
189     SDValue visitSUB(SDNode *N);
190     SDValue visitADDC(SDNode *N);
191     SDValue visitSUBC(SDNode *N);
192     SDValue visitADDE(SDNode *N);
193     SDValue visitSUBE(SDNode *N);
194     SDValue visitMUL(SDNode *N);
195     SDValue visitSDIV(SDNode *N);
196     SDValue visitUDIV(SDNode *N);
197     SDValue visitSREM(SDNode *N);
198     SDValue visitUREM(SDNode *N);
199     SDValue visitMULHU(SDNode *N);
200     SDValue visitMULHS(SDNode *N);
201     SDValue visitSMUL_LOHI(SDNode *N);
202     SDValue visitUMUL_LOHI(SDNode *N);
203     SDValue visitSMULO(SDNode *N);
204     SDValue visitUMULO(SDNode *N);
205     SDValue visitSDIVREM(SDNode *N);
206     SDValue visitUDIVREM(SDNode *N);
207     SDValue visitAND(SDNode *N);
208     SDValue visitOR(SDNode *N);
209     SDValue visitXOR(SDNode *N);
210     SDValue SimplifyVBinOp(SDNode *N);
211     SDValue SimplifyVUnaryOp(SDNode *N);
212     SDValue visitSHL(SDNode *N);
213     SDValue visitSRA(SDNode *N);
214     SDValue visitSRL(SDNode *N);
215     SDValue visitCTLZ(SDNode *N);
216     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
217     SDValue visitCTTZ(SDNode *N);
218     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
219     SDValue visitCTPOP(SDNode *N);
220     SDValue visitSELECT(SDNode *N);
221     SDValue visitVSELECT(SDNode *N);
222     SDValue visitSELECT_CC(SDNode *N);
223     SDValue visitSETCC(SDNode *N);
224     SDValue visitSIGN_EXTEND(SDNode *N);
225     SDValue visitZERO_EXTEND(SDNode *N);
226     SDValue visitANY_EXTEND(SDNode *N);
227     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
228     SDValue visitTRUNCATE(SDNode *N);
229     SDValue visitBITCAST(SDNode *N);
230     SDValue visitBUILD_PAIR(SDNode *N);
231     SDValue visitFADD(SDNode *N);
232     SDValue visitFSUB(SDNode *N);
233     SDValue visitFMUL(SDNode *N);
234     SDValue visitFMA(SDNode *N);
235     SDValue visitFDIV(SDNode *N);
236     SDValue visitFREM(SDNode *N);
237     SDValue visitFCOPYSIGN(SDNode *N);
238     SDValue visitSINT_TO_FP(SDNode *N);
239     SDValue visitUINT_TO_FP(SDNode *N);
240     SDValue visitFP_TO_SINT(SDNode *N);
241     SDValue visitFP_TO_UINT(SDNode *N);
242     SDValue visitFP_ROUND(SDNode *N);
243     SDValue visitFP_ROUND_INREG(SDNode *N);
244     SDValue visitFP_EXTEND(SDNode *N);
245     SDValue visitFNEG(SDNode *N);
246     SDValue visitFABS(SDNode *N);
247     SDValue visitFCEIL(SDNode *N);
248     SDValue visitFTRUNC(SDNode *N);
249     SDValue visitFFLOOR(SDNode *N);
250     SDValue visitBRCOND(SDNode *N);
251     SDValue visitBR_CC(SDNode *N);
252     SDValue visitLOAD(SDNode *N);
253     SDValue visitSTORE(SDNode *N);
254     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
255     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
256     SDValue visitBUILD_VECTOR(SDNode *N);
257     SDValue visitCONCAT_VECTORS(SDNode *N);
258     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
259     SDValue visitVECTOR_SHUFFLE(SDNode *N);
260
261     SDValue XformToShuffleWithZero(SDNode *N);
262     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
263
264     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
265
266     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
267     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
268     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
269     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
270                              SDValue N3, ISD::CondCode CC,
271                              bool NotExtCompare = false);
272     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
273                           SDLoc DL, bool foldBooleans = true);
274     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
275                                          unsigned HiOp);
276     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
277     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
278     SDValue BuildSDIV(SDNode *N);
279     SDValue BuildUDIV(SDNode *N);
280     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
281                                bool DemandHighBits = true);
282     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
283     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
284     SDValue ReduceLoadWidth(SDNode *N);
285     SDValue ReduceLoadOpStoreWidth(SDNode *N);
286     SDValue TransformFPLoadStorePair(SDNode *N);
287     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
288     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
289
290     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
291
292     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
293     /// looking for aliasing nodes and adding them to the Aliases vector.
294     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
295                           SmallVectorImpl<SDValue> &Aliases);
296
297     /// isAlias - Return true if there is any possibility that the two addresses
298     /// overlap.
299     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
300                  const Value *SrcValue1, int SrcValueOffset1,
301                  unsigned SrcValueAlign1,
302                  const MDNode *TBAAInfo1,
303                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
304                  const Value *SrcValue2, int SrcValueOffset2,
305                  unsigned SrcValueAlign2,
306                  const MDNode *TBAAInfo2) const;
307
308     /// isAlias - Return true if there is any possibility that the two addresses
309     /// overlap.
310     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
311
312     /// FindAliasInfo - Extracts the relevant alias information from the memory
313     /// node.  Returns true if the operand was a load.
314     bool FindAliasInfo(SDNode *N,
315                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
316                        const Value *&SrcValue, int &SrcValueOffset,
317                        unsigned &SrcValueAlignment,
318                        const MDNode *&TBAAInfo) const;
319
320     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
321     /// looking for a better chain (aliasing node.)
322     SDValue FindBetterChain(SDNode *N, SDValue Chain);
323
324     /// Merge consecutive store operations into a wide store.
325     /// This optimization uses wide integers or vectors when possible.
326     /// \return True if some memory operations were changed.
327     bool MergeConsecutiveStores(StoreSDNode *N);
328
329   public:
330     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
331         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
332           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
333       AttributeSet FnAttrs =
334           DAG.getMachineFunction().getFunction()->getAttributes();
335       ForCodeSize =
336           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
337                                Attribute::OptimizeForSize) ||
338           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
339     }
340
341     /// Run - runs the dag combiner on all nodes in the work list
342     void Run(CombineLevel AtLevel);
343
344     SelectionDAG &getDAG() const { return DAG; }
345
346     /// getShiftAmountTy - Returns a type large enough to hold any valid
347     /// shift amount - before type legalization these can be huge.
348     EVT getShiftAmountTy(EVT LHSTy) {
349       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
350       if (LHSTy.isVector())
351         return LHSTy;
352       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
353                         : TLI.getPointerTy();
354     }
355
356     /// isTypeLegal - This method returns true if we are running before type
357     /// legalization or if the specified VT is legal.
358     bool isTypeLegal(const EVT &VT) {
359       if (!LegalTypes) return true;
360       return TLI.isTypeLegal(VT);
361     }
362
363     /// getSetCCResultType - Convenience wrapper around
364     /// TargetLowering::getSetCCResultType
365     EVT getSetCCResultType(EVT VT) const {
366       return TLI.getSetCCResultType(*DAG.getContext(), VT);
367     }
368   };
369 }
370
371
372 namespace {
373 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
374 /// nodes from the worklist.
375 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
376   DAGCombiner &DC;
377 public:
378   explicit WorkListRemover(DAGCombiner &dc)
379     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
380
381   virtual void NodeDeleted(SDNode *N, SDNode *E) {
382     DC.removeFromWorkList(N);
383   }
384 };
385 }
386
387 //===----------------------------------------------------------------------===//
388 //  TargetLowering::DAGCombinerInfo implementation
389 //===----------------------------------------------------------------------===//
390
391 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
392   ((DAGCombiner*)DC)->AddToWorkList(N);
393 }
394
395 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
396   ((DAGCombiner*)DC)->removeFromWorkList(N);
397 }
398
399 SDValue TargetLowering::DAGCombinerInfo::
400 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
401   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
402 }
403
404 SDValue TargetLowering::DAGCombinerInfo::
405 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
406   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
407 }
408
409
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
412   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
413 }
414
415 void TargetLowering::DAGCombinerInfo::
416 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
417   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
418 }
419
420 //===----------------------------------------------------------------------===//
421 // Helper Functions
422 //===----------------------------------------------------------------------===//
423
424 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
425 /// specified expression for the same cost as the expression itself, or 2 if we
426 /// can compute the negated form more cheaply than the expression itself.
427 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
428                                const TargetLowering &TLI,
429                                const TargetOptions *Options,
430                                unsigned Depth = 0) {
431   // fneg is removable even if it has multiple uses.
432   if (Op.getOpcode() == ISD::FNEG) return 2;
433
434   // Don't allow anything with multiple uses.
435   if (!Op.hasOneUse()) return 0;
436
437   // Don't recurse exponentially.
438   if (Depth > 6) return 0;
439
440   switch (Op.getOpcode()) {
441   default: return false;
442   case ISD::ConstantFP:
443     // Don't invert constant FP values after legalize.  The negated constant
444     // isn't necessarily legal.
445     return LegalOperations ? 0 : 1;
446   case ISD::FADD:
447     // FIXME: determine better conditions for this xform.
448     if (!Options->UnsafeFPMath) return 0;
449
450     // After operation legalization, it might not be legal to create new FSUBs.
451     if (LegalOperations &&
452         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
453       return 0;
454
455     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
456     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
457                                     Options, Depth + 1))
458       return V;
459     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
460     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
461                               Depth + 1);
462   case ISD::FSUB:
463     // We can't turn -(A-B) into B-A when we honor signed zeros.
464     if (!Options->UnsafeFPMath) return 0;
465
466     // fold (fneg (fsub A, B)) -> (fsub B, A)
467     return 1;
468
469   case ISD::FMUL:
470   case ISD::FDIV:
471     if (Options->HonorSignDependentRoundingFPMath()) return 0;
472
473     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
474     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
475                                     Options, Depth + 1))
476       return V;
477
478     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
479                               Depth + 1);
480
481   case ISD::FP_EXTEND:
482   case ISD::FP_ROUND:
483   case ISD::FSIN:
484     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
485                               Depth + 1);
486   }
487 }
488
489 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
490 /// returns the newly negated expression.
491 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
492                                     bool LegalOperations, unsigned Depth = 0) {
493   // fneg is removable even if it has multiple uses.
494   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
495
496   // Don't allow anything with multiple uses.
497   assert(Op.hasOneUse() && "Unknown reuse!");
498
499   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
500   switch (Op.getOpcode()) {
501   default: llvm_unreachable("Unknown code");
502   case ISD::ConstantFP: {
503     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
504     V.changeSign();
505     return DAG.getConstantFP(V, Op.getValueType());
506   }
507   case ISD::FADD:
508     // FIXME: determine better conditions for this xform.
509     assert(DAG.getTarget().Options.UnsafeFPMath);
510
511     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
512     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
513                            DAG.getTargetLoweringInfo(),
514                            &DAG.getTarget().Options, Depth+1))
515       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
516                          GetNegatedExpression(Op.getOperand(0), DAG,
517                                               LegalOperations, Depth+1),
518                          Op.getOperand(1));
519     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
520     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
521                        GetNegatedExpression(Op.getOperand(1), DAG,
522                                             LegalOperations, Depth+1),
523                        Op.getOperand(0));
524   case ISD::FSUB:
525     // We can't turn -(A-B) into B-A when we honor signed zeros.
526     assert(DAG.getTarget().Options.UnsafeFPMath);
527
528     // fold (fneg (fsub 0, B)) -> B
529     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
530       if (N0CFP->getValueAPF().isZero())
531         return Op.getOperand(1);
532
533     // fold (fneg (fsub A, B)) -> (fsub B, A)
534     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
535                        Op.getOperand(1), Op.getOperand(0));
536
537   case ISD::FMUL:
538   case ISD::FDIV:
539     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
540
541     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
542     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                            DAG.getTargetLoweringInfo(),
544                            &DAG.getTarget().Options, Depth+1))
545       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
546                          GetNegatedExpression(Op.getOperand(0), DAG,
547                                               LegalOperations, Depth+1),
548                          Op.getOperand(1));
549
550     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
551     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
552                        Op.getOperand(0),
553                        GetNegatedExpression(Op.getOperand(1), DAG,
554                                             LegalOperations, Depth+1));
555
556   case ISD::FP_EXTEND:
557   case ISD::FSIN:
558     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
559                        GetNegatedExpression(Op.getOperand(0), DAG,
560                                             LegalOperations, Depth+1));
561   case ISD::FP_ROUND:
562       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
563                          GetNegatedExpression(Op.getOperand(0), DAG,
564                                               LegalOperations, Depth+1),
565                          Op.getOperand(1));
566   }
567 }
568
569
570 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
571 // that selects between the values 1 and 0, making it equivalent to a setcc.
572 // Also, set the incoming LHS, RHS, and CC references to the appropriate
573 // nodes based on the type of node we are checking.  This simplifies life a
574 // bit for the callers.
575 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
576                               SDValue &CC) {
577   if (N.getOpcode() == ISD::SETCC) {
578     LHS = N.getOperand(0);
579     RHS = N.getOperand(1);
580     CC  = N.getOperand(2);
581     return true;
582   }
583   if (N.getOpcode() == ISD::SELECT_CC &&
584       N.getOperand(2).getOpcode() == ISD::Constant &&
585       N.getOperand(3).getOpcode() == ISD::Constant &&
586       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
587       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
588     LHS = N.getOperand(0);
589     RHS = N.getOperand(1);
590     CC  = N.getOperand(4);
591     return true;
592   }
593   return false;
594 }
595
596 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
597 // one use.  If this is true, it allows the users to invert the operation for
598 // free when it is profitable to do so.
599 static bool isOneUseSetCC(SDValue N) {
600   SDValue N0, N1, N2;
601   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
602     return true;
603   return false;
604 }
605
606 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
607                                     SDValue N0, SDValue N1) {
608   EVT VT = N0.getValueType();
609   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
610     if (isa<ConstantSDNode>(N1)) {
611       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
612       SDValue OpNode =
613         DAG.FoldConstantArithmetic(Opc, VT,
614                                    cast<ConstantSDNode>(N0.getOperand(1)),
615                                    cast<ConstantSDNode>(N1));
616       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
617     }
618     if (N0.hasOneUse()) {
619       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
620       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
621                                    N0.getOperand(0), N1);
622       AddToWorkList(OpNode.getNode());
623       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
624     }
625   }
626
627   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
628     if (isa<ConstantSDNode>(N0)) {
629       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
630       SDValue OpNode =
631         DAG.FoldConstantArithmetic(Opc, VT,
632                                    cast<ConstantSDNode>(N1.getOperand(1)),
633                                    cast<ConstantSDNode>(N0));
634       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
635     }
636     if (N1.hasOneUse()) {
637       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
638       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
639                                    N1.getOperand(0), N0);
640       AddToWorkList(OpNode.getNode());
641       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
642     }
643   }
644
645   return SDValue();
646 }
647
648 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
649                                bool AddTo) {
650   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
651   ++NodesCombined;
652   DEBUG(dbgs() << "\nReplacing.1 ";
653         N->dump(&DAG);
654         dbgs() << "\nWith: ";
655         To[0].getNode()->dump(&DAG);
656         dbgs() << " and " << NumTo-1 << " other values\n";
657         for (unsigned i = 0, e = NumTo; i != e; ++i)
658           assert((!To[i].getNode() ||
659                   N->getValueType(i) == To[i].getValueType()) &&
660                  "Cannot combine value to value of different type!"));
661   WorkListRemover DeadNodes(*this);
662   DAG.ReplaceAllUsesWith(N, To);
663   if (AddTo) {
664     // Push the new nodes and any users onto the worklist
665     for (unsigned i = 0, e = NumTo; i != e; ++i) {
666       if (To[i].getNode()) {
667         AddToWorkList(To[i].getNode());
668         AddUsersToWorkList(To[i].getNode());
669       }
670     }
671   }
672
673   // Finally, if the node is now dead, remove it from the graph.  The node
674   // may not be dead if the replacement process recursively simplified to
675   // something else needing this node.
676   if (N->use_empty()) {
677     // Nodes can be reintroduced into the worklist.  Make sure we do not
678     // process a node that has been replaced.
679     removeFromWorkList(N);
680
681     // Finally, since the node is now dead, remove it from the graph.
682     DAG.DeleteNode(N);
683   }
684   return SDValue(N, 0);
685 }
686
687 void DAGCombiner::
688 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
689   // Replace all uses.  If any nodes become isomorphic to other nodes and
690   // are deleted, make sure to remove them from our worklist.
691   WorkListRemover DeadNodes(*this);
692   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
693
694   // Push the new node and any (possibly new) users onto the worklist.
695   AddToWorkList(TLO.New.getNode());
696   AddUsersToWorkList(TLO.New.getNode());
697
698   // Finally, if the node is now dead, remove it from the graph.  The node
699   // may not be dead if the replacement process recursively simplified to
700   // something else needing this node.
701   if (TLO.Old.getNode()->use_empty()) {
702     removeFromWorkList(TLO.Old.getNode());
703
704     // If the operands of this node are only used by the node, they will now
705     // be dead.  Make sure to visit them first to delete dead nodes early.
706     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
707       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
708         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
709
710     DAG.DeleteNode(TLO.Old.getNode());
711   }
712 }
713
714 /// SimplifyDemandedBits - Check the specified integer node value to see if
715 /// it can be simplified or if things it uses can be simplified by bit
716 /// propagation.  If so, return true.
717 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
718   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
719   APInt KnownZero, KnownOne;
720   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
721     return false;
722
723   // Revisit the node.
724   AddToWorkList(Op.getNode());
725
726   // Replace the old value with the new one.
727   ++NodesCombined;
728   DEBUG(dbgs() << "\nReplacing.2 ";
729         TLO.Old.getNode()->dump(&DAG);
730         dbgs() << "\nWith: ";
731         TLO.New.getNode()->dump(&DAG);
732         dbgs() << '\n');
733
734   CommitTargetLoweringOpt(TLO);
735   return true;
736 }
737
738 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
739   SDLoc dl(Load);
740   EVT VT = Load->getValueType(0);
741   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
742
743   DEBUG(dbgs() << "\nReplacing.9 ";
744         Load->dump(&DAG);
745         dbgs() << "\nWith: ";
746         Trunc.getNode()->dump(&DAG);
747         dbgs() << '\n');
748   WorkListRemover DeadNodes(*this);
749   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
750   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
751   removeFromWorkList(Load);
752   DAG.DeleteNode(Load);
753   AddToWorkList(Trunc.getNode());
754 }
755
756 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
757   Replace = false;
758   SDLoc dl(Op);
759   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
760     EVT MemVT = LD->getMemoryVT();
761     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
762       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
763                                                   : ISD::EXTLOAD)
764       : LD->getExtensionType();
765     Replace = true;
766     return DAG.getExtLoad(ExtType, dl, PVT,
767                           LD->getChain(), LD->getBasePtr(),
768                           MemVT, LD->getMemOperand());
769   }
770
771   unsigned Opc = Op.getOpcode();
772   switch (Opc) {
773   default: break;
774   case ISD::AssertSext:
775     return DAG.getNode(ISD::AssertSext, dl, PVT,
776                        SExtPromoteOperand(Op.getOperand(0), PVT),
777                        Op.getOperand(1));
778   case ISD::AssertZext:
779     return DAG.getNode(ISD::AssertZext, dl, PVT,
780                        ZExtPromoteOperand(Op.getOperand(0), PVT),
781                        Op.getOperand(1));
782   case ISD::Constant: {
783     unsigned ExtOpc =
784       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
785     return DAG.getNode(ExtOpc, dl, PVT, Op);
786   }
787   }
788
789   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
790     return SDValue();
791   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
792 }
793
794 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
795   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
796     return SDValue();
797   EVT OldVT = Op.getValueType();
798   SDLoc dl(Op);
799   bool Replace = false;
800   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
801   if (NewOp.getNode() == 0)
802     return SDValue();
803   AddToWorkList(NewOp.getNode());
804
805   if (Replace)
806     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
807   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
808                      DAG.getValueType(OldVT));
809 }
810
811 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
812   EVT OldVT = Op.getValueType();
813   SDLoc dl(Op);
814   bool Replace = false;
815   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
816   if (NewOp.getNode() == 0)
817     return SDValue();
818   AddToWorkList(NewOp.getNode());
819
820   if (Replace)
821     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
822   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
823 }
824
825 /// PromoteIntBinOp - Promote the specified integer binary operation if the
826 /// target indicates it is beneficial. e.g. On x86, it's usually better to
827 /// promote i16 operations to i32 since i16 instructions are longer.
828 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
829   if (!LegalOperations)
830     return SDValue();
831
832   EVT VT = Op.getValueType();
833   if (VT.isVector() || !VT.isInteger())
834     return SDValue();
835
836   // If operation type is 'undesirable', e.g. i16 on x86, consider
837   // promoting it.
838   unsigned Opc = Op.getOpcode();
839   if (TLI.isTypeDesirableForOp(Opc, VT))
840     return SDValue();
841
842   EVT PVT = VT;
843   // Consult target whether it is a good idea to promote this operation and
844   // what's the right type to promote it to.
845   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
846     assert(PVT != VT && "Don't know what type to promote to!");
847
848     bool Replace0 = false;
849     SDValue N0 = Op.getOperand(0);
850     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
851     if (NN0.getNode() == 0)
852       return SDValue();
853
854     bool Replace1 = false;
855     SDValue N1 = Op.getOperand(1);
856     SDValue NN1;
857     if (N0 == N1)
858       NN1 = NN0;
859     else {
860       NN1 = PromoteOperand(N1, PVT, Replace1);
861       if (NN1.getNode() == 0)
862         return SDValue();
863     }
864
865     AddToWorkList(NN0.getNode());
866     if (NN1.getNode())
867       AddToWorkList(NN1.getNode());
868
869     if (Replace0)
870       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
871     if (Replace1)
872       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
873
874     DEBUG(dbgs() << "\nPromoting ";
875           Op.getNode()->dump(&DAG));
876     SDLoc dl(Op);
877     return DAG.getNode(ISD::TRUNCATE, dl, VT,
878                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
879   }
880   return SDValue();
881 }
882
883 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
884 /// target indicates it is beneficial. e.g. On x86, it's usually better to
885 /// promote i16 operations to i32 since i16 instructions are longer.
886 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
887   if (!LegalOperations)
888     return SDValue();
889
890   EVT VT = Op.getValueType();
891   if (VT.isVector() || !VT.isInteger())
892     return SDValue();
893
894   // If operation type is 'undesirable', e.g. i16 on x86, consider
895   // promoting it.
896   unsigned Opc = Op.getOpcode();
897   if (TLI.isTypeDesirableForOp(Opc, VT))
898     return SDValue();
899
900   EVT PVT = VT;
901   // Consult target whether it is a good idea to promote this operation and
902   // what's the right type to promote it to.
903   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
904     assert(PVT != VT && "Don't know what type to promote to!");
905
906     bool Replace = false;
907     SDValue N0 = Op.getOperand(0);
908     if (Opc == ISD::SRA)
909       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
910     else if (Opc == ISD::SRL)
911       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
912     else
913       N0 = PromoteOperand(N0, PVT, Replace);
914     if (N0.getNode() == 0)
915       return SDValue();
916
917     AddToWorkList(N0.getNode());
918     if (Replace)
919       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
920
921     DEBUG(dbgs() << "\nPromoting ";
922           Op.getNode()->dump(&DAG));
923     SDLoc dl(Op);
924     return DAG.getNode(ISD::TRUNCATE, dl, VT,
925                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
926   }
927   return SDValue();
928 }
929
930 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
931   if (!LegalOperations)
932     return SDValue();
933
934   EVT VT = Op.getValueType();
935   if (VT.isVector() || !VT.isInteger())
936     return SDValue();
937
938   // If operation type is 'undesirable', e.g. i16 on x86, consider
939   // promoting it.
940   unsigned Opc = Op.getOpcode();
941   if (TLI.isTypeDesirableForOp(Opc, VT))
942     return SDValue();
943
944   EVT PVT = VT;
945   // Consult target whether it is a good idea to promote this operation and
946   // what's the right type to promote it to.
947   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
948     assert(PVT != VT && "Don't know what type to promote to!");
949     // fold (aext (aext x)) -> (aext x)
950     // fold (aext (zext x)) -> (zext x)
951     // fold (aext (sext x)) -> (sext x)
952     DEBUG(dbgs() << "\nPromoting ";
953           Op.getNode()->dump(&DAG));
954     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
955   }
956   return SDValue();
957 }
958
959 bool DAGCombiner::PromoteLoad(SDValue Op) {
960   if (!LegalOperations)
961     return false;
962
963   EVT VT = Op.getValueType();
964   if (VT.isVector() || !VT.isInteger())
965     return false;
966
967   // If operation type is 'undesirable', e.g. i16 on x86, consider
968   // promoting it.
969   unsigned Opc = Op.getOpcode();
970   if (TLI.isTypeDesirableForOp(Opc, VT))
971     return false;
972
973   EVT PVT = VT;
974   // Consult target whether it is a good idea to promote this operation and
975   // what's the right type to promote it to.
976   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
977     assert(PVT != VT && "Don't know what type to promote to!");
978
979     SDLoc dl(Op);
980     SDNode *N = Op.getNode();
981     LoadSDNode *LD = cast<LoadSDNode>(N);
982     EVT MemVT = LD->getMemoryVT();
983     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
984       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
985                                                   : ISD::EXTLOAD)
986       : LD->getExtensionType();
987     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
988                                    LD->getChain(), LD->getBasePtr(),
989                                    MemVT, LD->getMemOperand());
990     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
991
992     DEBUG(dbgs() << "\nPromoting ";
993           N->dump(&DAG);
994           dbgs() << "\nTo: ";
995           Result.getNode()->dump(&DAG);
996           dbgs() << '\n');
997     WorkListRemover DeadNodes(*this);
998     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
999     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1000     removeFromWorkList(N);
1001     DAG.DeleteNode(N);
1002     AddToWorkList(Result.getNode());
1003     return true;
1004   }
1005   return false;
1006 }
1007
1008
1009 //===----------------------------------------------------------------------===//
1010 //  Main DAG Combiner implementation
1011 //===----------------------------------------------------------------------===//
1012
1013 void DAGCombiner::Run(CombineLevel AtLevel) {
1014   // set the instance variables, so that the various visit routines may use it.
1015   Level = AtLevel;
1016   LegalOperations = Level >= AfterLegalizeVectorOps;
1017   LegalTypes = Level >= AfterLegalizeTypes;
1018
1019   // Add all the dag nodes to the worklist.
1020   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1021        E = DAG.allnodes_end(); I != E; ++I)
1022     AddToWorkList(I);
1023
1024   // Create a dummy node (which is not added to allnodes), that adds a reference
1025   // to the root node, preventing it from being deleted, and tracking any
1026   // changes of the root.
1027   HandleSDNode Dummy(DAG.getRoot());
1028
1029   // The root of the dag may dangle to deleted nodes until the dag combiner is
1030   // done.  Set it to null to avoid confusion.
1031   DAG.setRoot(SDValue());
1032
1033   // while the worklist isn't empty, find a node and
1034   // try and combine it.
1035   while (!WorkListContents.empty()) {
1036     SDNode *N;
1037     // The WorkListOrder holds the SDNodes in order, but it may contain
1038     // duplicates.
1039     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1040     // worklist *should* contain, and check the node we want to visit is should
1041     // actually be visited.
1042     do {
1043       N = WorkListOrder.pop_back_val();
1044     } while (!WorkListContents.erase(N));
1045
1046     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1047     // N is deleted from the DAG, since they too may now be dead or may have a
1048     // reduced number of uses, allowing other xforms.
1049     if (N->use_empty() && N != &Dummy) {
1050       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1051         AddToWorkList(N->getOperand(i).getNode());
1052
1053       DAG.DeleteNode(N);
1054       continue;
1055     }
1056
1057     SDValue RV = combine(N);
1058
1059     if (RV.getNode() == 0)
1060       continue;
1061
1062     ++NodesCombined;
1063
1064     // If we get back the same node we passed in, rather than a new node or
1065     // zero, we know that the node must have defined multiple values and
1066     // CombineTo was used.  Since CombineTo takes care of the worklist
1067     // mechanics for us, we have no work to do in this case.
1068     if (RV.getNode() == N)
1069       continue;
1070
1071     assert(N->getOpcode() != ISD::DELETED_NODE &&
1072            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1073            "Node was deleted but visit returned new node!");
1074
1075     DEBUG(dbgs() << "\nReplacing.3 ";
1076           N->dump(&DAG);
1077           dbgs() << "\nWith: ";
1078           RV.getNode()->dump(&DAG);
1079           dbgs() << '\n');
1080
1081     // Transfer debug value.
1082     DAG.TransferDbgValues(SDValue(N, 0), RV);
1083     WorkListRemover DeadNodes(*this);
1084     if (N->getNumValues() == RV.getNode()->getNumValues())
1085       DAG.ReplaceAllUsesWith(N, RV.getNode());
1086     else {
1087       assert(N->getValueType(0) == RV.getValueType() &&
1088              N->getNumValues() == 1 && "Type mismatch");
1089       SDValue OpV = RV;
1090       DAG.ReplaceAllUsesWith(N, &OpV);
1091     }
1092
1093     // Push the new node and any users onto the worklist
1094     AddToWorkList(RV.getNode());
1095     AddUsersToWorkList(RV.getNode());
1096
1097     // Add any uses of the old node to the worklist in case this node is the
1098     // last one that uses them.  They may become dead after this node is
1099     // deleted.
1100     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1101       AddToWorkList(N->getOperand(i).getNode());
1102
1103     // Finally, if the node is now dead, remove it from the graph.  The node
1104     // may not be dead if the replacement process recursively simplified to
1105     // something else needing this node.
1106     if (N->use_empty()) {
1107       // Nodes can be reintroduced into the worklist.  Make sure we do not
1108       // process a node that has been replaced.
1109       removeFromWorkList(N);
1110
1111       // Finally, since the node is now dead, remove it from the graph.
1112       DAG.DeleteNode(N);
1113     }
1114   }
1115
1116   // If the root changed (e.g. it was a dead load, update the root).
1117   DAG.setRoot(Dummy.getValue());
1118   DAG.RemoveDeadNodes();
1119 }
1120
1121 SDValue DAGCombiner::visit(SDNode *N) {
1122   switch (N->getOpcode()) {
1123   default: break;
1124   case ISD::TokenFactor:        return visitTokenFactor(N);
1125   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1126   case ISD::ADD:                return visitADD(N);
1127   case ISD::SUB:                return visitSUB(N);
1128   case ISD::ADDC:               return visitADDC(N);
1129   case ISD::SUBC:               return visitSUBC(N);
1130   case ISD::ADDE:               return visitADDE(N);
1131   case ISD::SUBE:               return visitSUBE(N);
1132   case ISD::MUL:                return visitMUL(N);
1133   case ISD::SDIV:               return visitSDIV(N);
1134   case ISD::UDIV:               return visitUDIV(N);
1135   case ISD::SREM:               return visitSREM(N);
1136   case ISD::UREM:               return visitUREM(N);
1137   case ISD::MULHU:              return visitMULHU(N);
1138   case ISD::MULHS:              return visitMULHS(N);
1139   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1140   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1141   case ISD::SMULO:              return visitSMULO(N);
1142   case ISD::UMULO:              return visitUMULO(N);
1143   case ISD::SDIVREM:            return visitSDIVREM(N);
1144   case ISD::UDIVREM:            return visitUDIVREM(N);
1145   case ISD::AND:                return visitAND(N);
1146   case ISD::OR:                 return visitOR(N);
1147   case ISD::XOR:                return visitXOR(N);
1148   case ISD::SHL:                return visitSHL(N);
1149   case ISD::SRA:                return visitSRA(N);
1150   case ISD::SRL:                return visitSRL(N);
1151   case ISD::CTLZ:               return visitCTLZ(N);
1152   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1153   case ISD::CTTZ:               return visitCTTZ(N);
1154   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1155   case ISD::CTPOP:              return visitCTPOP(N);
1156   case ISD::SELECT:             return visitSELECT(N);
1157   case ISD::VSELECT:            return visitVSELECT(N);
1158   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1159   case ISD::SETCC:              return visitSETCC(N);
1160   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1161   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1162   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1163   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1164   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1165   case ISD::BITCAST:            return visitBITCAST(N);
1166   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1167   case ISD::FADD:               return visitFADD(N);
1168   case ISD::FSUB:               return visitFSUB(N);
1169   case ISD::FMUL:               return visitFMUL(N);
1170   case ISD::FMA:                return visitFMA(N);
1171   case ISD::FDIV:               return visitFDIV(N);
1172   case ISD::FREM:               return visitFREM(N);
1173   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1174   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1175   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1176   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1177   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1178   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1179   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1180   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1181   case ISD::FNEG:               return visitFNEG(N);
1182   case ISD::FABS:               return visitFABS(N);
1183   case ISD::FFLOOR:             return visitFFLOOR(N);
1184   case ISD::FCEIL:              return visitFCEIL(N);
1185   case ISD::FTRUNC:             return visitFTRUNC(N);
1186   case ISD::BRCOND:             return visitBRCOND(N);
1187   case ISD::BR_CC:              return visitBR_CC(N);
1188   case ISD::LOAD:               return visitLOAD(N);
1189   case ISD::STORE:              return visitSTORE(N);
1190   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1191   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1192   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1193   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1194   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1195   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1196   }
1197   return SDValue();
1198 }
1199
1200 SDValue DAGCombiner::combine(SDNode *N) {
1201   SDValue RV = visit(N);
1202
1203   // If nothing happened, try a target-specific DAG combine.
1204   if (RV.getNode() == 0) {
1205     assert(N->getOpcode() != ISD::DELETED_NODE &&
1206            "Node was deleted but visit returned NULL!");
1207
1208     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1209         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1210
1211       // Expose the DAG combiner to the target combiner impls.
1212       TargetLowering::DAGCombinerInfo
1213         DagCombineInfo(DAG, Level, false, this);
1214
1215       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1216     }
1217   }
1218
1219   // If nothing happened still, try promoting the operation.
1220   if (RV.getNode() == 0) {
1221     switch (N->getOpcode()) {
1222     default: break;
1223     case ISD::ADD:
1224     case ISD::SUB:
1225     case ISD::MUL:
1226     case ISD::AND:
1227     case ISD::OR:
1228     case ISD::XOR:
1229       RV = PromoteIntBinOp(SDValue(N, 0));
1230       break;
1231     case ISD::SHL:
1232     case ISD::SRA:
1233     case ISD::SRL:
1234       RV = PromoteIntShiftOp(SDValue(N, 0));
1235       break;
1236     case ISD::SIGN_EXTEND:
1237     case ISD::ZERO_EXTEND:
1238     case ISD::ANY_EXTEND:
1239       RV = PromoteExtend(SDValue(N, 0));
1240       break;
1241     case ISD::LOAD:
1242       if (PromoteLoad(SDValue(N, 0)))
1243         RV = SDValue(N, 0);
1244       break;
1245     }
1246   }
1247
1248   // If N is a commutative binary node, try commuting it to enable more
1249   // sdisel CSE.
1250   if (RV.getNode() == 0 &&
1251       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1252       N->getNumValues() == 1) {
1253     SDValue N0 = N->getOperand(0);
1254     SDValue N1 = N->getOperand(1);
1255
1256     // Constant operands are canonicalized to RHS.
1257     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1258       SDValue Ops[] = { N1, N0 };
1259       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1260                                             Ops, 2);
1261       if (CSENode)
1262         return SDValue(CSENode, 0);
1263     }
1264   }
1265
1266   return RV;
1267 }
1268
1269 /// getInputChainForNode - Given a node, return its input chain if it has one,
1270 /// otherwise return a null sd operand.
1271 static SDValue getInputChainForNode(SDNode *N) {
1272   if (unsigned NumOps = N->getNumOperands()) {
1273     if (N->getOperand(0).getValueType() == MVT::Other)
1274       return N->getOperand(0);
1275     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1276       return N->getOperand(NumOps-1);
1277     for (unsigned i = 1; i < NumOps-1; ++i)
1278       if (N->getOperand(i).getValueType() == MVT::Other)
1279         return N->getOperand(i);
1280   }
1281   return SDValue();
1282 }
1283
1284 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1285   // If N has two operands, where one has an input chain equal to the other,
1286   // the 'other' chain is redundant.
1287   if (N->getNumOperands() == 2) {
1288     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1289       return N->getOperand(0);
1290     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1291       return N->getOperand(1);
1292   }
1293
1294   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1295   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1296   SmallPtrSet<SDNode*, 16> SeenOps;
1297   bool Changed = false;             // If we should replace this token factor.
1298
1299   // Start out with this token factor.
1300   TFs.push_back(N);
1301
1302   // Iterate through token factors.  The TFs grows when new token factors are
1303   // encountered.
1304   for (unsigned i = 0; i < TFs.size(); ++i) {
1305     SDNode *TF = TFs[i];
1306
1307     // Check each of the operands.
1308     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1309       SDValue Op = TF->getOperand(i);
1310
1311       switch (Op.getOpcode()) {
1312       case ISD::EntryToken:
1313         // Entry tokens don't need to be added to the list. They are
1314         // rededundant.
1315         Changed = true;
1316         break;
1317
1318       case ISD::TokenFactor:
1319         if (Op.hasOneUse() &&
1320             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1321           // Queue up for processing.
1322           TFs.push_back(Op.getNode());
1323           // Clean up in case the token factor is removed.
1324           AddToWorkList(Op.getNode());
1325           Changed = true;
1326           break;
1327         }
1328         // Fall thru
1329
1330       default:
1331         // Only add if it isn't already in the list.
1332         if (SeenOps.insert(Op.getNode()))
1333           Ops.push_back(Op);
1334         else
1335           Changed = true;
1336         break;
1337       }
1338     }
1339   }
1340
1341   SDValue Result;
1342
1343   // If we've change things around then replace token factor.
1344   if (Changed) {
1345     if (Ops.empty()) {
1346       // The entry token is the only possible outcome.
1347       Result = DAG.getEntryNode();
1348     } else {
1349       // New and improved token factor.
1350       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1351                            MVT::Other, &Ops[0], Ops.size());
1352     }
1353
1354     // Don't add users to work list.
1355     return CombineTo(N, Result, false);
1356   }
1357
1358   return Result;
1359 }
1360
1361 /// MERGE_VALUES can always be eliminated.
1362 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1363   WorkListRemover DeadNodes(*this);
1364   // Replacing results may cause a different MERGE_VALUES to suddenly
1365   // be CSE'd with N, and carry its uses with it. Iterate until no
1366   // uses remain, to ensure that the node can be safely deleted.
1367   // First add the users of this node to the work list so that they
1368   // can be tried again once they have new operands.
1369   AddUsersToWorkList(N);
1370   do {
1371     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1372       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1373   } while (!N->use_empty());
1374   removeFromWorkList(N);
1375   DAG.DeleteNode(N);
1376   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1377 }
1378
1379 static
1380 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1381                               SelectionDAG &DAG) {
1382   EVT VT = N0.getValueType();
1383   SDValue N00 = N0.getOperand(0);
1384   SDValue N01 = N0.getOperand(1);
1385   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1386
1387   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1388       isa<ConstantSDNode>(N00.getOperand(1))) {
1389     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1390     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1391                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1392                                  N00.getOperand(0), N01),
1393                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1394                                  N00.getOperand(1), N01));
1395     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1396   }
1397
1398   return SDValue();
1399 }
1400
1401 SDValue DAGCombiner::visitADD(SDNode *N) {
1402   SDValue N0 = N->getOperand(0);
1403   SDValue N1 = N->getOperand(1);
1404   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1405   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1406   EVT VT = N0.getValueType();
1407
1408   // fold vector ops
1409   if (VT.isVector()) {
1410     SDValue FoldedVOp = SimplifyVBinOp(N);
1411     if (FoldedVOp.getNode()) return FoldedVOp;
1412
1413     // fold (add x, 0) -> x, vector edition
1414     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1415       return N0;
1416     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1417       return N1;
1418   }
1419
1420   // fold (add x, undef) -> undef
1421   if (N0.getOpcode() == ISD::UNDEF)
1422     return N0;
1423   if (N1.getOpcode() == ISD::UNDEF)
1424     return N1;
1425   // fold (add c1, c2) -> c1+c2
1426   if (N0C && N1C)
1427     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1428   // canonicalize constant to RHS
1429   if (N0C && !N1C)
1430     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1431   // fold (add x, 0) -> x
1432   if (N1C && N1C->isNullValue())
1433     return N0;
1434   // fold (add Sym, c) -> Sym+c
1435   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1436     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1437         GA->getOpcode() == ISD::GlobalAddress)
1438       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1439                                   GA->getOffset() +
1440                                     (uint64_t)N1C->getSExtValue());
1441   // fold ((c1-A)+c2) -> (c1+c2)-A
1442   if (N1C && N0.getOpcode() == ISD::SUB)
1443     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1444       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1445                          DAG.getConstant(N1C->getAPIntValue()+
1446                                          N0C->getAPIntValue(), VT),
1447                          N0.getOperand(1));
1448   // reassociate add
1449   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1450   if (RADD.getNode() != 0)
1451     return RADD;
1452   // fold ((0-A) + B) -> B-A
1453   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1454       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1455     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1456   // fold (A + (0-B)) -> A-B
1457   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1458       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1459     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1460   // fold (A+(B-A)) -> B
1461   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1462     return N1.getOperand(0);
1463   // fold ((B-A)+A) -> B
1464   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1465     return N0.getOperand(0);
1466   // fold (A+(B-(A+C))) to (B-C)
1467   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1468       N0 == N1.getOperand(1).getOperand(0))
1469     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1470                        N1.getOperand(1).getOperand(1));
1471   // fold (A+(B-(C+A))) to (B-C)
1472   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1473       N0 == N1.getOperand(1).getOperand(1))
1474     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1475                        N1.getOperand(1).getOperand(0));
1476   // fold (A+((B-A)+or-C)) to (B+or-C)
1477   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1478       N1.getOperand(0).getOpcode() == ISD::SUB &&
1479       N0 == N1.getOperand(0).getOperand(1))
1480     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1481                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1482
1483   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1484   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1485     SDValue N00 = N0.getOperand(0);
1486     SDValue N01 = N0.getOperand(1);
1487     SDValue N10 = N1.getOperand(0);
1488     SDValue N11 = N1.getOperand(1);
1489
1490     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1491       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1493                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1494   }
1495
1496   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1497     return SDValue(N, 0);
1498
1499   // fold (a+b) -> (a|b) iff a and b share no bits.
1500   if (VT.isInteger() && !VT.isVector()) {
1501     APInt LHSZero, LHSOne;
1502     APInt RHSZero, RHSOne;
1503     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1504
1505     if (LHSZero.getBoolValue()) {
1506       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1507
1508       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1509       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1510       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1511         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1512     }
1513   }
1514
1515   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1516   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1517     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1518     if (Result.getNode()) return Result;
1519   }
1520   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1521     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1522     if (Result.getNode()) return Result;
1523   }
1524
1525   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1526   if (N1.getOpcode() == ISD::SHL &&
1527       N1.getOperand(0).getOpcode() == ISD::SUB)
1528     if (ConstantSDNode *C =
1529           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1530       if (C->getAPIntValue() == 0)
1531         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1532                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1533                                        N1.getOperand(0).getOperand(1),
1534                                        N1.getOperand(1)));
1535   if (N0.getOpcode() == ISD::SHL &&
1536       N0.getOperand(0).getOpcode() == ISD::SUB)
1537     if (ConstantSDNode *C =
1538           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1539       if (C->getAPIntValue() == 0)
1540         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1541                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1542                                        N0.getOperand(0).getOperand(1),
1543                                        N0.getOperand(1)));
1544
1545   if (N1.getOpcode() == ISD::AND) {
1546     SDValue AndOp0 = N1.getOperand(0);
1547     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1548     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1549     unsigned DestBits = VT.getScalarType().getSizeInBits();
1550
1551     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1552     // and similar xforms where the inner op is either ~0 or 0.
1553     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1554       SDLoc DL(N);
1555       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1556     }
1557   }
1558
1559   // add (sext i1), X -> sub X, (zext i1)
1560   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1561       N0.getOperand(0).getValueType() == MVT::i1 &&
1562       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1563     SDLoc DL(N);
1564     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1565     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1566   }
1567
1568   return SDValue();
1569 }
1570
1571 SDValue DAGCombiner::visitADDC(SDNode *N) {
1572   SDValue N0 = N->getOperand(0);
1573   SDValue N1 = N->getOperand(1);
1574   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1575   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1576   EVT VT = N0.getValueType();
1577
1578   // If the flag result is dead, turn this into an ADD.
1579   if (!N->hasAnyUseOfValue(1))
1580     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1581                      DAG.getNode(ISD::CARRY_FALSE,
1582                                  SDLoc(N), MVT::Glue));
1583
1584   // canonicalize constant to RHS.
1585   if (N0C && !N1C)
1586     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1587
1588   // fold (addc x, 0) -> x + no carry out
1589   if (N1C && N1C->isNullValue())
1590     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1591                                         SDLoc(N), MVT::Glue));
1592
1593   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1594   APInt LHSZero, LHSOne;
1595   APInt RHSZero, RHSOne;
1596   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1597
1598   if (LHSZero.getBoolValue()) {
1599     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1600
1601     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1602     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1603     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1604       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1605                        DAG.getNode(ISD::CARRY_FALSE,
1606                                    SDLoc(N), MVT::Glue));
1607   }
1608
1609   return SDValue();
1610 }
1611
1612 SDValue DAGCombiner::visitADDE(SDNode *N) {
1613   SDValue N0 = N->getOperand(0);
1614   SDValue N1 = N->getOperand(1);
1615   SDValue CarryIn = N->getOperand(2);
1616   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1617   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1618
1619   // canonicalize constant to RHS
1620   if (N0C && !N1C)
1621     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1622                        N1, N0, CarryIn);
1623
1624   // fold (adde x, y, false) -> (addc x, y)
1625   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1626     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1627
1628   return SDValue();
1629 }
1630
1631 // Since it may not be valid to emit a fold to zero for vector initializers
1632 // check if we can before folding.
1633 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1634                              SelectionDAG &DAG,
1635                              bool LegalOperations, bool LegalTypes) {
1636   if (!VT.isVector())
1637     return DAG.getConstant(0, VT);
1638   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1639     return DAG.getConstant(0, VT);
1640   return SDValue();
1641 }
1642
1643 SDValue DAGCombiner::visitSUB(SDNode *N) {
1644   SDValue N0 = N->getOperand(0);
1645   SDValue N1 = N->getOperand(1);
1646   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1647   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1648   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1649     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1650   EVT VT = N0.getValueType();
1651
1652   // fold vector ops
1653   if (VT.isVector()) {
1654     SDValue FoldedVOp = SimplifyVBinOp(N);
1655     if (FoldedVOp.getNode()) return FoldedVOp;
1656
1657     // fold (sub x, 0) -> x, vector edition
1658     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1659       return N0;
1660   }
1661
1662   // fold (sub x, x) -> 0
1663   // FIXME: Refactor this and xor and other similar operations together.
1664   if (N0 == N1)
1665     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1666   // fold (sub c1, c2) -> c1-c2
1667   if (N0C && N1C)
1668     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1669   // fold (sub x, c) -> (add x, -c)
1670   if (N1C)
1671     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1672                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1673   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1674   if (N0C && N0C->isAllOnesValue())
1675     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1676   // fold A-(A-B) -> B
1677   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1678     return N1.getOperand(1);
1679   // fold (A+B)-A -> B
1680   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1681     return N0.getOperand(1);
1682   // fold (A+B)-B -> A
1683   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1684     return N0.getOperand(0);
1685   // fold C2-(A+C1) -> (C2-C1)-A
1686   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1687     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1688                                    VT);
1689     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1690                        N1.getOperand(0));
1691   }
1692   // fold ((A+(B+or-C))-B) -> A+or-C
1693   if (N0.getOpcode() == ISD::ADD &&
1694       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1695        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1696       N0.getOperand(1).getOperand(0) == N1)
1697     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1698                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1699   // fold ((A+(C+B))-B) -> A+C
1700   if (N0.getOpcode() == ISD::ADD &&
1701       N0.getOperand(1).getOpcode() == ISD::ADD &&
1702       N0.getOperand(1).getOperand(1) == N1)
1703     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1704                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1705   // fold ((A-(B-C))-C) -> A-B
1706   if (N0.getOpcode() == ISD::SUB &&
1707       N0.getOperand(1).getOpcode() == ISD::SUB &&
1708       N0.getOperand(1).getOperand(1) == N1)
1709     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1710                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1711
1712   // If either operand of a sub is undef, the result is undef
1713   if (N0.getOpcode() == ISD::UNDEF)
1714     return N0;
1715   if (N1.getOpcode() == ISD::UNDEF)
1716     return N1;
1717
1718   // If the relocation model supports it, consider symbol offsets.
1719   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1720     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1721       // fold (sub Sym, c) -> Sym-c
1722       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1723         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1724                                     GA->getOffset() -
1725                                       (uint64_t)N1C->getSExtValue());
1726       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1727       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1728         if (GA->getGlobal() == GB->getGlobal())
1729           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1730                                  VT);
1731     }
1732
1733   return SDValue();
1734 }
1735
1736 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1737   SDValue N0 = N->getOperand(0);
1738   SDValue N1 = N->getOperand(1);
1739   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1740   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1741   EVT VT = N0.getValueType();
1742
1743   // If the flag result is dead, turn this into an SUB.
1744   if (!N->hasAnyUseOfValue(1))
1745     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1746                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1747                                  MVT::Glue));
1748
1749   // fold (subc x, x) -> 0 + no borrow
1750   if (N0 == N1)
1751     return CombineTo(N, DAG.getConstant(0, VT),
1752                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1753                                  MVT::Glue));
1754
1755   // fold (subc x, 0) -> x + no borrow
1756   if (N1C && N1C->isNullValue())
1757     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1758                                         MVT::Glue));
1759
1760   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1761   if (N0C && N0C->isAllOnesValue())
1762     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1763                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1764                                  MVT::Glue));
1765
1766   return SDValue();
1767 }
1768
1769 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1770   SDValue N0 = N->getOperand(0);
1771   SDValue N1 = N->getOperand(1);
1772   SDValue CarryIn = N->getOperand(2);
1773
1774   // fold (sube x, y, false) -> (subc x, y)
1775   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1776     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1777
1778   return SDValue();
1779 }
1780
1781 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1782 /// elements are all the same constant or undefined.
1783 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1784   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1785   if (!C)
1786     return false;
1787
1788   APInt SplatUndef;
1789   unsigned SplatBitSize;
1790   bool HasAnyUndefs;
1791   EVT EltVT = N->getValueType(0).getVectorElementType();
1792   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1793                              HasAnyUndefs) &&
1794           EltVT.getSizeInBits() >= SplatBitSize);
1795 }
1796
1797 SDValue DAGCombiner::visitMUL(SDNode *N) {
1798   SDValue N0 = N->getOperand(0);
1799   SDValue N1 = N->getOperand(1);
1800   EVT VT = N0.getValueType();
1801
1802   // fold (mul x, undef) -> 0
1803   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1804     return DAG.getConstant(0, VT);
1805
1806   bool N0IsConst = false;
1807   bool N1IsConst = false;
1808   APInt ConstValue0, ConstValue1;
1809   // fold vector ops
1810   if (VT.isVector()) {
1811     SDValue FoldedVOp = SimplifyVBinOp(N);
1812     if (FoldedVOp.getNode()) return FoldedVOp;
1813
1814     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1815     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1816   } else {
1817     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1818     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1819                             : APInt();
1820     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1821     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1822                             : APInt();
1823   }
1824
1825   // fold (mul c1, c2) -> c1*c2
1826   if (N0IsConst && N1IsConst)
1827     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1828
1829   // canonicalize constant to RHS
1830   if (N0IsConst && !N1IsConst)
1831     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1832   // fold (mul x, 0) -> 0
1833   if (N1IsConst && ConstValue1 == 0)
1834     return N1;
1835   // We require a splat of the entire scalar bit width for non-contiguous
1836   // bit patterns.
1837   bool IsFullSplat =
1838     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1839   // fold (mul x, 1) -> x
1840   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1841     return N0;
1842   // fold (mul x, -1) -> 0-x
1843   if (N1IsConst && ConstValue1.isAllOnesValue())
1844     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1845                        DAG.getConstant(0, VT), N0);
1846   // fold (mul x, (1 << c)) -> x << c
1847   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1848     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1849                        DAG.getConstant(ConstValue1.logBase2(),
1850                                        getShiftAmountTy(N0.getValueType())));
1851   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1852   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1853     unsigned Log2Val = (-ConstValue1).logBase2();
1854     // FIXME: If the input is something that is easily negated (e.g. a
1855     // single-use add), we should put the negate there.
1856     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857                        DAG.getConstant(0, VT),
1858                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1859                             DAG.getConstant(Log2Val,
1860                                       getShiftAmountTy(N0.getValueType()))));
1861   }
1862
1863   APInt Val;
1864   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1865   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1866       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1867                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1868     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1869                              N1, N0.getOperand(1));
1870     AddToWorkList(C3.getNode());
1871     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1872                        N0.getOperand(0), C3);
1873   }
1874
1875   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1876   // use.
1877   {
1878     SDValue Sh(0,0), Y(0,0);
1879     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1880     if (N0.getOpcode() == ISD::SHL &&
1881         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1882                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1883         N0.getNode()->hasOneUse()) {
1884       Sh = N0; Y = N1;
1885     } else if (N1.getOpcode() == ISD::SHL &&
1886                isa<ConstantSDNode>(N1.getOperand(1)) &&
1887                N1.getNode()->hasOneUse()) {
1888       Sh = N1; Y = N0;
1889     }
1890
1891     if (Sh.getNode()) {
1892       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1893                                 Sh.getOperand(0), Y);
1894       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1895                          Mul, Sh.getOperand(1));
1896     }
1897   }
1898
1899   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1900   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1901       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1902                      isa<ConstantSDNode>(N0.getOperand(1))))
1903     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1904                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1905                                    N0.getOperand(0), N1),
1906                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1907                                    N0.getOperand(1), N1));
1908
1909   // reassociate mul
1910   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1911   if (RMUL.getNode() != 0)
1912     return RMUL;
1913
1914   return SDValue();
1915 }
1916
1917 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1918   SDValue N0 = N->getOperand(0);
1919   SDValue N1 = N->getOperand(1);
1920   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1921   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1922   EVT VT = N->getValueType(0);
1923
1924   // fold vector ops
1925   if (VT.isVector()) {
1926     SDValue FoldedVOp = SimplifyVBinOp(N);
1927     if (FoldedVOp.getNode()) return FoldedVOp;
1928   }
1929
1930   // fold (sdiv c1, c2) -> c1/c2
1931   if (N0C && N1C && !N1C->isNullValue())
1932     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1933   // fold (sdiv X, 1) -> X
1934   if (N1C && N1C->getAPIntValue() == 1LL)
1935     return N0;
1936   // fold (sdiv X, -1) -> 0-X
1937   if (N1C && N1C->isAllOnesValue())
1938     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1939                        DAG.getConstant(0, VT), N0);
1940   // If we know the sign bits of both operands are zero, strength reduce to a
1941   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1942   if (!VT.isVector()) {
1943     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1944       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1945                          N0, N1);
1946   }
1947   // fold (sdiv X, pow2) -> simple ops after legalize
1948   if (N1C && !N1C->isNullValue() &&
1949       (N1C->getAPIntValue().isPowerOf2() ||
1950        (-N1C->getAPIntValue()).isPowerOf2())) {
1951     // If dividing by powers of two is cheap, then don't perform the following
1952     // fold.
1953     if (TLI.isPow2DivCheap())
1954       return SDValue();
1955
1956     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1957
1958     // Splat the sign bit into the register
1959     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1960                               DAG.getConstant(VT.getSizeInBits()-1,
1961                                        getShiftAmountTy(N0.getValueType())));
1962     AddToWorkList(SGN.getNode());
1963
1964     // Add (N0 < 0) ? abs2 - 1 : 0;
1965     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1966                               DAG.getConstant(VT.getSizeInBits() - lg2,
1967                                        getShiftAmountTy(SGN.getValueType())));
1968     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1969     AddToWorkList(SRL.getNode());
1970     AddToWorkList(ADD.getNode());    // Divide by pow2
1971     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1972                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1973
1974     // If we're dividing by a positive value, we're done.  Otherwise, we must
1975     // negate the result.
1976     if (N1C->getAPIntValue().isNonNegative())
1977       return SRA;
1978
1979     AddToWorkList(SRA.getNode());
1980     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1981                        DAG.getConstant(0, VT), SRA);
1982   }
1983
1984   // if integer divide is expensive and we satisfy the requirements, emit an
1985   // alternate sequence.
1986   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1987     SDValue Op = BuildSDIV(N);
1988     if (Op.getNode()) return Op;
1989   }
1990
1991   // undef / X -> 0
1992   if (N0.getOpcode() == ISD::UNDEF)
1993     return DAG.getConstant(0, VT);
1994   // X / undef -> undef
1995   if (N1.getOpcode() == ISD::UNDEF)
1996     return N1;
1997
1998   return SDValue();
1999 }
2000
2001 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2002   SDValue N0 = N->getOperand(0);
2003   SDValue N1 = N->getOperand(1);
2004   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2005   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2006   EVT VT = N->getValueType(0);
2007
2008   // fold vector ops
2009   if (VT.isVector()) {
2010     SDValue FoldedVOp = SimplifyVBinOp(N);
2011     if (FoldedVOp.getNode()) return FoldedVOp;
2012   }
2013
2014   // fold (udiv c1, c2) -> c1/c2
2015   if (N0C && N1C && !N1C->isNullValue())
2016     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2017   // fold (udiv x, (1 << c)) -> x >>u c
2018   if (N1C && N1C->getAPIntValue().isPowerOf2())
2019     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2020                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2021                                        getShiftAmountTy(N0.getValueType())));
2022   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2023   if (N1.getOpcode() == ISD::SHL) {
2024     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2025       if (SHC->getAPIntValue().isPowerOf2()) {
2026         EVT ADDVT = N1.getOperand(1).getValueType();
2027         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2028                                   N1.getOperand(1),
2029                                   DAG.getConstant(SHC->getAPIntValue()
2030                                                                   .logBase2(),
2031                                                   ADDVT));
2032         AddToWorkList(Add.getNode());
2033         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2034       }
2035     }
2036   }
2037   // fold (udiv x, c) -> alternate
2038   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2039     SDValue Op = BuildUDIV(N);
2040     if (Op.getNode()) return Op;
2041   }
2042
2043   // undef / X -> 0
2044   if (N0.getOpcode() == ISD::UNDEF)
2045     return DAG.getConstant(0, VT);
2046   // X / undef -> undef
2047   if (N1.getOpcode() == ISD::UNDEF)
2048     return N1;
2049
2050   return SDValue();
2051 }
2052
2053 SDValue DAGCombiner::visitSREM(SDNode *N) {
2054   SDValue N0 = N->getOperand(0);
2055   SDValue N1 = N->getOperand(1);
2056   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2057   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2058   EVT VT = N->getValueType(0);
2059
2060   // fold (srem c1, c2) -> c1%c2
2061   if (N0C && N1C && !N1C->isNullValue())
2062     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2063   // If we know the sign bits of both operands are zero, strength reduce to a
2064   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2065   if (!VT.isVector()) {
2066     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2067       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2068   }
2069
2070   // If X/C can be simplified by the division-by-constant logic, lower
2071   // X%C to the equivalent of X-X/C*C.
2072   if (N1C && !N1C->isNullValue()) {
2073     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2074     AddToWorkList(Div.getNode());
2075     SDValue OptimizedDiv = combine(Div.getNode());
2076     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2077       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2078                                 OptimizedDiv, N1);
2079       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2080       AddToWorkList(Mul.getNode());
2081       return Sub;
2082     }
2083   }
2084
2085   // undef % X -> 0
2086   if (N0.getOpcode() == ISD::UNDEF)
2087     return DAG.getConstant(0, VT);
2088   // X % undef -> undef
2089   if (N1.getOpcode() == ISD::UNDEF)
2090     return N1;
2091
2092   return SDValue();
2093 }
2094
2095 SDValue DAGCombiner::visitUREM(SDNode *N) {
2096   SDValue N0 = N->getOperand(0);
2097   SDValue N1 = N->getOperand(1);
2098   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2099   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2100   EVT VT = N->getValueType(0);
2101
2102   // fold (urem c1, c2) -> c1%c2
2103   if (N0C && N1C && !N1C->isNullValue())
2104     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2105   // fold (urem x, pow2) -> (and x, pow2-1)
2106   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2107     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2108                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2109   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2110   if (N1.getOpcode() == ISD::SHL) {
2111     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2112       if (SHC->getAPIntValue().isPowerOf2()) {
2113         SDValue Add =
2114           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2115                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2116                                  VT));
2117         AddToWorkList(Add.getNode());
2118         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2119       }
2120     }
2121   }
2122
2123   // If X/C can be simplified by the division-by-constant logic, lower
2124   // X%C to the equivalent of X-X/C*C.
2125   if (N1C && !N1C->isNullValue()) {
2126     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2127     AddToWorkList(Div.getNode());
2128     SDValue OptimizedDiv = combine(Div.getNode());
2129     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2130       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2131                                 OptimizedDiv, N1);
2132       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2133       AddToWorkList(Mul.getNode());
2134       return Sub;
2135     }
2136   }
2137
2138   // undef % X -> 0
2139   if (N0.getOpcode() == ISD::UNDEF)
2140     return DAG.getConstant(0, VT);
2141   // X % undef -> undef
2142   if (N1.getOpcode() == ISD::UNDEF)
2143     return N1;
2144
2145   return SDValue();
2146 }
2147
2148 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2149   SDValue N0 = N->getOperand(0);
2150   SDValue N1 = N->getOperand(1);
2151   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2152   EVT VT = N->getValueType(0);
2153   SDLoc DL(N);
2154
2155   // fold (mulhs x, 0) -> 0
2156   if (N1C && N1C->isNullValue())
2157     return N1;
2158   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2159   if (N1C && N1C->getAPIntValue() == 1)
2160     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2161                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2162                                        getShiftAmountTy(N0.getValueType())));
2163   // fold (mulhs x, undef) -> 0
2164   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2165     return DAG.getConstant(0, VT);
2166
2167   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2168   // plus a shift.
2169   if (VT.isSimple() && !VT.isVector()) {
2170     MVT Simple = VT.getSimpleVT();
2171     unsigned SimpleSize = Simple.getSizeInBits();
2172     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2173     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2174       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2175       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2176       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2177       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2178             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2179       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2180     }
2181   }
2182
2183   return SDValue();
2184 }
2185
2186 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2187   SDValue N0 = N->getOperand(0);
2188   SDValue N1 = N->getOperand(1);
2189   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2190   EVT VT = N->getValueType(0);
2191   SDLoc DL(N);
2192
2193   // fold (mulhu x, 0) -> 0
2194   if (N1C && N1C->isNullValue())
2195     return N1;
2196   // fold (mulhu x, 1) -> 0
2197   if (N1C && N1C->getAPIntValue() == 1)
2198     return DAG.getConstant(0, N0.getValueType());
2199   // fold (mulhu x, undef) -> 0
2200   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2201     return DAG.getConstant(0, VT);
2202
2203   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2204   // plus a shift.
2205   if (VT.isSimple() && !VT.isVector()) {
2206     MVT Simple = VT.getSimpleVT();
2207     unsigned SimpleSize = Simple.getSizeInBits();
2208     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2209     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2210       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2211       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2212       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2213       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2214             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2215       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2216     }
2217   }
2218
2219   return SDValue();
2220 }
2221
2222 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2223 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2224 /// that are being performed. Return true if a simplification was made.
2225 ///
2226 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2227                                                 unsigned HiOp) {
2228   // If the high half is not needed, just compute the low half.
2229   bool HiExists = N->hasAnyUseOfValue(1);
2230   if (!HiExists &&
2231       (!LegalOperations ||
2232        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2233     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2234                               N->op_begin(), N->getNumOperands());
2235     return CombineTo(N, Res, Res);
2236   }
2237
2238   // If the low half is not needed, just compute the high half.
2239   bool LoExists = N->hasAnyUseOfValue(0);
2240   if (!LoExists &&
2241       (!LegalOperations ||
2242        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2243     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2244                               N->op_begin(), N->getNumOperands());
2245     return CombineTo(N, Res, Res);
2246   }
2247
2248   // If both halves are used, return as it is.
2249   if (LoExists && HiExists)
2250     return SDValue();
2251
2252   // If the two computed results can be simplified separately, separate them.
2253   if (LoExists) {
2254     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2255                              N->op_begin(), N->getNumOperands());
2256     AddToWorkList(Lo.getNode());
2257     SDValue LoOpt = combine(Lo.getNode());
2258     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2259         (!LegalOperations ||
2260          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2261       return CombineTo(N, LoOpt, LoOpt);
2262   }
2263
2264   if (HiExists) {
2265     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2266                              N->op_begin(), N->getNumOperands());
2267     AddToWorkList(Hi.getNode());
2268     SDValue HiOpt = combine(Hi.getNode());
2269     if (HiOpt.getNode() && HiOpt != Hi &&
2270         (!LegalOperations ||
2271          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2272       return CombineTo(N, HiOpt, HiOpt);
2273   }
2274
2275   return SDValue();
2276 }
2277
2278 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2279   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2280   if (Res.getNode()) return Res;
2281
2282   EVT VT = N->getValueType(0);
2283   SDLoc DL(N);
2284
2285   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2286   // plus a shift.
2287   if (VT.isSimple() && !VT.isVector()) {
2288     MVT Simple = VT.getSimpleVT();
2289     unsigned SimpleSize = Simple.getSizeInBits();
2290     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2291     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2292       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2293       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2294       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2295       // Compute the high part as N1.
2296       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2297             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2298       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2299       // Compute the low part as N0.
2300       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2301       return CombineTo(N, Lo, Hi);
2302     }
2303   }
2304
2305   return SDValue();
2306 }
2307
2308 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2309   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2310   if (Res.getNode()) return Res;
2311
2312   EVT VT = N->getValueType(0);
2313   SDLoc DL(N);
2314
2315   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2316   // plus a shift.
2317   if (VT.isSimple() && !VT.isVector()) {
2318     MVT Simple = VT.getSimpleVT();
2319     unsigned SimpleSize = Simple.getSizeInBits();
2320     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2323       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2324       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2325       // Compute the high part as N1.
2326       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2327             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2328       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2329       // Compute the low part as N0.
2330       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2331       return CombineTo(N, Lo, Hi);
2332     }
2333   }
2334
2335   return SDValue();
2336 }
2337
2338 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2339   // (smulo x, 2) -> (saddo x, x)
2340   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2341     if (C2->getAPIntValue() == 2)
2342       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2343                          N->getOperand(0), N->getOperand(0));
2344
2345   return SDValue();
2346 }
2347
2348 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2349   // (umulo x, 2) -> (uaddo x, x)
2350   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2351     if (C2->getAPIntValue() == 2)
2352       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2353                          N->getOperand(0), N->getOperand(0));
2354
2355   return SDValue();
2356 }
2357
2358 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2359   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2360   if (Res.getNode()) return Res;
2361
2362   return SDValue();
2363 }
2364
2365 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2366   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2367   if (Res.getNode()) return Res;
2368
2369   return SDValue();
2370 }
2371
2372 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2373 /// two operands of the same opcode, try to simplify it.
2374 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2375   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2376   EVT VT = N0.getValueType();
2377   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2378
2379   // Bail early if none of these transforms apply.
2380   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2381
2382   // For each of OP in AND/OR/XOR:
2383   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2384   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2385   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2386   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2387   //
2388   // do not sink logical op inside of a vector extend, since it may combine
2389   // into a vsetcc.
2390   EVT Op0VT = N0.getOperand(0).getValueType();
2391   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2392        N0.getOpcode() == ISD::SIGN_EXTEND ||
2393        // Avoid infinite looping with PromoteIntBinOp.
2394        (N0.getOpcode() == ISD::ANY_EXTEND &&
2395         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2396        (N0.getOpcode() == ISD::TRUNCATE &&
2397         (!TLI.isZExtFree(VT, Op0VT) ||
2398          !TLI.isTruncateFree(Op0VT, VT)) &&
2399         TLI.isTypeLegal(Op0VT))) &&
2400       !VT.isVector() &&
2401       Op0VT == N1.getOperand(0).getValueType() &&
2402       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2403     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2404                                  N0.getOperand(0).getValueType(),
2405                                  N0.getOperand(0), N1.getOperand(0));
2406     AddToWorkList(ORNode.getNode());
2407     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2408   }
2409
2410   // For each of OP in SHL/SRL/SRA/AND...
2411   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2412   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2413   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2414   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2415        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2416       N0.getOperand(1) == N1.getOperand(1)) {
2417     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2418                                  N0.getOperand(0).getValueType(),
2419                                  N0.getOperand(0), N1.getOperand(0));
2420     AddToWorkList(ORNode.getNode());
2421     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2422                        ORNode, N0.getOperand(1));
2423   }
2424
2425   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2426   // Only perform this optimization after type legalization and before
2427   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2428   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2429   // we don't want to undo this promotion.
2430   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2431   // on scalars.
2432   if ((N0.getOpcode() == ISD::BITCAST ||
2433        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2434       Level == AfterLegalizeTypes) {
2435     SDValue In0 = N0.getOperand(0);
2436     SDValue In1 = N1.getOperand(0);
2437     EVT In0Ty = In0.getValueType();
2438     EVT In1Ty = In1.getValueType();
2439     SDLoc DL(N);
2440     // If both incoming values are integers, and the original types are the
2441     // same.
2442     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2443       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2444       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2445       AddToWorkList(Op.getNode());
2446       return BC;
2447     }
2448   }
2449
2450   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2451   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2452   // If both shuffles use the same mask, and both shuffle within a single
2453   // vector, then it is worthwhile to move the swizzle after the operation.
2454   // The type-legalizer generates this pattern when loading illegal
2455   // vector types from memory. In many cases this allows additional shuffle
2456   // optimizations.
2457   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2458       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2459       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2460     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2461     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2462
2463     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2464            "Inputs to shuffles are not the same type");
2465
2466     unsigned NumElts = VT.getVectorNumElements();
2467
2468     // Check that both shuffles use the same mask. The masks are known to be of
2469     // the same length because the result vector type is the same.
2470     bool SameMask = true;
2471     for (unsigned i = 0; i != NumElts; ++i) {
2472       int Idx0 = SVN0->getMaskElt(i);
2473       int Idx1 = SVN1->getMaskElt(i);
2474       if (Idx0 != Idx1) {
2475         SameMask = false;
2476         break;
2477       }
2478     }
2479
2480     if (SameMask) {
2481       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2482                                N0.getOperand(0), N1.getOperand(0));
2483       AddToWorkList(Op.getNode());
2484       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2485                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2486     }
2487   }
2488
2489   return SDValue();
2490 }
2491
2492 SDValue DAGCombiner::visitAND(SDNode *N) {
2493   SDValue N0 = N->getOperand(0);
2494   SDValue N1 = N->getOperand(1);
2495   SDValue LL, LR, RL, RR, CC0, CC1;
2496   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2497   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2498   EVT VT = N1.getValueType();
2499   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2500
2501   // fold vector ops
2502   if (VT.isVector()) {
2503     SDValue FoldedVOp = SimplifyVBinOp(N);
2504     if (FoldedVOp.getNode()) return FoldedVOp;
2505
2506     // fold (and x, 0) -> 0, vector edition
2507     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2508       return N0;
2509     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2510       return N1;
2511
2512     // fold (and x, -1) -> x, vector edition
2513     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2514       return N1;
2515     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2516       return N0;
2517   }
2518
2519   // fold (and x, undef) -> 0
2520   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2521     return DAG.getConstant(0, VT);
2522   // fold (and c1, c2) -> c1&c2
2523   if (N0C && N1C)
2524     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2525   // canonicalize constant to RHS
2526   if (N0C && !N1C)
2527     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2528   // fold (and x, -1) -> x
2529   if (N1C && N1C->isAllOnesValue())
2530     return N0;
2531   // if (and x, c) is known to be zero, return 0
2532   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2533                                    APInt::getAllOnesValue(BitWidth)))
2534     return DAG.getConstant(0, VT);
2535   // reassociate and
2536   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2537   if (RAND.getNode() != 0)
2538     return RAND;
2539   // fold (and (or x, C), D) -> D if (C & D) == D
2540   if (N1C && N0.getOpcode() == ISD::OR)
2541     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2542       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2543         return N1;
2544   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2545   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2546     SDValue N0Op0 = N0.getOperand(0);
2547     APInt Mask = ~N1C->getAPIntValue();
2548     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2549     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2550       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2551                                  N0.getValueType(), N0Op0);
2552
2553       // Replace uses of the AND with uses of the Zero extend node.
2554       CombineTo(N, Zext);
2555
2556       // We actually want to replace all uses of the any_extend with the
2557       // zero_extend, to avoid duplicating things.  This will later cause this
2558       // AND to be folded.
2559       CombineTo(N0.getNode(), Zext);
2560       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2561     }
2562   }
2563   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2564   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2565   // already be zero by virtue of the width of the base type of the load.
2566   //
2567   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2568   // more cases.
2569   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2570        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2571       N0.getOpcode() == ISD::LOAD) {
2572     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2573                                          N0 : N0.getOperand(0) );
2574
2575     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2576     // This can be a pure constant or a vector splat, in which case we treat the
2577     // vector as a scalar and use the splat value.
2578     APInt Constant = APInt::getNullValue(1);
2579     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2580       Constant = C->getAPIntValue();
2581     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2582       APInt SplatValue, SplatUndef;
2583       unsigned SplatBitSize;
2584       bool HasAnyUndefs;
2585       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2586                                              SplatBitSize, HasAnyUndefs);
2587       if (IsSplat) {
2588         // Undef bits can contribute to a possible optimisation if set, so
2589         // set them.
2590         SplatValue |= SplatUndef;
2591
2592         // The splat value may be something like "0x00FFFFFF", which means 0 for
2593         // the first vector value and FF for the rest, repeating. We need a mask
2594         // that will apply equally to all members of the vector, so AND all the
2595         // lanes of the constant together.
2596         EVT VT = Vector->getValueType(0);
2597         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2598
2599         // If the splat value has been compressed to a bitlength lower
2600         // than the size of the vector lane, we need to re-expand it to
2601         // the lane size.
2602         if (BitWidth > SplatBitSize)
2603           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2604                SplatBitSize < BitWidth;
2605                SplatBitSize = SplatBitSize * 2)
2606             SplatValue |= SplatValue.shl(SplatBitSize);
2607
2608         Constant = APInt::getAllOnesValue(BitWidth);
2609         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2610           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2611       }
2612     }
2613
2614     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2615     // actually legal and isn't going to get expanded, else this is a false
2616     // optimisation.
2617     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2618                                                     Load->getMemoryVT());
2619
2620     // Resize the constant to the same size as the original memory access before
2621     // extension. If it is still the AllOnesValue then this AND is completely
2622     // unneeded.
2623     Constant =
2624       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2625
2626     bool B;
2627     switch (Load->getExtensionType()) {
2628     default: B = false; break;
2629     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2630     case ISD::ZEXTLOAD:
2631     case ISD::NON_EXTLOAD: B = true; break;
2632     }
2633
2634     if (B && Constant.isAllOnesValue()) {
2635       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2636       // preserve semantics once we get rid of the AND.
2637       SDValue NewLoad(Load, 0);
2638       if (Load->getExtensionType() == ISD::EXTLOAD) {
2639         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2640                               Load->getValueType(0), SDLoc(Load),
2641                               Load->getChain(), Load->getBasePtr(),
2642                               Load->getOffset(), Load->getMemoryVT(),
2643                               Load->getMemOperand());
2644         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2645         if (Load->getNumValues() == 3) {
2646           // PRE/POST_INC loads have 3 values.
2647           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2648                            NewLoad.getValue(2) };
2649           CombineTo(Load, To, 3, true);
2650         } else {
2651           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2652         }
2653       }
2654
2655       // Fold the AND away, taking care not to fold to the old load node if we
2656       // replaced it.
2657       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2658
2659       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2660     }
2661   }
2662   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2663   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2664     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2665     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2666
2667     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2668         LL.getValueType().isInteger()) {
2669       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2670       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2671         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2672                                      LR.getValueType(), LL, RL);
2673         AddToWorkList(ORNode.getNode());
2674         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2675       }
2676       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2677       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2678         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2679                                       LR.getValueType(), LL, RL);
2680         AddToWorkList(ANDNode.getNode());
2681         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2682       }
2683       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2684       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2685         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2686                                      LR.getValueType(), LL, RL);
2687         AddToWorkList(ORNode.getNode());
2688         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2689       }
2690     }
2691     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2692     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2693         Op0 == Op1 && LL.getValueType().isInteger() &&
2694       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2695                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2696                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2697                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2698       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2699                                     LL, DAG.getConstant(1, LL.getValueType()));
2700       AddToWorkList(ADDNode.getNode());
2701       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2702                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2703     }
2704     // canonicalize equivalent to ll == rl
2705     if (LL == RR && LR == RL) {
2706       Op1 = ISD::getSetCCSwappedOperands(Op1);
2707       std::swap(RL, RR);
2708     }
2709     if (LL == RL && LR == RR) {
2710       bool isInteger = LL.getValueType().isInteger();
2711       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2712       if (Result != ISD::SETCC_INVALID &&
2713           (!LegalOperations ||
2714            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2715             TLI.isOperationLegal(ISD::SETCC,
2716                             getSetCCResultType(N0.getSimpleValueType())))))
2717         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2718                             LL, LR, Result);
2719     }
2720   }
2721
2722   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2723   if (N0.getOpcode() == N1.getOpcode()) {
2724     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2725     if (Tmp.getNode()) return Tmp;
2726   }
2727
2728   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2729   // fold (and (sra)) -> (and (srl)) when possible.
2730   if (!VT.isVector() &&
2731       SimplifyDemandedBits(SDValue(N, 0)))
2732     return SDValue(N, 0);
2733
2734   // fold (zext_inreg (extload x)) -> (zextload x)
2735   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2736     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2737     EVT MemVT = LN0->getMemoryVT();
2738     // If we zero all the possible extended bits, then we can turn this into
2739     // a zextload if we are running before legalize or the operation is legal.
2740     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2741     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2742                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2743         ((!LegalOperations && !LN0->isVolatile()) ||
2744          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2745       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2746                                        LN0->getChain(), LN0->getBasePtr(),
2747                                        MemVT, LN0->getMemOperand());
2748       AddToWorkList(N);
2749       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2750       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2751     }
2752   }
2753   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2754   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2755       N0.hasOneUse()) {
2756     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2757     EVT MemVT = LN0->getMemoryVT();
2758     // If we zero all the possible extended bits, then we can turn this into
2759     // a zextload if we are running before legalize or the operation is legal.
2760     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2761     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2762                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2763         ((!LegalOperations && !LN0->isVolatile()) ||
2764          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2765       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2766                                        LN0->getChain(), LN0->getBasePtr(),
2767                                        MemVT, LN0->getMemOperand());
2768       AddToWorkList(N);
2769       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2770       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2771     }
2772   }
2773
2774   // fold (and (load x), 255) -> (zextload x, i8)
2775   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2776   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2777   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2778               (N0.getOpcode() == ISD::ANY_EXTEND &&
2779                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2780     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2781     LoadSDNode *LN0 = HasAnyExt
2782       ? cast<LoadSDNode>(N0.getOperand(0))
2783       : cast<LoadSDNode>(N0);
2784     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2785         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2786       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2787       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2788         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2789         EVT LoadedVT = LN0->getMemoryVT();
2790
2791         if (ExtVT == LoadedVT &&
2792             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2793           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2794
2795           SDValue NewLoad =
2796             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2797                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2798                            LN0->getMemOperand());
2799           AddToWorkList(N);
2800           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2801           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2802         }
2803
2804         // Do not change the width of a volatile load.
2805         // Do not generate loads of non-round integer types since these can
2806         // be expensive (and would be wrong if the type is not byte sized).
2807         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2808             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2809           EVT PtrType = LN0->getOperand(1).getValueType();
2810
2811           unsigned Alignment = LN0->getAlignment();
2812           SDValue NewPtr = LN0->getBasePtr();
2813
2814           // For big endian targets, we need to add an offset to the pointer
2815           // to load the correct bytes.  For little endian systems, we merely
2816           // need to read fewer bytes from the same pointer.
2817           if (TLI.isBigEndian()) {
2818             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2819             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2820             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2821             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2822                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2823             Alignment = MinAlign(Alignment, PtrOff);
2824           }
2825
2826           AddToWorkList(NewPtr.getNode());
2827
2828           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2829           SDValue Load =
2830             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2831                            LN0->getChain(), NewPtr,
2832                            LN0->getPointerInfo(),
2833                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2834                            Alignment, LN0->getTBAAInfo());
2835           AddToWorkList(N);
2836           CombineTo(LN0, Load, Load.getValue(1));
2837           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2838         }
2839       }
2840     }
2841   }
2842
2843   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2844       VT.getSizeInBits() <= 64) {
2845     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2846       APInt ADDC = ADDI->getAPIntValue();
2847       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2848         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2849         // immediate for an add, but it is legal if its top c2 bits are set,
2850         // transform the ADD so the immediate doesn't need to be materialized
2851         // in a register.
2852         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2853           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2854                                              SRLI->getZExtValue());
2855           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2856             ADDC |= Mask;
2857             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2858               SDValue NewAdd =
2859                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2860                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2861               CombineTo(N0.getNode(), NewAdd);
2862               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2863             }
2864           }
2865         }
2866       }
2867     }
2868   }
2869
2870   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2871   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2872     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2873                                        N0.getOperand(1), false);
2874     if (BSwap.getNode())
2875       return BSwap;
2876   }
2877
2878   return SDValue();
2879 }
2880
2881 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2882 ///
2883 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2884                                         bool DemandHighBits) {
2885   if (!LegalOperations)
2886     return SDValue();
2887
2888   EVT VT = N->getValueType(0);
2889   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2890     return SDValue();
2891   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2892     return SDValue();
2893
2894   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2895   bool LookPassAnd0 = false;
2896   bool LookPassAnd1 = false;
2897   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2898       std::swap(N0, N1);
2899   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2900       std::swap(N0, N1);
2901   if (N0.getOpcode() == ISD::AND) {
2902     if (!N0.getNode()->hasOneUse())
2903       return SDValue();
2904     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2905     if (!N01C || N01C->getZExtValue() != 0xFF00)
2906       return SDValue();
2907     N0 = N0.getOperand(0);
2908     LookPassAnd0 = true;
2909   }
2910
2911   if (N1.getOpcode() == ISD::AND) {
2912     if (!N1.getNode()->hasOneUse())
2913       return SDValue();
2914     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2915     if (!N11C || N11C->getZExtValue() != 0xFF)
2916       return SDValue();
2917     N1 = N1.getOperand(0);
2918     LookPassAnd1 = true;
2919   }
2920
2921   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2922     std::swap(N0, N1);
2923   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2924     return SDValue();
2925   if (!N0.getNode()->hasOneUse() ||
2926       !N1.getNode()->hasOneUse())
2927     return SDValue();
2928
2929   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2930   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2931   if (!N01C || !N11C)
2932     return SDValue();
2933   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2934     return SDValue();
2935
2936   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2937   SDValue N00 = N0->getOperand(0);
2938   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2939     if (!N00.getNode()->hasOneUse())
2940       return SDValue();
2941     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2942     if (!N001C || N001C->getZExtValue() != 0xFF)
2943       return SDValue();
2944     N00 = N00.getOperand(0);
2945     LookPassAnd0 = true;
2946   }
2947
2948   SDValue N10 = N1->getOperand(0);
2949   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2950     if (!N10.getNode()->hasOneUse())
2951       return SDValue();
2952     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2953     if (!N101C || N101C->getZExtValue() != 0xFF00)
2954       return SDValue();
2955     N10 = N10.getOperand(0);
2956     LookPassAnd1 = true;
2957   }
2958
2959   if (N00 != N10)
2960     return SDValue();
2961
2962   // Make sure everything beyond the low halfword gets set to zero since the SRL
2963   // 16 will clear the top bits.
2964   unsigned OpSizeInBits = VT.getSizeInBits();
2965   if (DemandHighBits && OpSizeInBits > 16) {
2966     // If the left-shift isn't masked out then the only way this is a bswap is
2967     // if all bits beyond the low 8 are 0. In that case the entire pattern
2968     // reduces to a left shift anyway: leave it for other parts of the combiner.
2969     if (!LookPassAnd0)
2970       return SDValue();
2971
2972     // However, if the right shift isn't masked out then it might be because
2973     // it's not needed. See if we can spot that too.
2974     if (!LookPassAnd1 &&
2975         !DAG.MaskedValueIsZero(
2976             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2977       return SDValue();
2978   }
2979
2980   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2981   if (OpSizeInBits > 16)
2982     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2983                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2984   return Res;
2985 }
2986
2987 /// isBSwapHWordElement - Return true if the specified node is an element
2988 /// that makes up a 32-bit packed halfword byteswap. i.e.
2989 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2990 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2991   if (!N.getNode()->hasOneUse())
2992     return false;
2993
2994   unsigned Opc = N.getOpcode();
2995   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2996     return false;
2997
2998   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2999   if (!N1C)
3000     return false;
3001
3002   unsigned Num;
3003   switch (N1C->getZExtValue()) {
3004   default:
3005     return false;
3006   case 0xFF:       Num = 0; break;
3007   case 0xFF00:     Num = 1; break;
3008   case 0xFF0000:   Num = 2; break;
3009   case 0xFF000000: Num = 3; break;
3010   }
3011
3012   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3013   SDValue N0 = N.getOperand(0);
3014   if (Opc == ISD::AND) {
3015     if (Num == 0 || Num == 2) {
3016       // (x >> 8) & 0xff
3017       // (x >> 8) & 0xff0000
3018       if (N0.getOpcode() != ISD::SRL)
3019         return false;
3020       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3021       if (!C || C->getZExtValue() != 8)
3022         return false;
3023     } else {
3024       // (x << 8) & 0xff00
3025       // (x << 8) & 0xff000000
3026       if (N0.getOpcode() != ISD::SHL)
3027         return false;
3028       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3029       if (!C || C->getZExtValue() != 8)
3030         return false;
3031     }
3032   } else if (Opc == ISD::SHL) {
3033     // (x & 0xff) << 8
3034     // (x & 0xff0000) << 8
3035     if (Num != 0 && Num != 2)
3036       return false;
3037     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3038     if (!C || C->getZExtValue() != 8)
3039       return false;
3040   } else { // Opc == ISD::SRL
3041     // (x & 0xff00) >> 8
3042     // (x & 0xff000000) >> 8
3043     if (Num != 1 && Num != 3)
3044       return false;
3045     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3046     if (!C || C->getZExtValue() != 8)
3047       return false;
3048   }
3049
3050   if (Parts[Num])
3051     return false;
3052
3053   Parts[Num] = N0.getOperand(0).getNode();
3054   return true;
3055 }
3056
3057 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3058 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3059 /// => (rotl (bswap x), 16)
3060 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3061   if (!LegalOperations)
3062     return SDValue();
3063
3064   EVT VT = N->getValueType(0);
3065   if (VT != MVT::i32)
3066     return SDValue();
3067   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3068     return SDValue();
3069
3070   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3071   // Look for either
3072   // (or (or (and), (and)), (or (and), (and)))
3073   // (or (or (or (and), (and)), (and)), (and))
3074   if (N0.getOpcode() != ISD::OR)
3075     return SDValue();
3076   SDValue N00 = N0.getOperand(0);
3077   SDValue N01 = N0.getOperand(1);
3078
3079   if (N1.getOpcode() == ISD::OR &&
3080       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3081     // (or (or (and), (and)), (or (and), (and)))
3082     SDValue N000 = N00.getOperand(0);
3083     if (!isBSwapHWordElement(N000, Parts))
3084       return SDValue();
3085
3086     SDValue N001 = N00.getOperand(1);
3087     if (!isBSwapHWordElement(N001, Parts))
3088       return SDValue();
3089     SDValue N010 = N01.getOperand(0);
3090     if (!isBSwapHWordElement(N010, Parts))
3091       return SDValue();
3092     SDValue N011 = N01.getOperand(1);
3093     if (!isBSwapHWordElement(N011, Parts))
3094       return SDValue();
3095   } else {
3096     // (or (or (or (and), (and)), (and)), (and))
3097     if (!isBSwapHWordElement(N1, Parts))
3098       return SDValue();
3099     if (!isBSwapHWordElement(N01, Parts))
3100       return SDValue();
3101     if (N00.getOpcode() != ISD::OR)
3102       return SDValue();
3103     SDValue N000 = N00.getOperand(0);
3104     if (!isBSwapHWordElement(N000, Parts))
3105       return SDValue();
3106     SDValue N001 = N00.getOperand(1);
3107     if (!isBSwapHWordElement(N001, Parts))
3108       return SDValue();
3109   }
3110
3111   // Make sure the parts are all coming from the same node.
3112   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3113     return SDValue();
3114
3115   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3116                               SDValue(Parts[0],0));
3117
3118   // Result of the bswap should be rotated by 16. If it's not legal, then
3119   // do  (x << 16) | (x >> 16).
3120   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3121   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3122     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3123   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3124     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3125   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3126                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3127                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3128 }
3129
3130 SDValue DAGCombiner::visitOR(SDNode *N) {
3131   SDValue N0 = N->getOperand(0);
3132   SDValue N1 = N->getOperand(1);
3133   SDValue LL, LR, RL, RR, CC0, CC1;
3134   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3135   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3136   EVT VT = N1.getValueType();
3137
3138   // fold vector ops
3139   if (VT.isVector()) {
3140     SDValue FoldedVOp = SimplifyVBinOp(N);
3141     if (FoldedVOp.getNode()) return FoldedVOp;
3142
3143     // fold (or x, 0) -> x, vector edition
3144     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3145       return N1;
3146     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3147       return N0;
3148
3149     // fold (or x, -1) -> -1, vector edition
3150     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3151       return N0;
3152     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3153       return N1;
3154   }
3155
3156   // fold (or x, undef) -> -1
3157   if (!LegalOperations &&
3158       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3159     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3160     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3161   }
3162   // fold (or c1, c2) -> c1|c2
3163   if (N0C && N1C)
3164     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3165   // canonicalize constant to RHS
3166   if (N0C && !N1C)
3167     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3168   // fold (or x, 0) -> x
3169   if (N1C && N1C->isNullValue())
3170     return N0;
3171   // fold (or x, -1) -> -1
3172   if (N1C && N1C->isAllOnesValue())
3173     return N1;
3174   // fold (or x, c) -> c iff (x & ~c) == 0
3175   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3176     return N1;
3177
3178   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3179   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3180   if (BSwap.getNode() != 0)
3181     return BSwap;
3182   BSwap = MatchBSwapHWordLow(N, N0, N1);
3183   if (BSwap.getNode() != 0)
3184     return BSwap;
3185
3186   // reassociate or
3187   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3188   if (ROR.getNode() != 0)
3189     return ROR;
3190   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3191   // iff (c1 & c2) == 0.
3192   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3193              isa<ConstantSDNode>(N0.getOperand(1))) {
3194     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3195     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3196       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3197                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3198                                      N0.getOperand(0), N1),
3199                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3200   }
3201   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3202   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3203     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3204     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3205
3206     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3207         LL.getValueType().isInteger()) {
3208       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3209       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3210       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3211           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3212         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3213                                      LR.getValueType(), LL, RL);
3214         AddToWorkList(ORNode.getNode());
3215         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3216       }
3217       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3218       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3219       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3220           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3221         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3222                                       LR.getValueType(), LL, RL);
3223         AddToWorkList(ANDNode.getNode());
3224         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3225       }
3226     }
3227     // canonicalize equivalent to ll == rl
3228     if (LL == RR && LR == RL) {
3229       Op1 = ISD::getSetCCSwappedOperands(Op1);
3230       std::swap(RL, RR);
3231     }
3232     if (LL == RL && LR == RR) {
3233       bool isInteger = LL.getValueType().isInteger();
3234       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3235       if (Result != ISD::SETCC_INVALID &&
3236           (!LegalOperations ||
3237            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3238             TLI.isOperationLegal(ISD::SETCC,
3239               getSetCCResultType(N0.getValueType())))))
3240         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3241                             LL, LR, Result);
3242     }
3243   }
3244
3245   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3246   if (N0.getOpcode() == N1.getOpcode()) {
3247     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3248     if (Tmp.getNode()) return Tmp;
3249   }
3250
3251   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3252   if (N0.getOpcode() == ISD::AND &&
3253       N1.getOpcode() == ISD::AND &&
3254       N0.getOperand(1).getOpcode() == ISD::Constant &&
3255       N1.getOperand(1).getOpcode() == ISD::Constant &&
3256       // Don't increase # computations.
3257       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3258     // We can only do this xform if we know that bits from X that are set in C2
3259     // but not in C1 are already zero.  Likewise for Y.
3260     const APInt &LHSMask =
3261       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3262     const APInt &RHSMask =
3263       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3264
3265     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3266         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3267       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3268                               N0.getOperand(0), N1.getOperand(0));
3269       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3270                          DAG.getConstant(LHSMask | RHSMask, VT));
3271     }
3272   }
3273
3274   // See if this is some rotate idiom.
3275   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3276     return SDValue(Rot, 0);
3277
3278   // Simplify the operands using demanded-bits information.
3279   if (!VT.isVector() &&
3280       SimplifyDemandedBits(SDValue(N, 0)))
3281     return SDValue(N, 0);
3282
3283   return SDValue();
3284 }
3285
3286 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3287 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3288   if (Op.getOpcode() == ISD::AND) {
3289     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3290       Mask = Op.getOperand(1);
3291       Op = Op.getOperand(0);
3292     } else {
3293       return false;
3294     }
3295   }
3296
3297   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3298     Shift = Op;
3299     return true;
3300   }
3301
3302   return false;
3303 }
3304
3305 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3306 // idioms for rotate, and if the target supports rotation instructions, generate
3307 // a rot[lr].
3308 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3309   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3310   EVT VT = LHS.getValueType();
3311   if (!TLI.isTypeLegal(VT)) return 0;
3312
3313   // The target must have at least one rotate flavor.
3314   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3315   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3316   if (!HasROTL && !HasROTR) return 0;
3317
3318   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3319   SDValue LHSShift;   // The shift.
3320   SDValue LHSMask;    // AND value if any.
3321   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3322     return 0; // Not part of a rotate.
3323
3324   SDValue RHSShift;   // The shift.
3325   SDValue RHSMask;    // AND value if any.
3326   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3327     return 0; // Not part of a rotate.
3328
3329   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3330     return 0;   // Not shifting the same value.
3331
3332   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3333     return 0;   // Shifts must disagree.
3334
3335   // Canonicalize shl to left side in a shl/srl pair.
3336   if (RHSShift.getOpcode() == ISD::SHL) {
3337     std::swap(LHS, RHS);
3338     std::swap(LHSShift, RHSShift);
3339     std::swap(LHSMask , RHSMask );
3340   }
3341
3342   unsigned OpSizeInBits = VT.getSizeInBits();
3343   SDValue LHSShiftArg = LHSShift.getOperand(0);
3344   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3345   SDValue RHSShiftArg = RHSShift.getOperand(0);
3346   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3347
3348   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3349   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3350   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3351       RHSShiftAmt.getOpcode() == ISD::Constant) {
3352     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3353     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3354     if ((LShVal + RShVal) != OpSizeInBits)
3355       return 0;
3356
3357     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3358                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3359
3360     // If there is an AND of either shifted operand, apply it to the result.
3361     if (LHSMask.getNode() || RHSMask.getNode()) {
3362       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3363
3364       if (LHSMask.getNode()) {
3365         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3366         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3367       }
3368       if (RHSMask.getNode()) {
3369         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3370         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3371       }
3372
3373       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3374     }
3375
3376     return Rot.getNode();
3377   }
3378
3379   // If there is a mask here, and we have a variable shift, we can't be sure
3380   // that we're masking out the right stuff.
3381   if (LHSMask.getNode() || RHSMask.getNode())
3382     return 0;
3383
3384   // If the shift amount is sign/zext/any-extended just peel it off.
3385   SDValue LExtOp0 = LHSShiftAmt;
3386   SDValue RExtOp0 = RHSShiftAmt;
3387   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3388        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3389        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3390        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3391       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3392        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3393        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3394        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3395     LExtOp0 = LHSShiftAmt.getOperand(0);
3396     RExtOp0 = RHSShiftAmt.getOperand(0);
3397   }
3398
3399   if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3400     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3401     //   (rotl x, y)
3402     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3403     //   (rotr x, (sub 32, y))
3404     if (ConstantSDNode *SUBC =
3405             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3406       if (SUBC->getAPIntValue() == OpSizeInBits) {
3407         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3408                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3409       } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3410                  LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3411         // fold (or (shl (*ext x), (*ext y)),
3412         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3413         //   (*ext (rotl x, y))
3414         // fold (or (shl (*ext x), (*ext y)),
3415         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3416         //   (*ext (rotr x, (sub 32, y)))
3417         SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3418         EVT LArgVT = LArgExtOp0.getValueType();
3419         bool HasROTRWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTR, LArgVT);
3420         bool HasROTLWithLArg = TLI.isOperationLegalOrCustom(ISD::ROTL, LArgVT);
3421         if (HasROTRWithLArg || HasROTLWithLArg) {
3422           if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3423             SDValue V =
3424                 DAG.getNode(HasROTLWithLArg ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3425                             LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3426             return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3427           }
3428         }
3429       }
3430     }
3431   } else if (LExtOp0.getOpcode() == ISD::SUB &&
3432              RExtOp0 == LExtOp0.getOperand(1)) {
3433     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3434     //   (rotr x, y)
3435     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3436     //   (rotl x, (sub 32, y))
3437     if (ConstantSDNode *SUBC =
3438             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3439       if (SUBC->getAPIntValue() == OpSizeInBits) {
3440         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3441                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3442       } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3443                  RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3444         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3445         //          (srl (*ext x), (*ext y))) ->
3446         //   (*ext (rotl x, y))
3447         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3448         //          (srl (*ext x), (*ext y))) ->
3449         //   (*ext (rotr x, (sub 32, y)))
3450         SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3451         EVT RArgVT = RArgExtOp0.getValueType();
3452         bool HasROTRWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTR, RArgVT);
3453         bool HasROTLWithRArg = TLI.isOperationLegalOrCustom(ISD::ROTL, RArgVT);
3454         if (HasROTRWithRArg || HasROTLWithRArg) {
3455           if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3456             SDValue V =
3457                 DAG.getNode(HasROTRWithRArg ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3458                             RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3459             return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3460           }
3461         }
3462       }
3463     }
3464   }
3465
3466   return 0;
3467 }
3468
3469 SDValue DAGCombiner::visitXOR(SDNode *N) {
3470   SDValue N0 = N->getOperand(0);
3471   SDValue N1 = N->getOperand(1);
3472   SDValue LHS, RHS, CC;
3473   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3474   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3475   EVT VT = N0.getValueType();
3476
3477   // fold vector ops
3478   if (VT.isVector()) {
3479     SDValue FoldedVOp = SimplifyVBinOp(N);
3480     if (FoldedVOp.getNode()) return FoldedVOp;
3481
3482     // fold (xor x, 0) -> x, vector edition
3483     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3484       return N1;
3485     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3486       return N0;
3487   }
3488
3489   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3490   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3491     return DAG.getConstant(0, VT);
3492   // fold (xor x, undef) -> undef
3493   if (N0.getOpcode() == ISD::UNDEF)
3494     return N0;
3495   if (N1.getOpcode() == ISD::UNDEF)
3496     return N1;
3497   // fold (xor c1, c2) -> c1^c2
3498   if (N0C && N1C)
3499     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3500   // canonicalize constant to RHS
3501   if (N0C && !N1C)
3502     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3503   // fold (xor x, 0) -> x
3504   if (N1C && N1C->isNullValue())
3505     return N0;
3506   // reassociate xor
3507   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3508   if (RXOR.getNode() != 0)
3509     return RXOR;
3510
3511   // fold !(x cc y) -> (x !cc y)
3512   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3513     bool isInt = LHS.getValueType().isInteger();
3514     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3515                                                isInt);
3516
3517     if (!LegalOperations ||
3518         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3519       switch (N0.getOpcode()) {
3520       default:
3521         llvm_unreachable("Unhandled SetCC Equivalent!");
3522       case ISD::SETCC:
3523         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3524       case ISD::SELECT_CC:
3525         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3526                                N0.getOperand(3), NotCC);
3527       }
3528     }
3529   }
3530
3531   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3532   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3533       N0.getNode()->hasOneUse() &&
3534       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3535     SDValue V = N0.getOperand(0);
3536     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3537                     DAG.getConstant(1, V.getValueType()));
3538     AddToWorkList(V.getNode());
3539     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3540   }
3541
3542   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3543   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3544       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3545     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3546     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3547       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3548       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3549       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3550       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3551       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3552     }
3553   }
3554   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3555   if (N1C && N1C->isAllOnesValue() &&
3556       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3557     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3558     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3559       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3560       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3561       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3562       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3563       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3564     }
3565   }
3566   // fold (xor (and x, y), y) -> (and (not x), y)
3567   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3568       N0->getOperand(1) == N1) {
3569     SDValue X = N0->getOperand(0);
3570     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3571     AddToWorkList(NotX.getNode());
3572     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3573   }
3574   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3575   if (N1C && N0.getOpcode() == ISD::XOR) {
3576     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3577     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3578     if (N00C)
3579       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3580                          DAG.getConstant(N1C->getAPIntValue() ^
3581                                          N00C->getAPIntValue(), VT));
3582     if (N01C)
3583       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3584                          DAG.getConstant(N1C->getAPIntValue() ^
3585                                          N01C->getAPIntValue(), VT));
3586   }
3587   // fold (xor x, x) -> 0
3588   if (N0 == N1)
3589     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3590
3591   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3592   if (N0.getOpcode() == N1.getOpcode()) {
3593     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3594     if (Tmp.getNode()) return Tmp;
3595   }
3596
3597   // Simplify the expression using non-local knowledge.
3598   if (!VT.isVector() &&
3599       SimplifyDemandedBits(SDValue(N, 0)))
3600     return SDValue(N, 0);
3601
3602   return SDValue();
3603 }
3604
3605 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3606 /// the shift amount is a constant.
3607 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3608   SDNode *LHS = N->getOperand(0).getNode();
3609   if (!LHS->hasOneUse()) return SDValue();
3610
3611   // We want to pull some binops through shifts, so that we have (and (shift))
3612   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3613   // thing happens with address calculations, so it's important to canonicalize
3614   // it.
3615   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3616
3617   switch (LHS->getOpcode()) {
3618   default: return SDValue();
3619   case ISD::OR:
3620   case ISD::XOR:
3621     HighBitSet = false; // We can only transform sra if the high bit is clear.
3622     break;
3623   case ISD::AND:
3624     HighBitSet = true;  // We can only transform sra if the high bit is set.
3625     break;
3626   case ISD::ADD:
3627     if (N->getOpcode() != ISD::SHL)
3628       return SDValue(); // only shl(add) not sr[al](add).
3629     HighBitSet = false; // We can only transform sra if the high bit is clear.
3630     break;
3631   }
3632
3633   // We require the RHS of the binop to be a constant as well.
3634   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3635   if (!BinOpCst) return SDValue();
3636
3637   // FIXME: disable this unless the input to the binop is a shift by a constant.
3638   // If it is not a shift, it pessimizes some common cases like:
3639   //
3640   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3641   //    int bar(int *X, int i) { return X[i & 255]; }
3642   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3643   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3644        BinOpLHSVal->getOpcode() != ISD::SRA &&
3645        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3646       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3647     return SDValue();
3648
3649   EVT VT = N->getValueType(0);
3650
3651   // If this is a signed shift right, and the high bit is modified by the
3652   // logical operation, do not perform the transformation. The highBitSet
3653   // boolean indicates the value of the high bit of the constant which would
3654   // cause it to be modified for this operation.
3655   if (N->getOpcode() == ISD::SRA) {
3656     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3657     if (BinOpRHSSignSet != HighBitSet)
3658       return SDValue();
3659   }
3660
3661   // Fold the constants, shifting the binop RHS by the shift amount.
3662   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3663                                N->getValueType(0),
3664                                LHS->getOperand(1), N->getOperand(1));
3665
3666   // Create the new shift.
3667   SDValue NewShift = DAG.getNode(N->getOpcode(),
3668                                  SDLoc(LHS->getOperand(0)),
3669                                  VT, LHS->getOperand(0), N->getOperand(1));
3670
3671   // Create the new binop.
3672   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3673 }
3674
3675 SDValue DAGCombiner::visitSHL(SDNode *N) {
3676   SDValue N0 = N->getOperand(0);
3677   SDValue N1 = N->getOperand(1);
3678   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3679   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3680   EVT VT = N0.getValueType();
3681   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3682
3683   // fold vector ops
3684   if (VT.isVector()) {
3685     SDValue FoldedVOp = SimplifyVBinOp(N);
3686     if (FoldedVOp.getNode()) return FoldedVOp;
3687   }
3688
3689   // fold (shl c1, c2) -> c1<<c2
3690   if (N0C && N1C)
3691     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3692   // fold (shl 0, x) -> 0
3693   if (N0C && N0C->isNullValue())
3694     return N0;
3695   // fold (shl x, c >= size(x)) -> undef
3696   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3697     return DAG.getUNDEF(VT);
3698   // fold (shl x, 0) -> x
3699   if (N1C && N1C->isNullValue())
3700     return N0;
3701   // fold (shl undef, x) -> 0
3702   if (N0.getOpcode() == ISD::UNDEF)
3703     return DAG.getConstant(0, VT);
3704   // if (shl x, c) is known to be zero, return 0
3705   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3706                             APInt::getAllOnesValue(OpSizeInBits)))
3707     return DAG.getConstant(0, VT);
3708   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3709   if (N1.getOpcode() == ISD::TRUNCATE &&
3710       N1.getOperand(0).getOpcode() == ISD::AND &&
3711       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3712     SDValue N101 = N1.getOperand(0).getOperand(1);
3713     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3714       EVT TruncVT = N1.getValueType();
3715       SDValue N100 = N1.getOperand(0).getOperand(0);
3716       APInt TruncC = N101C->getAPIntValue();
3717       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3718       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3719                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3720                                      DAG.getNode(ISD::TRUNCATE,
3721                                                  SDLoc(N),
3722                                                  TruncVT, N100),
3723                                      DAG.getConstant(TruncC, TruncVT)));
3724     }
3725   }
3726
3727   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3728     return SDValue(N, 0);
3729
3730   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3731   if (N1C && N0.getOpcode() == ISD::SHL &&
3732       N0.getOperand(1).getOpcode() == ISD::Constant) {
3733     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3734     uint64_t c2 = N1C->getZExtValue();
3735     if (c1 + c2 >= OpSizeInBits)
3736       return DAG.getConstant(0, VT);
3737     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3738                        DAG.getConstant(c1 + c2, N1.getValueType()));
3739   }
3740
3741   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3742   // For this to be valid, the second form must not preserve any of the bits
3743   // that are shifted out by the inner shift in the first form.  This means
3744   // the outer shift size must be >= the number of bits added by the ext.
3745   // As a corollary, we don't care what kind of ext it is.
3746   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3747               N0.getOpcode() == ISD::ANY_EXTEND ||
3748               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3749       N0.getOperand(0).getOpcode() == ISD::SHL &&
3750       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3751     uint64_t c1 =
3752       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3753     uint64_t c2 = N1C->getZExtValue();
3754     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3755     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3756     if (c2 >= OpSizeInBits - InnerShiftSize) {
3757       if (c1 + c2 >= OpSizeInBits)
3758         return DAG.getConstant(0, VT);
3759       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3760                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3761                                      N0.getOperand(0)->getOperand(0)),
3762                          DAG.getConstant(c1 + c2, N1.getValueType()));
3763     }
3764   }
3765
3766   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3767   // Only fold this if the inner zext has no other uses to avoid increasing
3768   // the total number of instructions.
3769   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3770       N0.getOperand(0).getOpcode() == ISD::SRL &&
3771       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3772     uint64_t c1 =
3773       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3774     if (c1 < VT.getSizeInBits()) {
3775       uint64_t c2 = N1C->getZExtValue();
3776       if (c1 == c2) {
3777         SDValue NewOp0 = N0.getOperand(0);
3778         EVT CountVT = NewOp0.getOperand(1).getValueType();
3779         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3780                                      NewOp0, DAG.getConstant(c2, CountVT));
3781         AddToWorkList(NewSHL.getNode());
3782         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3783       }
3784     }
3785   }
3786
3787   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3788   //                               (and (srl x, (sub c1, c2), MASK)
3789   // Only fold this if the inner shift has no other uses -- if it does, folding
3790   // this will increase the total number of instructions.
3791   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3792       N0.getOperand(1).getOpcode() == ISD::Constant) {
3793     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3794     if (c1 < VT.getSizeInBits()) {
3795       uint64_t c2 = N1C->getZExtValue();
3796       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3797                                          VT.getSizeInBits() - c1);
3798       SDValue Shift;
3799       if (c2 > c1) {
3800         Mask = Mask.shl(c2-c1);
3801         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3802                             DAG.getConstant(c2-c1, N1.getValueType()));
3803       } else {
3804         Mask = Mask.lshr(c1-c2);
3805         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3806                             DAG.getConstant(c1-c2, N1.getValueType()));
3807       }
3808       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3809                          DAG.getConstant(Mask, VT));
3810     }
3811   }
3812   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3813   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3814     SDValue HiBitsMask =
3815       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3816                                             VT.getSizeInBits() -
3817                                               N1C->getZExtValue()),
3818                       VT);
3819     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3820                        HiBitsMask);
3821   }
3822
3823   if (N1C) {
3824     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3825     if (NewSHL.getNode())
3826       return NewSHL;
3827   }
3828
3829   return SDValue();
3830 }
3831
3832 SDValue DAGCombiner::visitSRA(SDNode *N) {
3833   SDValue N0 = N->getOperand(0);
3834   SDValue N1 = N->getOperand(1);
3835   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3836   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3837   EVT VT = N0.getValueType();
3838   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3839
3840   // fold vector ops
3841   if (VT.isVector()) {
3842     SDValue FoldedVOp = SimplifyVBinOp(N);
3843     if (FoldedVOp.getNode()) return FoldedVOp;
3844   }
3845
3846   // fold (sra c1, c2) -> (sra c1, c2)
3847   if (N0C && N1C)
3848     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3849   // fold (sra 0, x) -> 0
3850   if (N0C && N0C->isNullValue())
3851     return N0;
3852   // fold (sra -1, x) -> -1
3853   if (N0C && N0C->isAllOnesValue())
3854     return N0;
3855   // fold (sra x, (setge c, size(x))) -> undef
3856   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3857     return DAG.getUNDEF(VT);
3858   // fold (sra x, 0) -> x
3859   if (N1C && N1C->isNullValue())
3860     return N0;
3861   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3862   // sext_inreg.
3863   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3864     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3865     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3866     if (VT.isVector())
3867       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3868                                ExtVT, VT.getVectorNumElements());
3869     if ((!LegalOperations ||
3870          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3871       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3872                          N0.getOperand(0), DAG.getValueType(ExtVT));
3873   }
3874
3875   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3876   if (N1C && N0.getOpcode() == ISD::SRA) {
3877     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3878       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3879       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3880       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3881                          DAG.getConstant(Sum, N1C->getValueType(0)));
3882     }
3883   }
3884
3885   // fold (sra (shl X, m), (sub result_size, n))
3886   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3887   // result_size - n != m.
3888   // If truncate is free for the target sext(shl) is likely to result in better
3889   // code.
3890   if (N0.getOpcode() == ISD::SHL) {
3891     // Get the two constanst of the shifts, CN0 = m, CN = n.
3892     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3893     if (N01C && N1C) {
3894       // Determine what the truncate's result bitsize and type would be.
3895       EVT TruncVT =
3896         EVT::getIntegerVT(*DAG.getContext(),
3897                           OpSizeInBits - N1C->getZExtValue());
3898       // Determine the residual right-shift amount.
3899       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3900
3901       // If the shift is not a no-op (in which case this should be just a sign
3902       // extend already), the truncated to type is legal, sign_extend is legal
3903       // on that type, and the truncate to that type is both legal and free,
3904       // perform the transform.
3905       if ((ShiftAmt > 0) &&
3906           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3907           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3908           TLI.isTruncateFree(VT, TruncVT)) {
3909
3910           SDValue Amt = DAG.getConstant(ShiftAmt,
3911               getShiftAmountTy(N0.getOperand(0).getValueType()));
3912           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3913                                       N0.getOperand(0), Amt);
3914           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3915                                       Shift);
3916           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3917                              N->getValueType(0), Trunc);
3918       }
3919     }
3920   }
3921
3922   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3923   if (N1.getOpcode() == ISD::TRUNCATE &&
3924       N1.getOperand(0).getOpcode() == ISD::AND &&
3925       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3926     SDValue N101 = N1.getOperand(0).getOperand(1);
3927     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3928       EVT TruncVT = N1.getValueType();
3929       SDValue N100 = N1.getOperand(0).getOperand(0);
3930       APInt TruncC = N101C->getAPIntValue();
3931       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3932       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3933                          DAG.getNode(ISD::AND, SDLoc(N),
3934                                      TruncVT,
3935                                      DAG.getNode(ISD::TRUNCATE,
3936                                                  SDLoc(N),
3937                                                  TruncVT, N100),
3938                                      DAG.getConstant(TruncC, TruncVT)));
3939     }
3940   }
3941
3942   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3943   //      if c1 is equal to the number of bits the trunc removes
3944   if (N0.getOpcode() == ISD::TRUNCATE &&
3945       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3946        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3947       N0.getOperand(0).hasOneUse() &&
3948       N0.getOperand(0).getOperand(1).hasOneUse() &&
3949       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3950     EVT LargeVT = N0.getOperand(0).getValueType();
3951     ConstantSDNode *LargeShiftAmt =
3952       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3953
3954     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3955         LargeShiftAmt->getZExtValue()) {
3956       SDValue Amt =
3957         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3958               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3959       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3960                                 N0.getOperand(0).getOperand(0), Amt);
3961       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3962     }
3963   }
3964
3965   // Simplify, based on bits shifted out of the LHS.
3966   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3967     return SDValue(N, 0);
3968
3969
3970   // If the sign bit is known to be zero, switch this to a SRL.
3971   if (DAG.SignBitIsZero(N0))
3972     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3973
3974   if (N1C) {
3975     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3976     if (NewSRA.getNode())
3977       return NewSRA;
3978   }
3979
3980   return SDValue();
3981 }
3982
3983 SDValue DAGCombiner::visitSRL(SDNode *N) {
3984   SDValue N0 = N->getOperand(0);
3985   SDValue N1 = N->getOperand(1);
3986   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3987   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3988   EVT VT = N0.getValueType();
3989   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3990
3991   // fold vector ops
3992   if (VT.isVector()) {
3993     SDValue FoldedVOp = SimplifyVBinOp(N);
3994     if (FoldedVOp.getNode()) return FoldedVOp;
3995   }
3996
3997   // fold (srl c1, c2) -> c1 >>u c2
3998   if (N0C && N1C)
3999     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4000   // fold (srl 0, x) -> 0
4001   if (N0C && N0C->isNullValue())
4002     return N0;
4003   // fold (srl x, c >= size(x)) -> undef
4004   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4005     return DAG.getUNDEF(VT);
4006   // fold (srl x, 0) -> x
4007   if (N1C && N1C->isNullValue())
4008     return N0;
4009   // if (srl x, c) is known to be zero, return 0
4010   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4011                                    APInt::getAllOnesValue(OpSizeInBits)))
4012     return DAG.getConstant(0, VT);
4013
4014   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4015   if (N1C && N0.getOpcode() == ISD::SRL &&
4016       N0.getOperand(1).getOpcode() == ISD::Constant) {
4017     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4018     uint64_t c2 = N1C->getZExtValue();
4019     if (c1 + c2 >= OpSizeInBits)
4020       return DAG.getConstant(0, VT);
4021     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4022                        DAG.getConstant(c1 + c2, N1.getValueType()));
4023   }
4024
4025   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4026   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4027       N0.getOperand(0).getOpcode() == ISD::SRL &&
4028       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4029     uint64_t c1 =
4030       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4031     uint64_t c2 = N1C->getZExtValue();
4032     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4033     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4034     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4035     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4036     if (c1 + OpSizeInBits == InnerShiftSize) {
4037       if (c1 + c2 >= InnerShiftSize)
4038         return DAG.getConstant(0, VT);
4039       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4040                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4041                                      N0.getOperand(0)->getOperand(0),
4042                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4043     }
4044   }
4045
4046   // fold (srl (shl x, c), c) -> (and x, cst2)
4047   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4048       N0.getValueSizeInBits() <= 64) {
4049     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4050     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4051                        DAG.getConstant(~0ULL >> ShAmt, VT));
4052   }
4053
4054   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4055   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4056     // Shifting in all undef bits?
4057     EVT SmallVT = N0.getOperand(0).getValueType();
4058     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4059       return DAG.getUNDEF(VT);
4060
4061     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4062       uint64_t ShiftAmt = N1C->getZExtValue();
4063       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4064                                        N0.getOperand(0),
4065                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4066       AddToWorkList(SmallShift.getNode());
4067       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4068       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4069                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4070                          DAG.getConstant(Mask, VT));
4071     }
4072   }
4073
4074   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4075   // bit, which is unmodified by sra.
4076   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4077     if (N0.getOpcode() == ISD::SRA)
4078       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4079   }
4080
4081   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4082   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4083       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4084     APInt KnownZero, KnownOne;
4085     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4086
4087     // If any of the input bits are KnownOne, then the input couldn't be all
4088     // zeros, thus the result of the srl will always be zero.
4089     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4090
4091     // If all of the bits input the to ctlz node are known to be zero, then
4092     // the result of the ctlz is "32" and the result of the shift is one.
4093     APInt UnknownBits = ~KnownZero;
4094     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4095
4096     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4097     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4098       // Okay, we know that only that the single bit specified by UnknownBits
4099       // could be set on input to the CTLZ node. If this bit is set, the SRL
4100       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4101       // to an SRL/XOR pair, which is likely to simplify more.
4102       unsigned ShAmt = UnknownBits.countTrailingZeros();
4103       SDValue Op = N0.getOperand(0);
4104
4105       if (ShAmt) {
4106         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4107                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4108         AddToWorkList(Op.getNode());
4109       }
4110
4111       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4112                          Op, DAG.getConstant(1, VT));
4113     }
4114   }
4115
4116   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4117   if (N1.getOpcode() == ISD::TRUNCATE &&
4118       N1.getOperand(0).getOpcode() == ISD::AND &&
4119       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4120     SDValue N101 = N1.getOperand(0).getOperand(1);
4121     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4122       EVT TruncVT = N1.getValueType();
4123       SDValue N100 = N1.getOperand(0).getOperand(0);
4124       APInt TruncC = N101C->getAPIntValue();
4125       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4126       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4127                          DAG.getNode(ISD::AND, SDLoc(N),
4128                                      TruncVT,
4129                                      DAG.getNode(ISD::TRUNCATE,
4130                                                  SDLoc(N),
4131                                                  TruncVT, N100),
4132                                      DAG.getConstant(TruncC, TruncVT)));
4133     }
4134   }
4135
4136   // fold operands of srl based on knowledge that the low bits are not
4137   // demanded.
4138   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4139     return SDValue(N, 0);
4140
4141   if (N1C) {
4142     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4143     if (NewSRL.getNode())
4144       return NewSRL;
4145   }
4146
4147   // Attempt to convert a srl of a load into a narrower zero-extending load.
4148   SDValue NarrowLoad = ReduceLoadWidth(N);
4149   if (NarrowLoad.getNode())
4150     return NarrowLoad;
4151
4152   // Here is a common situation. We want to optimize:
4153   //
4154   //   %a = ...
4155   //   %b = and i32 %a, 2
4156   //   %c = srl i32 %b, 1
4157   //   brcond i32 %c ...
4158   //
4159   // into
4160   //
4161   //   %a = ...
4162   //   %b = and %a, 2
4163   //   %c = setcc eq %b, 0
4164   //   brcond %c ...
4165   //
4166   // However when after the source operand of SRL is optimized into AND, the SRL
4167   // itself may not be optimized further. Look for it and add the BRCOND into
4168   // the worklist.
4169   if (N->hasOneUse()) {
4170     SDNode *Use = *N->use_begin();
4171     if (Use->getOpcode() == ISD::BRCOND)
4172       AddToWorkList(Use);
4173     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4174       // Also look pass the truncate.
4175       Use = *Use->use_begin();
4176       if (Use->getOpcode() == ISD::BRCOND)
4177         AddToWorkList(Use);
4178     }
4179   }
4180
4181   return SDValue();
4182 }
4183
4184 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4185   SDValue N0 = N->getOperand(0);
4186   EVT VT = N->getValueType(0);
4187
4188   // fold (ctlz c1) -> c2
4189   if (isa<ConstantSDNode>(N0))
4190     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4191   return SDValue();
4192 }
4193
4194 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4195   SDValue N0 = N->getOperand(0);
4196   EVT VT = N->getValueType(0);
4197
4198   // fold (ctlz_zero_undef c1) -> c2
4199   if (isa<ConstantSDNode>(N0))
4200     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4201   return SDValue();
4202 }
4203
4204 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4205   SDValue N0 = N->getOperand(0);
4206   EVT VT = N->getValueType(0);
4207
4208   // fold (cttz c1) -> c2
4209   if (isa<ConstantSDNode>(N0))
4210     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4211   return SDValue();
4212 }
4213
4214 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4215   SDValue N0 = N->getOperand(0);
4216   EVT VT = N->getValueType(0);
4217
4218   // fold (cttz_zero_undef c1) -> c2
4219   if (isa<ConstantSDNode>(N0))
4220     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4221   return SDValue();
4222 }
4223
4224 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4225   SDValue N0 = N->getOperand(0);
4226   EVT VT = N->getValueType(0);
4227
4228   // fold (ctpop c1) -> c2
4229   if (isa<ConstantSDNode>(N0))
4230     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4231   return SDValue();
4232 }
4233
4234 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4235   SDValue N0 = N->getOperand(0);
4236   SDValue N1 = N->getOperand(1);
4237   SDValue N2 = N->getOperand(2);
4238   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4239   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4240   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4241   EVT VT = N->getValueType(0);
4242   EVT VT0 = N0.getValueType();
4243
4244   // fold (select C, X, X) -> X
4245   if (N1 == N2)
4246     return N1;
4247   // fold (select true, X, Y) -> X
4248   if (N0C && !N0C->isNullValue())
4249     return N1;
4250   // fold (select false, X, Y) -> Y
4251   if (N0C && N0C->isNullValue())
4252     return N2;
4253   // fold (select C, 1, X) -> (or C, X)
4254   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4255     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4256   // fold (select C, 0, 1) -> (xor C, 1)
4257   if (VT.isInteger() &&
4258       (VT0 == MVT::i1 ||
4259        (VT0.isInteger() &&
4260         TLI.getBooleanContents(false) ==
4261         TargetLowering::ZeroOrOneBooleanContent)) &&
4262       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4263     SDValue XORNode;
4264     if (VT == VT0)
4265       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4266                          N0, DAG.getConstant(1, VT0));
4267     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4268                           N0, DAG.getConstant(1, VT0));
4269     AddToWorkList(XORNode.getNode());
4270     if (VT.bitsGT(VT0))
4271       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4272     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4273   }
4274   // fold (select C, 0, X) -> (and (not C), X)
4275   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4276     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4277     AddToWorkList(NOTNode.getNode());
4278     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4279   }
4280   // fold (select C, X, 1) -> (or (not C), X)
4281   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4282     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4283     AddToWorkList(NOTNode.getNode());
4284     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4285   }
4286   // fold (select C, X, 0) -> (and C, X)
4287   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4288     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4289   // fold (select X, X, Y) -> (or X, Y)
4290   // fold (select X, 1, Y) -> (or X, Y)
4291   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4292     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4293   // fold (select X, Y, X) -> (and X, Y)
4294   // fold (select X, Y, 0) -> (and X, Y)
4295   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4296     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4297
4298   // If we can fold this based on the true/false value, do so.
4299   if (SimplifySelectOps(N, N1, N2))
4300     return SDValue(N, 0);  // Don't revisit N.
4301
4302   // fold selects based on a setcc into other things, such as min/max/abs
4303   if (N0.getOpcode() == ISD::SETCC) {
4304     // FIXME:
4305     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4306     // having to say they don't support SELECT_CC on every type the DAG knows
4307     // about, since there is no way to mark an opcode illegal at all value types
4308     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4309         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4310       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4311                          N0.getOperand(0), N0.getOperand(1),
4312                          N1, N2, N0.getOperand(2));
4313     return SimplifySelect(SDLoc(N), N0, N1, N2);
4314   }
4315
4316   return SDValue();
4317 }
4318
4319 static
4320 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4321   SDLoc DL(N);
4322   EVT LoVT, HiVT;
4323   llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4324
4325   // Split the inputs.
4326   SDValue Lo, Hi, LL, LH, RL, RH;
4327   llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4328   llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4329
4330   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4331   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4332
4333   return std::make_pair(Lo, Hi);
4334 }
4335
4336 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4337   SDValue N0 = N->getOperand(0);
4338   SDValue N1 = N->getOperand(1);
4339   SDValue N2 = N->getOperand(2);
4340   SDLoc DL(N);
4341
4342   // Canonicalize integer abs.
4343   // vselect (setg[te] X,  0),  X, -X ->
4344   // vselect (setgt    X, -1),  X, -X ->
4345   // vselect (setl[te] X,  0), -X,  X ->
4346   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4347   if (N0.getOpcode() == ISD::SETCC) {
4348     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4349     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4350     bool isAbs = false;
4351     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4352
4353     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4354          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4355         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4356       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4357     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4358              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4359       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4360
4361     if (isAbs) {
4362       EVT VT = LHS.getValueType();
4363       SDValue Shift = DAG.getNode(
4364           ISD::SRA, DL, VT, LHS,
4365           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4366       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4367       AddToWorkList(Shift.getNode());
4368       AddToWorkList(Add.getNode());
4369       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4370     }
4371   }
4372
4373   // If the VSELECT result requires splitting and the mask is provided by a
4374   // SETCC, then split both nodes and its operands before legalization. This
4375   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4376   // and enables future optimizations (e.g. min/max pattern matching on X86).
4377   if (N0.getOpcode() == ISD::SETCC) {
4378     EVT VT = N->getValueType(0);
4379
4380     // Check if any splitting is required.
4381     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4382         TargetLowering::TypeSplitVector)
4383       return SDValue();
4384
4385     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4386     llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4387     llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4388     llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4389
4390     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4391     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4392
4393     // Add the new VSELECT nodes to the work list in case they need to be split
4394     // again.
4395     AddToWorkList(Lo.getNode());
4396     AddToWorkList(Hi.getNode());
4397
4398     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4399   }
4400
4401   return SDValue();
4402 }
4403
4404 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4405   SDValue N0 = N->getOperand(0);
4406   SDValue N1 = N->getOperand(1);
4407   SDValue N2 = N->getOperand(2);
4408   SDValue N3 = N->getOperand(3);
4409   SDValue N4 = N->getOperand(4);
4410   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4411
4412   // fold select_cc lhs, rhs, x, x, cc -> x
4413   if (N2 == N3)
4414     return N2;
4415
4416   // Determine if the condition we're dealing with is constant
4417   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4418                               N0, N1, CC, SDLoc(N), false);
4419   if (SCC.getNode()) {
4420     AddToWorkList(SCC.getNode());
4421
4422     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4423       if (!SCCC->isNullValue())
4424         return N2;    // cond always true -> true val
4425       else
4426         return N3;    // cond always false -> false val
4427     }
4428
4429     // Fold to a simpler select_cc
4430     if (SCC.getOpcode() == ISD::SETCC)
4431       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4432                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4433                          SCC.getOperand(2));
4434   }
4435
4436   // If we can fold this based on the true/false value, do so.
4437   if (SimplifySelectOps(N, N2, N3))
4438     return SDValue(N, 0);  // Don't revisit N.
4439
4440   // fold select_cc into other things, such as min/max/abs
4441   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4442 }
4443
4444 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4445   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4446                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4447                        SDLoc(N));
4448 }
4449
4450 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4451 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4452 // transformation. Returns true if extension are possible and the above
4453 // mentioned transformation is profitable.
4454 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4455                                     unsigned ExtOpc,
4456                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4457                                     const TargetLowering &TLI) {
4458   bool HasCopyToRegUses = false;
4459   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4460   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4461                             UE = N0.getNode()->use_end();
4462        UI != UE; ++UI) {
4463     SDNode *User = *UI;
4464     if (User == N)
4465       continue;
4466     if (UI.getUse().getResNo() != N0.getResNo())
4467       continue;
4468     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4469     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4470       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4471       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4472         // Sign bits will be lost after a zext.
4473         return false;
4474       bool Add = false;
4475       for (unsigned i = 0; i != 2; ++i) {
4476         SDValue UseOp = User->getOperand(i);
4477         if (UseOp == N0)
4478           continue;
4479         if (!isa<ConstantSDNode>(UseOp))
4480           return false;
4481         Add = true;
4482       }
4483       if (Add)
4484         ExtendNodes.push_back(User);
4485       continue;
4486     }
4487     // If truncates aren't free and there are users we can't
4488     // extend, it isn't worthwhile.
4489     if (!isTruncFree)
4490       return false;
4491     // Remember if this value is live-out.
4492     if (User->getOpcode() == ISD::CopyToReg)
4493       HasCopyToRegUses = true;
4494   }
4495
4496   if (HasCopyToRegUses) {
4497     bool BothLiveOut = false;
4498     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4499          UI != UE; ++UI) {
4500       SDUse &Use = UI.getUse();
4501       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4502         BothLiveOut = true;
4503         break;
4504       }
4505     }
4506     if (BothLiveOut)
4507       // Both unextended and extended values are live out. There had better be
4508       // a good reason for the transformation.
4509       return ExtendNodes.size();
4510   }
4511   return true;
4512 }
4513
4514 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4515                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4516                                   ISD::NodeType ExtType) {
4517   // Extend SetCC uses if necessary.
4518   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4519     SDNode *SetCC = SetCCs[i];
4520     SmallVector<SDValue, 4> Ops;
4521
4522     for (unsigned j = 0; j != 2; ++j) {
4523       SDValue SOp = SetCC->getOperand(j);
4524       if (SOp == Trunc)
4525         Ops.push_back(ExtLoad);
4526       else
4527         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4528     }
4529
4530     Ops.push_back(SetCC->getOperand(2));
4531     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4532                                  &Ops[0], Ops.size()));
4533   }
4534 }
4535
4536 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4537   SDValue N0 = N->getOperand(0);
4538   EVT VT = N->getValueType(0);
4539
4540   // fold (sext c1) -> c1
4541   if (isa<ConstantSDNode>(N0))
4542     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4543
4544   // fold (sext (sext x)) -> (sext x)
4545   // fold (sext (aext x)) -> (sext x)
4546   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4547     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4548                        N0.getOperand(0));
4549
4550   if (N0.getOpcode() == ISD::TRUNCATE) {
4551     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4552     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4553     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4554     if (NarrowLoad.getNode()) {
4555       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4556       if (NarrowLoad.getNode() != N0.getNode()) {
4557         CombineTo(N0.getNode(), NarrowLoad);
4558         // CombineTo deleted the truncate, if needed, but not what's under it.
4559         AddToWorkList(oye);
4560       }
4561       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4562     }
4563
4564     // See if the value being truncated is already sign extended.  If so, just
4565     // eliminate the trunc/sext pair.
4566     SDValue Op = N0.getOperand(0);
4567     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4568     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4569     unsigned DestBits = VT.getScalarType().getSizeInBits();
4570     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4571
4572     if (OpBits == DestBits) {
4573       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4574       // bits, it is already ready.
4575       if (NumSignBits > DestBits-MidBits)
4576         return Op;
4577     } else if (OpBits < DestBits) {
4578       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4579       // bits, just sext from i32.
4580       if (NumSignBits > OpBits-MidBits)
4581         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4582     } else {
4583       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4584       // bits, just truncate to i32.
4585       if (NumSignBits > OpBits-MidBits)
4586         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4587     }
4588
4589     // fold (sext (truncate x)) -> (sextinreg x).
4590     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4591                                                  N0.getValueType())) {
4592       if (OpBits < DestBits)
4593         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4594       else if (OpBits > DestBits)
4595         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4596       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4597                          DAG.getValueType(N0.getValueType()));
4598     }
4599   }
4600
4601   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4602   // None of the supported targets knows how to perform load and sign extend
4603   // on vectors in one instruction.  We only perform this transformation on
4604   // scalars.
4605   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4606       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4607        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4608     bool DoXform = true;
4609     SmallVector<SDNode*, 4> SetCCs;
4610     if (!N0.hasOneUse())
4611       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4612     if (DoXform) {
4613       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4614       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4615                                        LN0->getChain(),
4616                                        LN0->getBasePtr(), N0.getValueType(),
4617                                        LN0->getMemOperand());
4618       CombineTo(N, ExtLoad);
4619       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4620                                   N0.getValueType(), ExtLoad);
4621       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4622       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4623                       ISD::SIGN_EXTEND);
4624       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4625     }
4626   }
4627
4628   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4629   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4630   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4631       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4632     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4633     EVT MemVT = LN0->getMemoryVT();
4634     if ((!LegalOperations && !LN0->isVolatile()) ||
4635         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4636       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4637                                        LN0->getChain(),
4638                                        LN0->getBasePtr(), MemVT,
4639                                        LN0->getMemOperand());
4640       CombineTo(N, ExtLoad);
4641       CombineTo(N0.getNode(),
4642                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4643                             N0.getValueType(), ExtLoad),
4644                 ExtLoad.getValue(1));
4645       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4646     }
4647   }
4648
4649   // fold (sext (and/or/xor (load x), cst)) ->
4650   //      (and/or/xor (sextload x), (sext cst))
4651   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4652        N0.getOpcode() == ISD::XOR) &&
4653       isa<LoadSDNode>(N0.getOperand(0)) &&
4654       N0.getOperand(1).getOpcode() == ISD::Constant &&
4655       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4656       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4657     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4658     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4659       bool DoXform = true;
4660       SmallVector<SDNode*, 4> SetCCs;
4661       if (!N0.hasOneUse())
4662         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4663                                           SetCCs, TLI);
4664       if (DoXform) {
4665         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4666                                          LN0->getChain(), LN0->getBasePtr(),
4667                                          LN0->getMemoryVT(),
4668                                          LN0->getMemOperand());
4669         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4670         Mask = Mask.sext(VT.getSizeInBits());
4671         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4672                                   ExtLoad, DAG.getConstant(Mask, VT));
4673         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4674                                     SDLoc(N0.getOperand(0)),
4675                                     N0.getOperand(0).getValueType(), ExtLoad);
4676         CombineTo(N, And);
4677         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4678         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4679                         ISD::SIGN_EXTEND);
4680         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4681       }
4682     }
4683   }
4684
4685   if (N0.getOpcode() == ISD::SETCC) {
4686     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4687     // Only do this before legalize for now.
4688     if (VT.isVector() && !LegalOperations &&
4689         TLI.getBooleanContents(true) ==
4690           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4691       EVT N0VT = N0.getOperand(0).getValueType();
4692       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4693       // of the same size as the compared operands. Only optimize sext(setcc())
4694       // if this is the case.
4695       EVT SVT = getSetCCResultType(N0VT);
4696
4697       // We know that the # elements of the results is the same as the
4698       // # elements of the compare (and the # elements of the compare result
4699       // for that matter).  Check to see that they are the same size.  If so,
4700       // we know that the element size of the sext'd result matches the
4701       // element size of the compare operands.
4702       if (VT.getSizeInBits() == SVT.getSizeInBits())
4703         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4704                              N0.getOperand(1),
4705                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4706
4707       // If the desired elements are smaller or larger than the source
4708       // elements we can use a matching integer vector type and then
4709       // truncate/sign extend
4710       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4711       if (SVT == MatchingVectorType) {
4712         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4713                                N0.getOperand(0), N0.getOperand(1),
4714                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4715         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4716       }
4717     }
4718
4719     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4720     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4721     SDValue NegOne =
4722       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4723     SDValue SCC =
4724       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4725                        NegOne, DAG.getConstant(0, VT),
4726                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4727     if (SCC.getNode()) return SCC;
4728     if (!VT.isVector() &&
4729         (!LegalOperations ||
4730          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4731       return DAG.getSelect(SDLoc(N), VT,
4732                            DAG.getSetCC(SDLoc(N),
4733                            getSetCCResultType(VT),
4734                            N0.getOperand(0), N0.getOperand(1),
4735                            cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4736                            NegOne, DAG.getConstant(0, VT));
4737     }
4738   }
4739
4740   // fold (sext x) -> (zext x) if the sign bit is known zero.
4741   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4742       DAG.SignBitIsZero(N0))
4743     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4744
4745   return SDValue();
4746 }
4747
4748 // isTruncateOf - If N is a truncate of some other value, return true, record
4749 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4750 // This function computes KnownZero to avoid a duplicated call to
4751 // ComputeMaskedBits in the caller.
4752 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4753                          APInt &KnownZero) {
4754   APInt KnownOne;
4755   if (N->getOpcode() == ISD::TRUNCATE) {
4756     Op = N->getOperand(0);
4757     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4758     return true;
4759   }
4760
4761   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4762       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4763     return false;
4764
4765   SDValue Op0 = N->getOperand(0);
4766   SDValue Op1 = N->getOperand(1);
4767   assert(Op0.getValueType() == Op1.getValueType());
4768
4769   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4770   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4771   if (COp0 && COp0->isNullValue())
4772     Op = Op1;
4773   else if (COp1 && COp1->isNullValue())
4774     Op = Op0;
4775   else
4776     return false;
4777
4778   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4779
4780   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4781     return false;
4782
4783   return true;
4784 }
4785
4786 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4787   SDValue N0 = N->getOperand(0);
4788   EVT VT = N->getValueType(0);
4789
4790   // fold (zext c1) -> c1
4791   if (isa<ConstantSDNode>(N0))
4792     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4793   // fold (zext (zext x)) -> (zext x)
4794   // fold (zext (aext x)) -> (zext x)
4795   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4796     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4797                        N0.getOperand(0));
4798
4799   // fold (zext (truncate x)) -> (zext x) or
4800   //      (zext (truncate x)) -> (truncate x)
4801   // This is valid when the truncated bits of x are already zero.
4802   // FIXME: We should extend this to work for vectors too.
4803   SDValue Op;
4804   APInt KnownZero;
4805   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4806     APInt TruncatedBits =
4807       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4808       APInt(Op.getValueSizeInBits(), 0) :
4809       APInt::getBitsSet(Op.getValueSizeInBits(),
4810                         N0.getValueSizeInBits(),
4811                         std::min(Op.getValueSizeInBits(),
4812                                  VT.getSizeInBits()));
4813     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4814       if (VT.bitsGT(Op.getValueType()))
4815         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4816       if (VT.bitsLT(Op.getValueType()))
4817         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4818
4819       return Op;
4820     }
4821   }
4822
4823   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4824   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4825   if (N0.getOpcode() == ISD::TRUNCATE) {
4826     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4827     if (NarrowLoad.getNode()) {
4828       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4829       if (NarrowLoad.getNode() != N0.getNode()) {
4830         CombineTo(N0.getNode(), NarrowLoad);
4831         // CombineTo deleted the truncate, if needed, but not what's under it.
4832         AddToWorkList(oye);
4833       }
4834       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4835     }
4836   }
4837
4838   // fold (zext (truncate x)) -> (and x, mask)
4839   if (N0.getOpcode() == ISD::TRUNCATE &&
4840       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4841
4842     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4843     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4844     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4845     if (NarrowLoad.getNode()) {
4846       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4847       if (NarrowLoad.getNode() != N0.getNode()) {
4848         CombineTo(N0.getNode(), NarrowLoad);
4849         // CombineTo deleted the truncate, if needed, but not what's under it.
4850         AddToWorkList(oye);
4851       }
4852       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4853     }
4854
4855     SDValue Op = N0.getOperand(0);
4856     if (Op.getValueType().bitsLT(VT)) {
4857       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4858       AddToWorkList(Op.getNode());
4859     } else if (Op.getValueType().bitsGT(VT)) {
4860       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4861       AddToWorkList(Op.getNode());
4862     }
4863     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4864                                   N0.getValueType().getScalarType());
4865   }
4866
4867   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4868   // if either of the casts is not free.
4869   if (N0.getOpcode() == ISD::AND &&
4870       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4871       N0.getOperand(1).getOpcode() == ISD::Constant &&
4872       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4873                            N0.getValueType()) ||
4874        !TLI.isZExtFree(N0.getValueType(), VT))) {
4875     SDValue X = N0.getOperand(0).getOperand(0);
4876     if (X.getValueType().bitsLT(VT)) {
4877       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4878     } else if (X.getValueType().bitsGT(VT)) {
4879       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4880     }
4881     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4882     Mask = Mask.zext(VT.getSizeInBits());
4883     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4884                        X, DAG.getConstant(Mask, VT));
4885   }
4886
4887   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4888   // None of the supported targets knows how to perform load and vector_zext
4889   // on vectors in one instruction.  We only perform this transformation on
4890   // scalars.
4891   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4892       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4893        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4894     bool DoXform = true;
4895     SmallVector<SDNode*, 4> SetCCs;
4896     if (!N0.hasOneUse())
4897       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4898     if (DoXform) {
4899       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4900       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4901                                        LN0->getChain(),
4902                                        LN0->getBasePtr(), N0.getValueType(),
4903                                        LN0->getMemOperand());
4904       CombineTo(N, ExtLoad);
4905       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4906                                   N0.getValueType(), ExtLoad);
4907       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4908
4909       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4910                       ISD::ZERO_EXTEND);
4911       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4912     }
4913   }
4914
4915   // fold (zext (and/or/xor (load x), cst)) ->
4916   //      (and/or/xor (zextload x), (zext cst))
4917   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4918        N0.getOpcode() == ISD::XOR) &&
4919       isa<LoadSDNode>(N0.getOperand(0)) &&
4920       N0.getOperand(1).getOpcode() == ISD::Constant &&
4921       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4922       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4923     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4924     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4925       bool DoXform = true;
4926       SmallVector<SDNode*, 4> SetCCs;
4927       if (!N0.hasOneUse())
4928         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4929                                           SetCCs, TLI);
4930       if (DoXform) {
4931         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4932                                          LN0->getChain(), LN0->getBasePtr(),
4933                                          LN0->getMemoryVT(),
4934                                          LN0->getMemOperand());
4935         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4936         Mask = Mask.zext(VT.getSizeInBits());
4937         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4938                                   ExtLoad, DAG.getConstant(Mask, VT));
4939         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4940                                     SDLoc(N0.getOperand(0)),
4941                                     N0.getOperand(0).getValueType(), ExtLoad);
4942         CombineTo(N, And);
4943         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4944         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4945                         ISD::ZERO_EXTEND);
4946         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4947       }
4948     }
4949   }
4950
4951   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4952   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4953   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4954       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4955     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4956     EVT MemVT = LN0->getMemoryVT();
4957     if ((!LegalOperations && !LN0->isVolatile()) ||
4958         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4959       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4960                                        LN0->getChain(),
4961                                        LN0->getBasePtr(), MemVT,
4962                                        LN0->getMemOperand());
4963       CombineTo(N, ExtLoad);
4964       CombineTo(N0.getNode(),
4965                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4966                             ExtLoad),
4967                 ExtLoad.getValue(1));
4968       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4969     }
4970   }
4971
4972   if (N0.getOpcode() == ISD::SETCC) {
4973     if (!LegalOperations && VT.isVector()) {
4974       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4975       // Only do this before legalize for now.
4976       EVT N0VT = N0.getOperand(0).getValueType();
4977       EVT EltVT = VT.getVectorElementType();
4978       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4979                                     DAG.getConstant(1, EltVT));
4980       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4981         // We know that the # elements of the results is the same as the
4982         // # elements of the compare (and the # elements of the compare result
4983         // for that matter).  Check to see that they are the same size.  If so,
4984         // we know that the element size of the sext'd result matches the
4985         // element size of the compare operands.
4986         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4987                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4988                                          N0.getOperand(1),
4989                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4990                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4991                                        &OneOps[0], OneOps.size()));
4992
4993       // If the desired elements are smaller or larger than the source
4994       // elements we can use a matching integer vector type and then
4995       // truncate/sign extend
4996       EVT MatchingElementType =
4997         EVT::getIntegerVT(*DAG.getContext(),
4998                           N0VT.getScalarType().getSizeInBits());
4999       EVT MatchingVectorType =
5000         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5001                          N0VT.getVectorNumElements());
5002       SDValue VsetCC =
5003         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5004                       N0.getOperand(1),
5005                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5006       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5007                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5008                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5009                                      &OneOps[0], OneOps.size()));
5010     }
5011
5012     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5013     SDValue SCC =
5014       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5015                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5016                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5017     if (SCC.getNode()) return SCC;
5018   }
5019
5020   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5021   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5022       isa<ConstantSDNode>(N0.getOperand(1)) &&
5023       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5024       N0.hasOneUse()) {
5025     SDValue ShAmt = N0.getOperand(1);
5026     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5027     if (N0.getOpcode() == ISD::SHL) {
5028       SDValue InnerZExt = N0.getOperand(0);
5029       // If the original shl may be shifting out bits, do not perform this
5030       // transformation.
5031       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5032         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5033       if (ShAmtVal > KnownZeroBits)
5034         return SDValue();
5035     }
5036
5037     SDLoc DL(N);
5038
5039     // Ensure that the shift amount is wide enough for the shifted value.
5040     if (VT.getSizeInBits() >= 256)
5041       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5042
5043     return DAG.getNode(N0.getOpcode(), DL, VT,
5044                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5045                        ShAmt);
5046   }
5047
5048   return SDValue();
5049 }
5050
5051 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5052   SDValue N0 = N->getOperand(0);
5053   EVT VT = N->getValueType(0);
5054
5055   // fold (aext c1) -> c1
5056   if (isa<ConstantSDNode>(N0))
5057     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5058   // fold (aext (aext x)) -> (aext x)
5059   // fold (aext (zext x)) -> (zext x)
5060   // fold (aext (sext x)) -> (sext x)
5061   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5062       N0.getOpcode() == ISD::ZERO_EXTEND ||
5063       N0.getOpcode() == ISD::SIGN_EXTEND)
5064     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5065
5066   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5067   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5068   if (N0.getOpcode() == ISD::TRUNCATE) {
5069     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5070     if (NarrowLoad.getNode()) {
5071       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5072       if (NarrowLoad.getNode() != N0.getNode()) {
5073         CombineTo(N0.getNode(), NarrowLoad);
5074         // CombineTo deleted the truncate, if needed, but not what's under it.
5075         AddToWorkList(oye);
5076       }
5077       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5078     }
5079   }
5080
5081   // fold (aext (truncate x))
5082   if (N0.getOpcode() == ISD::TRUNCATE) {
5083     SDValue TruncOp = N0.getOperand(0);
5084     if (TruncOp.getValueType() == VT)
5085       return TruncOp; // x iff x size == zext size.
5086     if (TruncOp.getValueType().bitsGT(VT))
5087       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5088     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5089   }
5090
5091   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5092   // if the trunc is not free.
5093   if (N0.getOpcode() == ISD::AND &&
5094       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5095       N0.getOperand(1).getOpcode() == ISD::Constant &&
5096       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5097                           N0.getValueType())) {
5098     SDValue X = N0.getOperand(0).getOperand(0);
5099     if (X.getValueType().bitsLT(VT)) {
5100       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5101     } else if (X.getValueType().bitsGT(VT)) {
5102       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5103     }
5104     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5105     Mask = Mask.zext(VT.getSizeInBits());
5106     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5107                        X, DAG.getConstant(Mask, VT));
5108   }
5109
5110   // fold (aext (load x)) -> (aext (truncate (extload x)))
5111   // None of the supported targets knows how to perform load and any_ext
5112   // on vectors in one instruction.  We only perform this transformation on
5113   // scalars.
5114   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5115       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5116        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5117     bool DoXform = true;
5118     SmallVector<SDNode*, 4> SetCCs;
5119     if (!N0.hasOneUse())
5120       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5121     if (DoXform) {
5122       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5123       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5124                                        LN0->getChain(),
5125                                        LN0->getBasePtr(), N0.getValueType(),
5126                                        LN0->getMemOperand());
5127       CombineTo(N, ExtLoad);
5128       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5129                                   N0.getValueType(), ExtLoad);
5130       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5131       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5132                       ISD::ANY_EXTEND);
5133       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5134     }
5135   }
5136
5137   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5138   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5139   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5140   if (N0.getOpcode() == ISD::LOAD &&
5141       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5142       N0.hasOneUse()) {
5143     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5144     EVT MemVT = LN0->getMemoryVT();
5145     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5146                                      VT, LN0->getChain(), LN0->getBasePtr(),
5147                                      MemVT, LN0->getMemOperand());
5148     CombineTo(N, ExtLoad);
5149     CombineTo(N0.getNode(),
5150               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5151                           N0.getValueType(), ExtLoad),
5152               ExtLoad.getValue(1));
5153     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5154   }
5155
5156   if (N0.getOpcode() == ISD::SETCC) {
5157     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5158     // Only do this before legalize for now.
5159     if (VT.isVector() && !LegalOperations) {
5160       EVT N0VT = N0.getOperand(0).getValueType();
5161         // We know that the # elements of the results is the same as the
5162         // # elements of the compare (and the # elements of the compare result
5163         // for that matter).  Check to see that they are the same size.  If so,
5164         // we know that the element size of the sext'd result matches the
5165         // element size of the compare operands.
5166       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5167         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5168                              N0.getOperand(1),
5169                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5170       // If the desired elements are smaller or larger than the source
5171       // elements we can use a matching integer vector type and then
5172       // truncate/sign extend
5173       else {
5174         EVT MatchingElementType =
5175           EVT::getIntegerVT(*DAG.getContext(),
5176                             N0VT.getScalarType().getSizeInBits());
5177         EVT MatchingVectorType =
5178           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5179                            N0VT.getVectorNumElements());
5180         SDValue VsetCC =
5181           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5182                         N0.getOperand(1),
5183                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5184         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5185       }
5186     }
5187
5188     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5189     SDValue SCC =
5190       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5191                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5192                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5193     if (SCC.getNode())
5194       return SCC;
5195   }
5196
5197   return SDValue();
5198 }
5199
5200 /// GetDemandedBits - See if the specified operand can be simplified with the
5201 /// knowledge that only the bits specified by Mask are used.  If so, return the
5202 /// simpler operand, otherwise return a null SDValue.
5203 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5204   switch (V.getOpcode()) {
5205   default: break;
5206   case ISD::Constant: {
5207     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5208     assert(CV != 0 && "Const value should be ConstSDNode.");
5209     const APInt &CVal = CV->getAPIntValue();
5210     APInt NewVal = CVal & Mask;
5211     if (NewVal != CVal)
5212       return DAG.getConstant(NewVal, V.getValueType());
5213     break;
5214   }
5215   case ISD::OR:
5216   case ISD::XOR:
5217     // If the LHS or RHS don't contribute bits to the or, drop them.
5218     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5219       return V.getOperand(1);
5220     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5221       return V.getOperand(0);
5222     break;
5223   case ISD::SRL:
5224     // Only look at single-use SRLs.
5225     if (!V.getNode()->hasOneUse())
5226       break;
5227     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5228       // See if we can recursively simplify the LHS.
5229       unsigned Amt = RHSC->getZExtValue();
5230
5231       // Watch out for shift count overflow though.
5232       if (Amt >= Mask.getBitWidth()) break;
5233       APInt NewMask = Mask << Amt;
5234       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5235       if (SimplifyLHS.getNode())
5236         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5237                            SimplifyLHS, V.getOperand(1));
5238     }
5239   }
5240   return SDValue();
5241 }
5242
5243 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5244 /// bits and then truncated to a narrower type and where N is a multiple
5245 /// of number of bits of the narrower type, transform it to a narrower load
5246 /// from address + N / num of bits of new type. If the result is to be
5247 /// extended, also fold the extension to form a extending load.
5248 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5249   unsigned Opc = N->getOpcode();
5250
5251   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5252   SDValue N0 = N->getOperand(0);
5253   EVT VT = N->getValueType(0);
5254   EVT ExtVT = VT;
5255
5256   // This transformation isn't valid for vector loads.
5257   if (VT.isVector())
5258     return SDValue();
5259
5260   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5261   // extended to VT.
5262   if (Opc == ISD::SIGN_EXTEND_INREG) {
5263     ExtType = ISD::SEXTLOAD;
5264     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5265   } else if (Opc == ISD::SRL) {
5266     // Another special-case: SRL is basically zero-extending a narrower value.
5267     ExtType = ISD::ZEXTLOAD;
5268     N0 = SDValue(N, 0);
5269     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5270     if (!N01) return SDValue();
5271     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5272                               VT.getSizeInBits() - N01->getZExtValue());
5273   }
5274   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5275     return SDValue();
5276
5277   unsigned EVTBits = ExtVT.getSizeInBits();
5278
5279   // Do not generate loads of non-round integer types since these can
5280   // be expensive (and would be wrong if the type is not byte sized).
5281   if (!ExtVT.isRound())
5282     return SDValue();
5283
5284   unsigned ShAmt = 0;
5285   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5286     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5287       ShAmt = N01->getZExtValue();
5288       // Is the shift amount a multiple of size of VT?
5289       if ((ShAmt & (EVTBits-1)) == 0) {
5290         N0 = N0.getOperand(0);
5291         // Is the load width a multiple of size of VT?
5292         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5293           return SDValue();
5294       }
5295
5296       // At this point, we must have a load or else we can't do the transform.
5297       if (!isa<LoadSDNode>(N0)) return SDValue();
5298
5299       // Because a SRL must be assumed to *need* to zero-extend the high bits
5300       // (as opposed to anyext the high bits), we can't combine the zextload
5301       // lowering of SRL and an sextload.
5302       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5303         return SDValue();
5304
5305       // If the shift amount is larger than the input type then we're not
5306       // accessing any of the loaded bytes.  If the load was a zextload/extload
5307       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5308       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5309         return SDValue();
5310     }
5311   }
5312
5313   // If the load is shifted left (and the result isn't shifted back right),
5314   // we can fold the truncate through the shift.
5315   unsigned ShLeftAmt = 0;
5316   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5317       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5318     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5319       ShLeftAmt = N01->getZExtValue();
5320       N0 = N0.getOperand(0);
5321     }
5322   }
5323
5324   // If we haven't found a load, we can't narrow it.  Don't transform one with
5325   // multiple uses, this would require adding a new load.
5326   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5327     return SDValue();
5328
5329   // Don't change the width of a volatile load.
5330   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5331   if (LN0->isVolatile())
5332     return SDValue();
5333
5334   // Verify that we are actually reducing a load width here.
5335   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5336     return SDValue();
5337
5338   // For the transform to be legal, the load must produce only two values
5339   // (the value loaded and the chain).  Don't transform a pre-increment
5340   // load, for example, which produces an extra value.  Otherwise the
5341   // transformation is not equivalent, and the downstream logic to replace
5342   // uses gets things wrong.
5343   if (LN0->getNumValues() > 2)
5344     return SDValue();
5345
5346   // If the load that we're shrinking is an extload and we're not just
5347   // discarding the extension we can't simply shrink the load. Bail.
5348   // TODO: It would be possible to merge the extensions in some cases.
5349   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5350       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5351     return SDValue();
5352
5353   EVT PtrType = N0.getOperand(1).getValueType();
5354
5355   if (PtrType == MVT::Untyped || PtrType.isExtended())
5356     // It's not possible to generate a constant of extended or untyped type.
5357     return SDValue();
5358
5359   // For big endian targets, we need to adjust the offset to the pointer to
5360   // load the correct bytes.
5361   if (TLI.isBigEndian()) {
5362     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5363     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5364     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5365   }
5366
5367   uint64_t PtrOff = ShAmt / 8;
5368   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5369   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5370                                PtrType, LN0->getBasePtr(),
5371                                DAG.getConstant(PtrOff, PtrType));
5372   AddToWorkList(NewPtr.getNode());
5373
5374   SDValue Load;
5375   if (ExtType == ISD::NON_EXTLOAD)
5376     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5377                         LN0->getPointerInfo().getWithOffset(PtrOff),
5378                         LN0->isVolatile(), LN0->isNonTemporal(),
5379                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5380   else
5381     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5382                           LN0->getPointerInfo().getWithOffset(PtrOff),
5383                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5384                           NewAlign, LN0->getTBAAInfo());
5385
5386   // Replace the old load's chain with the new load's chain.
5387   WorkListRemover DeadNodes(*this);
5388   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5389
5390   // Shift the result left, if we've swallowed a left shift.
5391   SDValue Result = Load;
5392   if (ShLeftAmt != 0) {
5393     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5394     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5395       ShImmTy = VT;
5396     // If the shift amount is as large as the result size (but, presumably,
5397     // no larger than the source) then the useful bits of the result are
5398     // zero; we can't simply return the shortened shift, because the result
5399     // of that operation is undefined.
5400     if (ShLeftAmt >= VT.getSizeInBits())
5401       Result = DAG.getConstant(0, VT);
5402     else
5403       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5404                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5405   }
5406
5407   // Return the new loaded value.
5408   return Result;
5409 }
5410
5411 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5412   SDValue N0 = N->getOperand(0);
5413   SDValue N1 = N->getOperand(1);
5414   EVT VT = N->getValueType(0);
5415   EVT EVT = cast<VTSDNode>(N1)->getVT();
5416   unsigned VTBits = VT.getScalarType().getSizeInBits();
5417   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5418
5419   // fold (sext_in_reg c1) -> c1
5420   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5421     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5422
5423   // If the input is already sign extended, just drop the extension.
5424   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5425     return N0;
5426
5427   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5428   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5429       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5430     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5431                        N0.getOperand(0), N1);
5432
5433   // fold (sext_in_reg (sext x)) -> (sext x)
5434   // fold (sext_in_reg (aext x)) -> (sext x)
5435   // if x is small enough.
5436   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5437     SDValue N00 = N0.getOperand(0);
5438     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5439         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5440       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5441   }
5442
5443   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5444   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5445     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5446
5447   // fold operands of sext_in_reg based on knowledge that the top bits are not
5448   // demanded.
5449   if (SimplifyDemandedBits(SDValue(N, 0)))
5450     return SDValue(N, 0);
5451
5452   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5453   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5454   SDValue NarrowLoad = ReduceLoadWidth(N);
5455   if (NarrowLoad.getNode())
5456     return NarrowLoad;
5457
5458   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5459   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5460   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5461   if (N0.getOpcode() == ISD::SRL) {
5462     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5463       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5464         // We can turn this into an SRA iff the input to the SRL is already sign
5465         // extended enough.
5466         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5467         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5468           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5469                              N0.getOperand(0), N0.getOperand(1));
5470       }
5471   }
5472
5473   // fold (sext_inreg (extload x)) -> (sextload x)
5474   if (ISD::isEXTLoad(N0.getNode()) &&
5475       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5476       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5477       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5478        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5479     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5480     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5481                                      LN0->getChain(),
5482                                      LN0->getBasePtr(), EVT,
5483                                      LN0->getMemOperand());
5484     CombineTo(N, ExtLoad);
5485     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5486     AddToWorkList(ExtLoad.getNode());
5487     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5488   }
5489   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5490   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5491       N0.hasOneUse() &&
5492       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5493       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5494        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5495     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5496     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5497                                      LN0->getChain(),
5498                                      LN0->getBasePtr(), EVT,
5499                                      LN0->getMemOperand());
5500     CombineTo(N, ExtLoad);
5501     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5502     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5503   }
5504
5505   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5506   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5507     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5508                                        N0.getOperand(1), false);
5509     if (BSwap.getNode() != 0)
5510       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5511                          BSwap, N1);
5512   }
5513
5514   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5515   // into a build_vector.
5516   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5517     SmallVector<SDValue, 8> Elts;
5518     unsigned NumElts = N0->getNumOperands();
5519     unsigned ShAmt = VTBits - EVTBits;
5520
5521     for (unsigned i = 0; i != NumElts; ++i) {
5522       SDValue Op = N0->getOperand(i);
5523       if (Op->getOpcode() == ISD::UNDEF) {
5524         Elts.push_back(Op);
5525         continue;
5526       }
5527
5528       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5529       const APInt &C = CurrentND->getAPIntValue();
5530       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt),
5531                                      Op.getValueType()));
5532     }
5533
5534     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5535   }
5536
5537   return SDValue();
5538 }
5539
5540 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5541   SDValue N0 = N->getOperand(0);
5542   EVT VT = N->getValueType(0);
5543   bool isLE = TLI.isLittleEndian();
5544
5545   // noop truncate
5546   if (N0.getValueType() == N->getValueType(0))
5547     return N0;
5548   // fold (truncate c1) -> c1
5549   if (isa<ConstantSDNode>(N0))
5550     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5551   // fold (truncate (truncate x)) -> (truncate x)
5552   if (N0.getOpcode() == ISD::TRUNCATE)
5553     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5554   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5555   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5556       N0.getOpcode() == ISD::SIGN_EXTEND ||
5557       N0.getOpcode() == ISD::ANY_EXTEND) {
5558     if (N0.getOperand(0).getValueType().bitsLT(VT))
5559       // if the source is smaller than the dest, we still need an extend
5560       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5561                          N0.getOperand(0));
5562     if (N0.getOperand(0).getValueType().bitsGT(VT))
5563       // if the source is larger than the dest, than we just need the truncate
5564       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5565     // if the source and dest are the same type, we can drop both the extend
5566     // and the truncate.
5567     return N0.getOperand(0);
5568   }
5569
5570   // Fold extract-and-trunc into a narrow extract. For example:
5571   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5572   //   i32 y = TRUNCATE(i64 x)
5573   //        -- becomes --
5574   //   v16i8 b = BITCAST (v2i64 val)
5575   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5576   //
5577   // Note: We only run this optimization after type legalization (which often
5578   // creates this pattern) and before operation legalization after which
5579   // we need to be more careful about the vector instructions that we generate.
5580   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5581       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5582
5583     EVT VecTy = N0.getOperand(0).getValueType();
5584     EVT ExTy = N0.getValueType();
5585     EVT TrTy = N->getValueType(0);
5586
5587     unsigned NumElem = VecTy.getVectorNumElements();
5588     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5589
5590     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5591     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5592
5593     SDValue EltNo = N0->getOperand(1);
5594     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5595       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5596       EVT IndexTy = TLI.getVectorIdxTy();
5597       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5598
5599       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5600                               NVT, N0.getOperand(0));
5601
5602       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5603                          SDLoc(N), TrTy, V,
5604                          DAG.getConstant(Index, IndexTy));
5605     }
5606   }
5607
5608   // Fold a series of buildvector, bitcast, and truncate if possible.
5609   // For example fold
5610   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5611   //   (2xi32 (buildvector x, y)).
5612   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5613       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5614       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5615       N0.getOperand(0).hasOneUse()) {
5616
5617     SDValue BuildVect = N0.getOperand(0);
5618     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5619     EVT TruncVecEltTy = VT.getVectorElementType();
5620
5621     // Check that the element types match.
5622     if (BuildVectEltTy == TruncVecEltTy) {
5623       // Now we only need to compute the offset of the truncated elements.
5624       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5625       unsigned TruncVecNumElts = VT.getVectorNumElements();
5626       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5627
5628       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5629              "Invalid number of elements");
5630
5631       SmallVector<SDValue, 8> Opnds;
5632       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5633         Opnds.push_back(BuildVect.getOperand(i));
5634
5635       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5636                          Opnds.size());
5637     }
5638   }
5639
5640   // See if we can simplify the input to this truncate through knowledge that
5641   // only the low bits are being used.
5642   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5643   // Currently we only perform this optimization on scalars because vectors
5644   // may have different active low bits.
5645   if (!VT.isVector()) {
5646     SDValue Shorter =
5647       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5648                                                VT.getSizeInBits()));
5649     if (Shorter.getNode())
5650       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5651   }
5652   // fold (truncate (load x)) -> (smaller load x)
5653   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5654   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5655     SDValue Reduced = ReduceLoadWidth(N);
5656     if (Reduced.getNode())
5657       return Reduced;
5658     // Handle the case where the load remains an extending load even
5659     // after truncation.
5660     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5661       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5662       if (!LN0->isVolatile() &&
5663           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5664         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5665                                          VT, LN0->getChain(), LN0->getBasePtr(),
5666                                          LN0->getMemoryVT(),
5667                                          LN0->getMemOperand());
5668         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5669         return NewLoad;
5670       }
5671     }
5672   }
5673   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5674   // where ... are all 'undef'.
5675   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5676     SmallVector<EVT, 8> VTs;
5677     SDValue V;
5678     unsigned Idx = 0;
5679     unsigned NumDefs = 0;
5680
5681     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5682       SDValue X = N0.getOperand(i);
5683       if (X.getOpcode() != ISD::UNDEF) {
5684         V = X;
5685         Idx = i;
5686         NumDefs++;
5687       }
5688       // Stop if more than one members are non-undef.
5689       if (NumDefs > 1)
5690         break;
5691       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5692                                      VT.getVectorElementType(),
5693                                      X.getValueType().getVectorNumElements()));
5694     }
5695
5696     if (NumDefs == 0)
5697       return DAG.getUNDEF(VT);
5698
5699     if (NumDefs == 1) {
5700       assert(V.getNode() && "The single defined operand is empty!");
5701       SmallVector<SDValue, 8> Opnds;
5702       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5703         if (i != Idx) {
5704           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5705           continue;
5706         }
5707         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5708         AddToWorkList(NV.getNode());
5709         Opnds.push_back(NV);
5710       }
5711       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5712                          &Opnds[0], Opnds.size());
5713     }
5714   }
5715
5716   // Simplify the operands using demanded-bits information.
5717   if (!VT.isVector() &&
5718       SimplifyDemandedBits(SDValue(N, 0)))
5719     return SDValue(N, 0);
5720
5721   return SDValue();
5722 }
5723
5724 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5725   SDValue Elt = N->getOperand(i);
5726   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5727     return Elt.getNode();
5728   return Elt.getOperand(Elt.getResNo()).getNode();
5729 }
5730
5731 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5732 /// if load locations are consecutive.
5733 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5734   assert(N->getOpcode() == ISD::BUILD_PAIR);
5735
5736   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5737   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5738   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5739       LD1->getPointerInfo().getAddrSpace() !=
5740          LD2->getPointerInfo().getAddrSpace())
5741     return SDValue();
5742   EVT LD1VT = LD1->getValueType(0);
5743
5744   if (ISD::isNON_EXTLoad(LD2) &&
5745       LD2->hasOneUse() &&
5746       // If both are volatile this would reduce the number of volatile loads.
5747       // If one is volatile it might be ok, but play conservative and bail out.
5748       !LD1->isVolatile() &&
5749       !LD2->isVolatile() &&
5750       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5751     unsigned Align = LD1->getAlignment();
5752     unsigned NewAlign = TLI.getDataLayout()->
5753       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5754
5755     if (NewAlign <= Align &&
5756         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5757       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5758                          LD1->getBasePtr(), LD1->getPointerInfo(),
5759                          false, false, false, Align);
5760   }
5761
5762   return SDValue();
5763 }
5764
5765 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5766   SDValue N0 = N->getOperand(0);
5767   EVT VT = N->getValueType(0);
5768
5769   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5770   // Only do this before legalize, since afterward the target may be depending
5771   // on the bitconvert.
5772   // First check to see if this is all constant.
5773   if (!LegalTypes &&
5774       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5775       VT.isVector()) {
5776     bool isSimple = true;
5777     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5778       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5779           N0.getOperand(i).getOpcode() != ISD::Constant &&
5780           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5781         isSimple = false;
5782         break;
5783       }
5784
5785     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5786     assert(!DestEltVT.isVector() &&
5787            "Element type of vector ValueType must not be vector!");
5788     if (isSimple)
5789       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5790   }
5791
5792   // If the input is a constant, let getNode fold it.
5793   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5794     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5795     if (Res.getNode() != N) {
5796       if (!LegalOperations ||
5797           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5798         return Res;
5799
5800       // Folding it resulted in an illegal node, and it's too late to
5801       // do that. Clean up the old node and forego the transformation.
5802       // Ideally this won't happen very often, because instcombine
5803       // and the earlier dagcombine runs (where illegal nodes are
5804       // permitted) should have folded most of them already.
5805       DAG.DeleteNode(Res.getNode());
5806     }
5807   }
5808
5809   // (conv (conv x, t1), t2) -> (conv x, t2)
5810   if (N0.getOpcode() == ISD::BITCAST)
5811     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5812                        N0.getOperand(0));
5813
5814   // fold (conv (load x)) -> (load (conv*)x)
5815   // If the resultant load doesn't need a higher alignment than the original!
5816   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5817       // Do not change the width of a volatile load.
5818       !cast<LoadSDNode>(N0)->isVolatile() &&
5819       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5820       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5821     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5822     unsigned Align = TLI.getDataLayout()->
5823       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5824     unsigned OrigAlign = LN0->getAlignment();
5825
5826     if (Align <= OrigAlign) {
5827       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5828                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5829                                  LN0->isVolatile(), LN0->isNonTemporal(),
5830                                  LN0->isInvariant(), OrigAlign,
5831                                  LN0->getTBAAInfo());
5832       AddToWorkList(N);
5833       CombineTo(N0.getNode(),
5834                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5835                             N0.getValueType(), Load),
5836                 Load.getValue(1));
5837       return Load;
5838     }
5839   }
5840
5841   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5842   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5843   // This often reduces constant pool loads.
5844   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5845        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5846       N0.getNode()->hasOneUse() && VT.isInteger() &&
5847       !VT.isVector() && !N0.getValueType().isVector()) {
5848     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5849                                   N0.getOperand(0));
5850     AddToWorkList(NewConv.getNode());
5851
5852     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5853     if (N0.getOpcode() == ISD::FNEG)
5854       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5855                          NewConv, DAG.getConstant(SignBit, VT));
5856     assert(N0.getOpcode() == ISD::FABS);
5857     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5858                        NewConv, DAG.getConstant(~SignBit, VT));
5859   }
5860
5861   // fold (bitconvert (fcopysign cst, x)) ->
5862   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5863   // Note that we don't handle (copysign x, cst) because this can always be
5864   // folded to an fneg or fabs.
5865   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5866       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5867       VT.isInteger() && !VT.isVector()) {
5868     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5869     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5870     if (isTypeLegal(IntXVT)) {
5871       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5872                               IntXVT, N0.getOperand(1));
5873       AddToWorkList(X.getNode());
5874
5875       // If X has a different width than the result/lhs, sext it or truncate it.
5876       unsigned VTWidth = VT.getSizeInBits();
5877       if (OrigXWidth < VTWidth) {
5878         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5879         AddToWorkList(X.getNode());
5880       } else if (OrigXWidth > VTWidth) {
5881         // To get the sign bit in the right place, we have to shift it right
5882         // before truncating.
5883         X = DAG.getNode(ISD::SRL, SDLoc(X),
5884                         X.getValueType(), X,
5885                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5886         AddToWorkList(X.getNode());
5887         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5888         AddToWorkList(X.getNode());
5889       }
5890
5891       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5892       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5893                       X, DAG.getConstant(SignBit, VT));
5894       AddToWorkList(X.getNode());
5895
5896       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5897                                 VT, N0.getOperand(0));
5898       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5899                         Cst, DAG.getConstant(~SignBit, VT));
5900       AddToWorkList(Cst.getNode());
5901
5902       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5903     }
5904   }
5905
5906   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5907   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5908     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5909     if (CombineLD.getNode())
5910       return CombineLD;
5911   }
5912
5913   return SDValue();
5914 }
5915
5916 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5917   EVT VT = N->getValueType(0);
5918   return CombineConsecutiveLoads(N, VT);
5919 }
5920
5921 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5922 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5923 /// destination element value type.
5924 SDValue DAGCombiner::
5925 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5926   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5927
5928   // If this is already the right type, we're done.
5929   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5930
5931   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5932   unsigned DstBitSize = DstEltVT.getSizeInBits();
5933
5934   // If this is a conversion of N elements of one type to N elements of another
5935   // type, convert each element.  This handles FP<->INT cases.
5936   if (SrcBitSize == DstBitSize) {
5937     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5938                               BV->getValueType(0).getVectorNumElements());
5939
5940     // Due to the FP element handling below calling this routine recursively,
5941     // we can end up with a scalar-to-vector node here.
5942     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5943       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5944                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5945                                      DstEltVT, BV->getOperand(0)));
5946
5947     SmallVector<SDValue, 8> Ops;
5948     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5949       SDValue Op = BV->getOperand(i);
5950       // If the vector element type is not legal, the BUILD_VECTOR operands
5951       // are promoted and implicitly truncated.  Make that explicit here.
5952       if (Op.getValueType() != SrcEltVT)
5953         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5954       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5955                                 DstEltVT, Op));
5956       AddToWorkList(Ops.back().getNode());
5957     }
5958     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5959                        &Ops[0], Ops.size());
5960   }
5961
5962   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5963   // handle annoying details of growing/shrinking FP values, we convert them to
5964   // int first.
5965   if (SrcEltVT.isFloatingPoint()) {
5966     // Convert the input float vector to a int vector where the elements are the
5967     // same sizes.
5968     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5969     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5970     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5971     SrcEltVT = IntVT;
5972   }
5973
5974   // Now we know the input is an integer vector.  If the output is a FP type,
5975   // convert to integer first, then to FP of the right size.
5976   if (DstEltVT.isFloatingPoint()) {
5977     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5978     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5979     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5980
5981     // Next, convert to FP elements of the same size.
5982     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5983   }
5984
5985   // Okay, we know the src/dst types are both integers of differing types.
5986   // Handling growing first.
5987   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5988   if (SrcBitSize < DstBitSize) {
5989     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5990
5991     SmallVector<SDValue, 8> Ops;
5992     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5993          i += NumInputsPerOutput) {
5994       bool isLE = TLI.isLittleEndian();
5995       APInt NewBits = APInt(DstBitSize, 0);
5996       bool EltIsUndef = true;
5997       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5998         // Shift the previously computed bits over.
5999         NewBits <<= SrcBitSize;
6000         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6001         if (Op.getOpcode() == ISD::UNDEF) continue;
6002         EltIsUndef = false;
6003
6004         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6005                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6006       }
6007
6008       if (EltIsUndef)
6009         Ops.push_back(DAG.getUNDEF(DstEltVT));
6010       else
6011         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6012     }
6013
6014     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6015     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6016                        &Ops[0], Ops.size());
6017   }
6018
6019   // Finally, this must be the case where we are shrinking elements: each input
6020   // turns into multiple outputs.
6021   bool isS2V = ISD::isScalarToVector(BV);
6022   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6023   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6024                             NumOutputsPerInput*BV->getNumOperands());
6025   SmallVector<SDValue, 8> Ops;
6026
6027   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6028     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6029       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6030         Ops.push_back(DAG.getUNDEF(DstEltVT));
6031       continue;
6032     }
6033
6034     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6035                   getAPIntValue().zextOrTrunc(SrcBitSize);
6036
6037     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6038       APInt ThisVal = OpVal.trunc(DstBitSize);
6039       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6040       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6041         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6042         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6043                            Ops[0]);
6044       OpVal = OpVal.lshr(DstBitSize);
6045     }
6046
6047     // For big endian targets, swap the order of the pieces of each element.
6048     if (TLI.isBigEndian())
6049       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6050   }
6051
6052   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6053                      &Ops[0], Ops.size());
6054 }
6055
6056 SDValue DAGCombiner::visitFADD(SDNode *N) {
6057   SDValue N0 = N->getOperand(0);
6058   SDValue N1 = N->getOperand(1);
6059   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6060   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6061   EVT VT = N->getValueType(0);
6062
6063   // fold vector ops
6064   if (VT.isVector()) {
6065     SDValue FoldedVOp = SimplifyVBinOp(N);
6066     if (FoldedVOp.getNode()) return FoldedVOp;
6067   }
6068
6069   // fold (fadd c1, c2) -> c1 + c2
6070   if (N0CFP && N1CFP)
6071     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6072   // canonicalize constant to RHS
6073   if (N0CFP && !N1CFP)
6074     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6075   // fold (fadd A, 0) -> A
6076   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6077       N1CFP->getValueAPF().isZero())
6078     return N0;
6079   // fold (fadd A, (fneg B)) -> (fsub A, B)
6080   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6081     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6082     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6083                        GetNegatedExpression(N1, DAG, LegalOperations));
6084   // fold (fadd (fneg A), B) -> (fsub B, A)
6085   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6086     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6087     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6088                        GetNegatedExpression(N0, DAG, LegalOperations));
6089
6090   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6091   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6092       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6093       isa<ConstantFPSDNode>(N0.getOperand(1)))
6094     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6095                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6096                                    N0.getOperand(1), N1));
6097
6098   // No FP constant should be created after legalization as Instruction
6099   // Selection pass has hard time in dealing with FP constant.
6100   //
6101   // We don't need test this condition for transformation like following, as
6102   // the DAG being transformed implies it is legal to take FP constant as
6103   // operand.
6104   //
6105   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6106   //
6107   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6108
6109   // If allow, fold (fadd (fneg x), x) -> 0.0
6110   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6111       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6112     return DAG.getConstantFP(0.0, VT);
6113
6114     // If allow, fold (fadd x, (fneg x)) -> 0.0
6115   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6116       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6117     return DAG.getConstantFP(0.0, VT);
6118
6119   // In unsafe math mode, we can fold chains of FADD's of the same value
6120   // into multiplications.  This transform is not safe in general because
6121   // we are reducing the number of rounding steps.
6122   if (DAG.getTarget().Options.UnsafeFPMath &&
6123       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6124       !N0CFP && !N1CFP) {
6125     if (N0.getOpcode() == ISD::FMUL) {
6126       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6127       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6128
6129       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6130       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6131         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6132                                      SDValue(CFP00, 0),
6133                                      DAG.getConstantFP(1.0, VT));
6134         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6135                            N1, NewCFP);
6136       }
6137
6138       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6139       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6140         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6141                                      SDValue(CFP01, 0),
6142                                      DAG.getConstantFP(1.0, VT));
6143         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6144                            N1, NewCFP);
6145       }
6146
6147       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6148       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6149           N1.getOperand(0) == N1.getOperand(1) &&
6150           N0.getOperand(1) == N1.getOperand(0)) {
6151         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6152                                      SDValue(CFP00, 0),
6153                                      DAG.getConstantFP(2.0, VT));
6154         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6155                            N0.getOperand(1), NewCFP);
6156       }
6157
6158       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6159       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6160           N1.getOperand(0) == N1.getOperand(1) &&
6161           N0.getOperand(0) == N1.getOperand(0)) {
6162         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6163                                      SDValue(CFP01, 0),
6164                                      DAG.getConstantFP(2.0, VT));
6165         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6166                            N0.getOperand(0), NewCFP);
6167       }
6168     }
6169
6170     if (N1.getOpcode() == ISD::FMUL) {
6171       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6172       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6173
6174       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6175       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6176         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6177                                      SDValue(CFP10, 0),
6178                                      DAG.getConstantFP(1.0, VT));
6179         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6180                            N0, NewCFP);
6181       }
6182
6183       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6184       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6185         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6186                                      SDValue(CFP11, 0),
6187                                      DAG.getConstantFP(1.0, VT));
6188         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6189                            N0, NewCFP);
6190       }
6191
6192
6193       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6194       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6195           N0.getOperand(0) == N0.getOperand(1) &&
6196           N1.getOperand(1) == N0.getOperand(0)) {
6197         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6198                                      SDValue(CFP10, 0),
6199                                      DAG.getConstantFP(2.0, VT));
6200         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6201                            N1.getOperand(1), NewCFP);
6202       }
6203
6204       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6205       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6206           N0.getOperand(0) == N0.getOperand(1) &&
6207           N1.getOperand(0) == N0.getOperand(0)) {
6208         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6209                                      SDValue(CFP11, 0),
6210                                      DAG.getConstantFP(2.0, VT));
6211         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6212                            N1.getOperand(0), NewCFP);
6213       }
6214     }
6215
6216     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6217       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6218       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6219       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6220           (N0.getOperand(0) == N1))
6221         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6222                            N1, DAG.getConstantFP(3.0, VT));
6223     }
6224
6225     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6226       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6227       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6228       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6229           N1.getOperand(0) == N0)
6230         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6231                            N0, DAG.getConstantFP(3.0, VT));
6232     }
6233
6234     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6235     if (AllowNewFpConst &&
6236         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6237         N0.getOperand(0) == N0.getOperand(1) &&
6238         N1.getOperand(0) == N1.getOperand(1) &&
6239         N0.getOperand(0) == N1.getOperand(0))
6240       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6241                          N0.getOperand(0),
6242                          DAG.getConstantFP(4.0, VT));
6243   }
6244
6245   // FADD -> FMA combines:
6246   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6247        DAG.getTarget().Options.UnsafeFPMath) &&
6248       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6249       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6250
6251     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6252     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6253       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6254                          N0.getOperand(0), N0.getOperand(1), N1);
6255
6256     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6257     // Note: Commutes FADD operands.
6258     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6259       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6260                          N1.getOperand(0), N1.getOperand(1), N0);
6261   }
6262
6263   return SDValue();
6264 }
6265
6266 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6267   SDValue N0 = N->getOperand(0);
6268   SDValue N1 = N->getOperand(1);
6269   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6270   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6271   EVT VT = N->getValueType(0);
6272   SDLoc dl(N);
6273
6274   // fold vector ops
6275   if (VT.isVector()) {
6276     SDValue FoldedVOp = SimplifyVBinOp(N);
6277     if (FoldedVOp.getNode()) return FoldedVOp;
6278   }
6279
6280   // fold (fsub c1, c2) -> c1-c2
6281   if (N0CFP && N1CFP)
6282     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6283   // fold (fsub A, 0) -> A
6284   if (DAG.getTarget().Options.UnsafeFPMath &&
6285       N1CFP && N1CFP->getValueAPF().isZero())
6286     return N0;
6287   // fold (fsub 0, B) -> -B
6288   if (DAG.getTarget().Options.UnsafeFPMath &&
6289       N0CFP && N0CFP->getValueAPF().isZero()) {
6290     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6291       return GetNegatedExpression(N1, DAG, LegalOperations);
6292     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6293       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6294   }
6295   // fold (fsub A, (fneg B)) -> (fadd A, B)
6296   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6297     return DAG.getNode(ISD::FADD, dl, VT, N0,
6298                        GetNegatedExpression(N1, DAG, LegalOperations));
6299
6300   // If 'unsafe math' is enabled, fold
6301   //    (fsub x, x) -> 0.0 &
6302   //    (fsub x, (fadd x, y)) -> (fneg y) &
6303   //    (fsub x, (fadd y, x)) -> (fneg y)
6304   if (DAG.getTarget().Options.UnsafeFPMath) {
6305     if (N0 == N1)
6306       return DAG.getConstantFP(0.0f, VT);
6307
6308     if (N1.getOpcode() == ISD::FADD) {
6309       SDValue N10 = N1->getOperand(0);
6310       SDValue N11 = N1->getOperand(1);
6311
6312       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6313                                           &DAG.getTarget().Options))
6314         return GetNegatedExpression(N11, DAG, LegalOperations);
6315
6316       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6317                                           &DAG.getTarget().Options))
6318         return GetNegatedExpression(N10, DAG, LegalOperations);
6319     }
6320   }
6321
6322   // FSUB -> FMA combines:
6323   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6324        DAG.getTarget().Options.UnsafeFPMath) &&
6325       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6326       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6327
6328     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6329     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6330       return DAG.getNode(ISD::FMA, dl, VT,
6331                          N0.getOperand(0), N0.getOperand(1),
6332                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6333
6334     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6335     // Note: Commutes FSUB operands.
6336     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6337       return DAG.getNode(ISD::FMA, dl, VT,
6338                          DAG.getNode(ISD::FNEG, dl, VT,
6339                          N1.getOperand(0)),
6340                          N1.getOperand(1), N0);
6341
6342     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6343     if (N0.getOpcode() == ISD::FNEG &&
6344         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6345         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6346       SDValue N00 = N0.getOperand(0).getOperand(0);
6347       SDValue N01 = N0.getOperand(0).getOperand(1);
6348       return DAG.getNode(ISD::FMA, dl, VT,
6349                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6350                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6351     }
6352   }
6353
6354   return SDValue();
6355 }
6356
6357 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6358   SDValue N0 = N->getOperand(0);
6359   SDValue N1 = N->getOperand(1);
6360   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6361   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6362   EVT VT = N->getValueType(0);
6363   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6364
6365   // fold vector ops
6366   if (VT.isVector()) {
6367     SDValue FoldedVOp = SimplifyVBinOp(N);
6368     if (FoldedVOp.getNode()) return FoldedVOp;
6369   }
6370
6371   // fold (fmul c1, c2) -> c1*c2
6372   if (N0CFP && N1CFP)
6373     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6374   // canonicalize constant to RHS
6375   if (N0CFP && !N1CFP)
6376     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6377   // fold (fmul A, 0) -> 0
6378   if (DAG.getTarget().Options.UnsafeFPMath &&
6379       N1CFP && N1CFP->getValueAPF().isZero())
6380     return N1;
6381   // fold (fmul A, 0) -> 0, vector edition.
6382   if (DAG.getTarget().Options.UnsafeFPMath &&
6383       ISD::isBuildVectorAllZeros(N1.getNode()))
6384     return N1;
6385   // fold (fmul A, 1.0) -> A
6386   if (N1CFP && N1CFP->isExactlyValue(1.0))
6387     return N0;
6388   // fold (fmul X, 2.0) -> (fadd X, X)
6389   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6390     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6391   // fold (fmul X, -1.0) -> (fneg X)
6392   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6393     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6394       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6395
6396   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6397   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6398                                        &DAG.getTarget().Options)) {
6399     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6400                                          &DAG.getTarget().Options)) {
6401       // Both can be negated for free, check to see if at least one is cheaper
6402       // negated.
6403       if (LHSNeg == 2 || RHSNeg == 2)
6404         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6405                            GetNegatedExpression(N0, DAG, LegalOperations),
6406                            GetNegatedExpression(N1, DAG, LegalOperations));
6407     }
6408   }
6409
6410   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6411   if (DAG.getTarget().Options.UnsafeFPMath &&
6412       N1CFP && N0.getOpcode() == ISD::FMUL &&
6413       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6414     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6415                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6416                                    N0.getOperand(1), N1));
6417
6418   return SDValue();
6419 }
6420
6421 SDValue DAGCombiner::visitFMA(SDNode *N) {
6422   SDValue N0 = N->getOperand(0);
6423   SDValue N1 = N->getOperand(1);
6424   SDValue N2 = N->getOperand(2);
6425   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6426   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6427   EVT VT = N->getValueType(0);
6428   SDLoc dl(N);
6429
6430   if (DAG.getTarget().Options.UnsafeFPMath) {
6431     if (N0CFP && N0CFP->isZero())
6432       return N2;
6433     if (N1CFP && N1CFP->isZero())
6434       return N2;
6435   }
6436   if (N0CFP && N0CFP->isExactlyValue(1.0))
6437     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6438   if (N1CFP && N1CFP->isExactlyValue(1.0))
6439     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6440
6441   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6442   if (N0CFP && !N1CFP)
6443     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6444
6445   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6446   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6447       N2.getOpcode() == ISD::FMUL &&
6448       N0 == N2.getOperand(0) &&
6449       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6450     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6451                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6452   }
6453
6454
6455   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6456   if (DAG.getTarget().Options.UnsafeFPMath &&
6457       N0.getOpcode() == ISD::FMUL && N1CFP &&
6458       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6459     return DAG.getNode(ISD::FMA, dl, VT,
6460                        N0.getOperand(0),
6461                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6462                        N2);
6463   }
6464
6465   // (fma x, 1, y) -> (fadd x, y)
6466   // (fma x, -1, y) -> (fadd (fneg x), y)
6467   if (N1CFP) {
6468     if (N1CFP->isExactlyValue(1.0))
6469       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6470
6471     if (N1CFP->isExactlyValue(-1.0) &&
6472         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6473       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6474       AddToWorkList(RHSNeg.getNode());
6475       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6476     }
6477   }
6478
6479   // (fma x, c, x) -> (fmul x, (c+1))
6480   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6481     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6482                        DAG.getNode(ISD::FADD, dl, VT,
6483                                    N1, DAG.getConstantFP(1.0, VT)));
6484
6485   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6486   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6487       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6488     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6489                        DAG.getNode(ISD::FADD, dl, VT,
6490                                    N1, DAG.getConstantFP(-1.0, VT)));
6491
6492
6493   return SDValue();
6494 }
6495
6496 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6497   SDValue N0 = N->getOperand(0);
6498   SDValue N1 = N->getOperand(1);
6499   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6500   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6501   EVT VT = N->getValueType(0);
6502   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6503
6504   // fold vector ops
6505   if (VT.isVector()) {
6506     SDValue FoldedVOp = SimplifyVBinOp(N);
6507     if (FoldedVOp.getNode()) return FoldedVOp;
6508   }
6509
6510   // fold (fdiv c1, c2) -> c1/c2
6511   if (N0CFP && N1CFP)
6512     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6513
6514   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6515   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6516     // Compute the reciprocal 1.0 / c2.
6517     APFloat N1APF = N1CFP->getValueAPF();
6518     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6519     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6520     // Only do the transform if the reciprocal is a legal fp immediate that
6521     // isn't too nasty (eg NaN, denormal, ...).
6522     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6523         (!LegalOperations ||
6524          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6525          // backend)... we should handle this gracefully after Legalize.
6526          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6527          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6528          TLI.isFPImmLegal(Recip, VT)))
6529       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6530                          DAG.getConstantFP(Recip, VT));
6531   }
6532
6533   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6534   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6535                                        &DAG.getTarget().Options)) {
6536     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6537                                          &DAG.getTarget().Options)) {
6538       // Both can be negated for free, check to see if at least one is cheaper
6539       // negated.
6540       if (LHSNeg == 2 || RHSNeg == 2)
6541         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6542                            GetNegatedExpression(N0, DAG, LegalOperations),
6543                            GetNegatedExpression(N1, DAG, LegalOperations));
6544     }
6545   }
6546
6547   return SDValue();
6548 }
6549
6550 SDValue DAGCombiner::visitFREM(SDNode *N) {
6551   SDValue N0 = N->getOperand(0);
6552   SDValue N1 = N->getOperand(1);
6553   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6554   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6555   EVT VT = N->getValueType(0);
6556
6557   // fold (frem c1, c2) -> fmod(c1,c2)
6558   if (N0CFP && N1CFP)
6559     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6560
6561   return SDValue();
6562 }
6563
6564 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6565   SDValue N0 = N->getOperand(0);
6566   SDValue N1 = N->getOperand(1);
6567   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6568   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6569   EVT VT = N->getValueType(0);
6570
6571   if (N0CFP && N1CFP)  // Constant fold
6572     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6573
6574   if (N1CFP) {
6575     const APFloat& V = N1CFP->getValueAPF();
6576     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6577     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6578     if (!V.isNegative()) {
6579       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6580         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6581     } else {
6582       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6583         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6584                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6585     }
6586   }
6587
6588   // copysign(fabs(x), y) -> copysign(x, y)
6589   // copysign(fneg(x), y) -> copysign(x, y)
6590   // copysign(copysign(x,z), y) -> copysign(x, y)
6591   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6592       N0.getOpcode() == ISD::FCOPYSIGN)
6593     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6594                        N0.getOperand(0), N1);
6595
6596   // copysign(x, abs(y)) -> abs(x)
6597   if (N1.getOpcode() == ISD::FABS)
6598     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6599
6600   // copysign(x, copysign(y,z)) -> copysign(x, z)
6601   if (N1.getOpcode() == ISD::FCOPYSIGN)
6602     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6603                        N0, N1.getOperand(1));
6604
6605   // copysign(x, fp_extend(y)) -> copysign(x, y)
6606   // copysign(x, fp_round(y)) -> copysign(x, y)
6607   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6608     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6609                        N0, N1.getOperand(0));
6610
6611   return SDValue();
6612 }
6613
6614 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6615   SDValue N0 = N->getOperand(0);
6616   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6617   EVT VT = N->getValueType(0);
6618   EVT OpVT = N0.getValueType();
6619
6620   // fold (sint_to_fp c1) -> c1fp
6621   if (N0C &&
6622       // ...but only if the target supports immediate floating-point values
6623       (!LegalOperations ||
6624        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6625     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6626
6627   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6628   // but UINT_TO_FP is legal on this target, try to convert.
6629   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6630       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6631     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6632     if (DAG.SignBitIsZero(N0))
6633       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6634   }
6635
6636   // The next optimizations are desireable only if SELECT_CC can be lowered.
6637   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6638   // having to say they don't support SELECT_CC on every type the DAG knows
6639   // about, since there is no way to mark an opcode illegal at all value types
6640   // (See also visitSELECT)
6641   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6642     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6643     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6644         !VT.isVector() &&
6645         (!LegalOperations ||
6646          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6647       SDValue Ops[] =
6648         { N0.getOperand(0), N0.getOperand(1),
6649           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6650           N0.getOperand(2) };
6651       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6652     }
6653
6654     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6655     //      (select_cc x, y, 1.0, 0.0,, cc)
6656     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6657         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6658         (!LegalOperations ||
6659          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6660       SDValue Ops[] =
6661         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6662           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6663           N0.getOperand(0).getOperand(2) };
6664       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6665     }
6666   }
6667
6668   return SDValue();
6669 }
6670
6671 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6672   SDValue N0 = N->getOperand(0);
6673   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6674   EVT VT = N->getValueType(0);
6675   EVT OpVT = N0.getValueType();
6676
6677   // fold (uint_to_fp c1) -> c1fp
6678   if (N0C &&
6679       // ...but only if the target supports immediate floating-point values
6680       (!LegalOperations ||
6681        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6682     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6683
6684   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6685   // but SINT_TO_FP is legal on this target, try to convert.
6686   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6687       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6688     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6689     if (DAG.SignBitIsZero(N0))
6690       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6691   }
6692
6693   // The next optimizations are desireable only if SELECT_CC can be lowered.
6694   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6695   // having to say they don't support SELECT_CC on every type the DAG knows
6696   // about, since there is no way to mark an opcode illegal at all value types
6697   // (See also visitSELECT)
6698   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6699     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6700
6701     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6702         (!LegalOperations ||
6703          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6704       SDValue Ops[] =
6705         { N0.getOperand(0), N0.getOperand(1),
6706           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6707           N0.getOperand(2) };
6708       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6709     }
6710   }
6711
6712   return SDValue();
6713 }
6714
6715 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6716   SDValue N0 = N->getOperand(0);
6717   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6718   EVT VT = N->getValueType(0);
6719
6720   // fold (fp_to_sint c1fp) -> c1
6721   if (N0CFP)
6722     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6723
6724   return SDValue();
6725 }
6726
6727 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6728   SDValue N0 = N->getOperand(0);
6729   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6730   EVT VT = N->getValueType(0);
6731
6732   // fold (fp_to_uint c1fp) -> c1
6733   if (N0CFP)
6734     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6735
6736   return SDValue();
6737 }
6738
6739 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6740   SDValue N0 = N->getOperand(0);
6741   SDValue N1 = N->getOperand(1);
6742   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6743   EVT VT = N->getValueType(0);
6744
6745   // fold (fp_round c1fp) -> c1fp
6746   if (N0CFP)
6747     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6748
6749   // fold (fp_round (fp_extend x)) -> x
6750   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6751     return N0.getOperand(0);
6752
6753   // fold (fp_round (fp_round x)) -> (fp_round x)
6754   if (N0.getOpcode() == ISD::FP_ROUND) {
6755     // This is a value preserving truncation if both round's are.
6756     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6757                    N0.getNode()->getConstantOperandVal(1) == 1;
6758     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6759                        DAG.getIntPtrConstant(IsTrunc));
6760   }
6761
6762   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6763   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6764     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6765                               N0.getOperand(0), N1);
6766     AddToWorkList(Tmp.getNode());
6767     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6768                        Tmp, N0.getOperand(1));
6769   }
6770
6771   return SDValue();
6772 }
6773
6774 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6775   SDValue N0 = N->getOperand(0);
6776   EVT VT = N->getValueType(0);
6777   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6778   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6779
6780   // fold (fp_round_inreg c1fp) -> c1fp
6781   if (N0CFP && isTypeLegal(EVT)) {
6782     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6783     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6784   }
6785
6786   return SDValue();
6787 }
6788
6789 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6790   SDValue N0 = N->getOperand(0);
6791   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6792   EVT VT = N->getValueType(0);
6793
6794   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6795   if (N->hasOneUse() &&
6796       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6797     return SDValue();
6798
6799   // fold (fp_extend c1fp) -> c1fp
6800   if (N0CFP)
6801     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6802
6803   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6804   // value of X.
6805   if (N0.getOpcode() == ISD::FP_ROUND
6806       && N0.getNode()->getConstantOperandVal(1) == 1) {
6807     SDValue In = N0.getOperand(0);
6808     if (In.getValueType() == VT) return In;
6809     if (VT.bitsLT(In.getValueType()))
6810       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6811                          In, N0.getOperand(1));
6812     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6813   }
6814
6815   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6816   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6817       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6818        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6819     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6820     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6821                                      LN0->getChain(),
6822                                      LN0->getBasePtr(), N0.getValueType(),
6823                                      LN0->getMemOperand());
6824     CombineTo(N, ExtLoad);
6825     CombineTo(N0.getNode(),
6826               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6827                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6828               ExtLoad.getValue(1));
6829     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6830   }
6831
6832   return SDValue();
6833 }
6834
6835 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6836   SDValue N0 = N->getOperand(0);
6837   EVT VT = N->getValueType(0);
6838
6839   if (VT.isVector()) {
6840     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6841     if (FoldedVOp.getNode()) return FoldedVOp;
6842   }
6843
6844   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6845                          &DAG.getTarget().Options))
6846     return GetNegatedExpression(N0, DAG, LegalOperations);
6847
6848   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6849   // constant pool values.
6850   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6851       !VT.isVector() &&
6852       N0.getNode()->hasOneUse() &&
6853       N0.getOperand(0).getValueType().isInteger()) {
6854     SDValue Int = N0.getOperand(0);
6855     EVT IntVT = Int.getValueType();
6856     if (IntVT.isInteger() && !IntVT.isVector()) {
6857       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6858               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6859       AddToWorkList(Int.getNode());
6860       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6861                          VT, Int);
6862     }
6863   }
6864
6865   // (fneg (fmul c, x)) -> (fmul -c, x)
6866   if (N0.getOpcode() == ISD::FMUL) {
6867     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6868     if (CFP1)
6869       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6870                          N0.getOperand(0),
6871                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6872                                      N0.getOperand(1)));
6873   }
6874
6875   return SDValue();
6876 }
6877
6878 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6879   SDValue N0 = N->getOperand(0);
6880   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6881   EVT VT = N->getValueType(0);
6882
6883   // fold (fceil c1) -> fceil(c1)
6884   if (N0CFP)
6885     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6886
6887   return SDValue();
6888 }
6889
6890 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6891   SDValue N0 = N->getOperand(0);
6892   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6893   EVT VT = N->getValueType(0);
6894
6895   // fold (ftrunc c1) -> ftrunc(c1)
6896   if (N0CFP)
6897     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6898
6899   return SDValue();
6900 }
6901
6902 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6903   SDValue N0 = N->getOperand(0);
6904   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6905   EVT VT = N->getValueType(0);
6906
6907   // fold (ffloor c1) -> ffloor(c1)
6908   if (N0CFP)
6909     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6910
6911   return SDValue();
6912 }
6913
6914 SDValue DAGCombiner::visitFABS(SDNode *N) {
6915   SDValue N0 = N->getOperand(0);
6916   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6917   EVT VT = N->getValueType(0);
6918
6919   if (VT.isVector()) {
6920     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6921     if (FoldedVOp.getNode()) return FoldedVOp;
6922   }
6923
6924   // fold (fabs c1) -> fabs(c1)
6925   if (N0CFP)
6926     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6927   // fold (fabs (fabs x)) -> (fabs x)
6928   if (N0.getOpcode() == ISD::FABS)
6929     return N->getOperand(0);
6930   // fold (fabs (fneg x)) -> (fabs x)
6931   // fold (fabs (fcopysign x, y)) -> (fabs x)
6932   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6933     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6934
6935   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6936   // constant pool values.
6937   if (!TLI.isFAbsFree(VT) &&
6938       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6939       N0.getOperand(0).getValueType().isInteger() &&
6940       !N0.getOperand(0).getValueType().isVector()) {
6941     SDValue Int = N0.getOperand(0);
6942     EVT IntVT = Int.getValueType();
6943     if (IntVT.isInteger() && !IntVT.isVector()) {
6944       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6945              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6946       AddToWorkList(Int.getNode());
6947       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6948                          N->getValueType(0), Int);
6949     }
6950   }
6951
6952   return SDValue();
6953 }
6954
6955 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6956   SDValue Chain = N->getOperand(0);
6957   SDValue N1 = N->getOperand(1);
6958   SDValue N2 = N->getOperand(2);
6959
6960   // If N is a constant we could fold this into a fallthrough or unconditional
6961   // branch. However that doesn't happen very often in normal code, because
6962   // Instcombine/SimplifyCFG should have handled the available opportunities.
6963   // If we did this folding here, it would be necessary to update the
6964   // MachineBasicBlock CFG, which is awkward.
6965
6966   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6967   // on the target.
6968   if (N1.getOpcode() == ISD::SETCC &&
6969       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6970                                    N1.getOperand(0).getValueType())) {
6971     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6972                        Chain, N1.getOperand(2),
6973                        N1.getOperand(0), N1.getOperand(1), N2);
6974   }
6975
6976   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6977       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6978        (N1.getOperand(0).hasOneUse() &&
6979         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6980     SDNode *Trunc = 0;
6981     if (N1.getOpcode() == ISD::TRUNCATE) {
6982       // Look pass the truncate.
6983       Trunc = N1.getNode();
6984       N1 = N1.getOperand(0);
6985     }
6986
6987     // Match this pattern so that we can generate simpler code:
6988     //
6989     //   %a = ...
6990     //   %b = and i32 %a, 2
6991     //   %c = srl i32 %b, 1
6992     //   brcond i32 %c ...
6993     //
6994     // into
6995     //
6996     //   %a = ...
6997     //   %b = and i32 %a, 2
6998     //   %c = setcc eq %b, 0
6999     //   brcond %c ...
7000     //
7001     // This applies only when the AND constant value has one bit set and the
7002     // SRL constant is equal to the log2 of the AND constant. The back-end is
7003     // smart enough to convert the result into a TEST/JMP sequence.
7004     SDValue Op0 = N1.getOperand(0);
7005     SDValue Op1 = N1.getOperand(1);
7006
7007     if (Op0.getOpcode() == ISD::AND &&
7008         Op1.getOpcode() == ISD::Constant) {
7009       SDValue AndOp1 = Op0.getOperand(1);
7010
7011       if (AndOp1.getOpcode() == ISD::Constant) {
7012         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7013
7014         if (AndConst.isPowerOf2() &&
7015             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7016           SDValue SetCC =
7017             DAG.getSetCC(SDLoc(N),
7018                          getSetCCResultType(Op0.getValueType()),
7019                          Op0, DAG.getConstant(0, Op0.getValueType()),
7020                          ISD::SETNE);
7021
7022           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7023                                           MVT::Other, Chain, SetCC, N2);
7024           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7025           // will convert it back to (X & C1) >> C2.
7026           CombineTo(N, NewBRCond, false);
7027           // Truncate is dead.
7028           if (Trunc) {
7029             removeFromWorkList(Trunc);
7030             DAG.DeleteNode(Trunc);
7031           }
7032           // Replace the uses of SRL with SETCC
7033           WorkListRemover DeadNodes(*this);
7034           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7035           removeFromWorkList(N1.getNode());
7036           DAG.DeleteNode(N1.getNode());
7037           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7038         }
7039       }
7040     }
7041
7042     if (Trunc)
7043       // Restore N1 if the above transformation doesn't match.
7044       N1 = N->getOperand(1);
7045   }
7046
7047   // Transform br(xor(x, y)) -> br(x != y)
7048   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7049   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7050     SDNode *TheXor = N1.getNode();
7051     SDValue Op0 = TheXor->getOperand(0);
7052     SDValue Op1 = TheXor->getOperand(1);
7053     if (Op0.getOpcode() == Op1.getOpcode()) {
7054       // Avoid missing important xor optimizations.
7055       SDValue Tmp = visitXOR(TheXor);
7056       if (Tmp.getNode()) {
7057         if (Tmp.getNode() != TheXor) {
7058           DEBUG(dbgs() << "\nReplacing.8 ";
7059                 TheXor->dump(&DAG);
7060                 dbgs() << "\nWith: ";
7061                 Tmp.getNode()->dump(&DAG);
7062                 dbgs() << '\n');
7063           WorkListRemover DeadNodes(*this);
7064           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7065           removeFromWorkList(TheXor);
7066           DAG.DeleteNode(TheXor);
7067           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7068                              MVT::Other, Chain, Tmp, N2);
7069         }
7070
7071         // visitXOR has changed XOR's operands or replaced the XOR completely,
7072         // bail out.
7073         return SDValue(N, 0);
7074       }
7075     }
7076
7077     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7078       bool Equal = false;
7079       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7080         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7081             Op0.getOpcode() == ISD::XOR) {
7082           TheXor = Op0.getNode();
7083           Equal = true;
7084         }
7085
7086       EVT SetCCVT = N1.getValueType();
7087       if (LegalTypes)
7088         SetCCVT = getSetCCResultType(SetCCVT);
7089       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7090                                    SetCCVT,
7091                                    Op0, Op1,
7092                                    Equal ? ISD::SETEQ : ISD::SETNE);
7093       // Replace the uses of XOR with SETCC
7094       WorkListRemover DeadNodes(*this);
7095       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7096       removeFromWorkList(N1.getNode());
7097       DAG.DeleteNode(N1.getNode());
7098       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7099                          MVT::Other, Chain, SetCC, N2);
7100     }
7101   }
7102
7103   return SDValue();
7104 }
7105
7106 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7107 //
7108 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7109   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7110   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7111
7112   // If N is a constant we could fold this into a fallthrough or unconditional
7113   // branch. However that doesn't happen very often in normal code, because
7114   // Instcombine/SimplifyCFG should have handled the available opportunities.
7115   // If we did this folding here, it would be necessary to update the
7116   // MachineBasicBlock CFG, which is awkward.
7117
7118   // Use SimplifySetCC to simplify SETCC's.
7119   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7120                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7121                                false);
7122   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7123
7124   // fold to a simpler setcc
7125   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7126     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7127                        N->getOperand(0), Simp.getOperand(2),
7128                        Simp.getOperand(0), Simp.getOperand(1),
7129                        N->getOperand(4));
7130
7131   return SDValue();
7132 }
7133
7134 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7135 /// uses N as its base pointer and that N may be folded in the load / store
7136 /// addressing mode.
7137 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7138                                     SelectionDAG &DAG,
7139                                     const TargetLowering &TLI) {
7140   EVT VT;
7141   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7142     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7143       return false;
7144     VT = Use->getValueType(0);
7145   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7146     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7147       return false;
7148     VT = ST->getValue().getValueType();
7149   } else
7150     return false;
7151
7152   TargetLowering::AddrMode AM;
7153   if (N->getOpcode() == ISD::ADD) {
7154     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7155     if (Offset)
7156       // [reg +/- imm]
7157       AM.BaseOffs = Offset->getSExtValue();
7158     else
7159       // [reg +/- reg]
7160       AM.Scale = 1;
7161   } else if (N->getOpcode() == ISD::SUB) {
7162     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7163     if (Offset)
7164       // [reg +/- imm]
7165       AM.BaseOffs = -Offset->getSExtValue();
7166     else
7167       // [reg +/- reg]
7168       AM.Scale = 1;
7169   } else
7170     return false;
7171
7172   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7173 }
7174
7175 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7176 /// pre-indexed load / store when the base pointer is an add or subtract
7177 /// and it has other uses besides the load / store. After the
7178 /// transformation, the new indexed load / store has effectively folded
7179 /// the add / subtract in and all of its other uses are redirected to the
7180 /// new load / store.
7181 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7182   if (Level < AfterLegalizeDAG)
7183     return false;
7184
7185   bool isLoad = true;
7186   SDValue Ptr;
7187   EVT VT;
7188   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7189     if (LD->isIndexed())
7190       return false;
7191     VT = LD->getMemoryVT();
7192     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7193         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7194       return false;
7195     Ptr = LD->getBasePtr();
7196   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7197     if (ST->isIndexed())
7198       return false;
7199     VT = ST->getMemoryVT();
7200     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7201         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7202       return false;
7203     Ptr = ST->getBasePtr();
7204     isLoad = false;
7205   } else {
7206     return false;
7207   }
7208
7209   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7210   // out.  There is no reason to make this a preinc/predec.
7211   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7212       Ptr.getNode()->hasOneUse())
7213     return false;
7214
7215   // Ask the target to do addressing mode selection.
7216   SDValue BasePtr;
7217   SDValue Offset;
7218   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7219   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7220     return false;
7221
7222   // Backends without true r+i pre-indexed forms may need to pass a
7223   // constant base with a variable offset so that constant coercion
7224   // will work with the patterns in canonical form.
7225   bool Swapped = false;
7226   if (isa<ConstantSDNode>(BasePtr)) {
7227     std::swap(BasePtr, Offset);
7228     Swapped = true;
7229   }
7230
7231   // Don't create a indexed load / store with zero offset.
7232   if (isa<ConstantSDNode>(Offset) &&
7233       cast<ConstantSDNode>(Offset)->isNullValue())
7234     return false;
7235
7236   // Try turning it into a pre-indexed load / store except when:
7237   // 1) The new base ptr is a frame index.
7238   // 2) If N is a store and the new base ptr is either the same as or is a
7239   //    predecessor of the value being stored.
7240   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7241   //    that would create a cycle.
7242   // 4) All uses are load / store ops that use it as old base ptr.
7243
7244   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7245   // (plus the implicit offset) to a register to preinc anyway.
7246   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7247     return false;
7248
7249   // Check #2.
7250   if (!isLoad) {
7251     SDValue Val = cast<StoreSDNode>(N)->getValue();
7252     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7253       return false;
7254   }
7255
7256   // If the offset is a constant, there may be other adds of constants that
7257   // can be folded with this one. We should do this to avoid having to keep
7258   // a copy of the original base pointer.
7259   SmallVector<SDNode *, 16> OtherUses;
7260   if (isa<ConstantSDNode>(Offset))
7261     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7262          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7263       SDNode *Use = *I;
7264       if (Use == Ptr.getNode())
7265         continue;
7266
7267       if (Use->isPredecessorOf(N))
7268         continue;
7269
7270       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7271         OtherUses.clear();
7272         break;
7273       }
7274
7275       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7276       if (Op1.getNode() == BasePtr.getNode())
7277         std::swap(Op0, Op1);
7278       assert(Op0.getNode() == BasePtr.getNode() &&
7279              "Use of ADD/SUB but not an operand");
7280
7281       if (!isa<ConstantSDNode>(Op1)) {
7282         OtherUses.clear();
7283         break;
7284       }
7285
7286       // FIXME: In some cases, we can be smarter about this.
7287       if (Op1.getValueType() != Offset.getValueType()) {
7288         OtherUses.clear();
7289         break;
7290       }
7291
7292       OtherUses.push_back(Use);
7293     }
7294
7295   if (Swapped)
7296     std::swap(BasePtr, Offset);
7297
7298   // Now check for #3 and #4.
7299   bool RealUse = false;
7300
7301   // Caches for hasPredecessorHelper
7302   SmallPtrSet<const SDNode *, 32> Visited;
7303   SmallVector<const SDNode *, 16> Worklist;
7304
7305   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7306          E = Ptr.getNode()->use_end(); I != E; ++I) {
7307     SDNode *Use = *I;
7308     if (Use == N)
7309       continue;
7310     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7311       return false;
7312
7313     // If Ptr may be folded in addressing mode of other use, then it's
7314     // not profitable to do this transformation.
7315     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7316       RealUse = true;
7317   }
7318
7319   if (!RealUse)
7320     return false;
7321
7322   SDValue Result;
7323   if (isLoad)
7324     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7325                                 BasePtr, Offset, AM);
7326   else
7327     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7328                                  BasePtr, Offset, AM);
7329   ++PreIndexedNodes;
7330   ++NodesCombined;
7331   DEBUG(dbgs() << "\nReplacing.4 ";
7332         N->dump(&DAG);
7333         dbgs() << "\nWith: ";
7334         Result.getNode()->dump(&DAG);
7335         dbgs() << '\n');
7336   WorkListRemover DeadNodes(*this);
7337   if (isLoad) {
7338     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7339     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7340   } else {
7341     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7342   }
7343
7344   // Finally, since the node is now dead, remove it from the graph.
7345   DAG.DeleteNode(N);
7346
7347   if (Swapped)
7348     std::swap(BasePtr, Offset);
7349
7350   // Replace other uses of BasePtr that can be updated to use Ptr
7351   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7352     unsigned OffsetIdx = 1;
7353     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7354       OffsetIdx = 0;
7355     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7356            BasePtr.getNode() && "Expected BasePtr operand");
7357
7358     // We need to replace ptr0 in the following expression:
7359     //   x0 * offset0 + y0 * ptr0 = t0
7360     // knowing that
7361     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7362     //
7363     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7364     // indexed load/store and the expresion that needs to be re-written.
7365     //
7366     // Therefore, we have:
7367     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7368
7369     ConstantSDNode *CN =
7370       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7371     int X0, X1, Y0, Y1;
7372     APInt Offset0 = CN->getAPIntValue();
7373     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7374
7375     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7376     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7377     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7378     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7379
7380     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7381
7382     APInt CNV = Offset0;
7383     if (X0 < 0) CNV = -CNV;
7384     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7385     else CNV = CNV - Offset1;
7386
7387     // We can now generate the new expression.
7388     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7389     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7390
7391     SDValue NewUse = DAG.getNode(Opcode,
7392                                  SDLoc(OtherUses[i]),
7393                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7394     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7395     removeFromWorkList(OtherUses[i]);
7396     DAG.DeleteNode(OtherUses[i]);
7397   }
7398
7399   // Replace the uses of Ptr with uses of the updated base value.
7400   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7401   removeFromWorkList(Ptr.getNode());
7402   DAG.DeleteNode(Ptr.getNode());
7403
7404   return true;
7405 }
7406
7407 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7408 /// add / sub of the base pointer node into a post-indexed load / store.
7409 /// The transformation folded the add / subtract into the new indexed
7410 /// load / store effectively and all of its uses are redirected to the
7411 /// new load / store.
7412 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7413   if (Level < AfterLegalizeDAG)
7414     return false;
7415
7416   bool isLoad = true;
7417   SDValue Ptr;
7418   EVT VT;
7419   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7420     if (LD->isIndexed())
7421       return false;
7422     VT = LD->getMemoryVT();
7423     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7424         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7425       return false;
7426     Ptr = LD->getBasePtr();
7427   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7428     if (ST->isIndexed())
7429       return false;
7430     VT = ST->getMemoryVT();
7431     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7432         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7433       return false;
7434     Ptr = ST->getBasePtr();
7435     isLoad = false;
7436   } else {
7437     return false;
7438   }
7439
7440   if (Ptr.getNode()->hasOneUse())
7441     return false;
7442
7443   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7444          E = Ptr.getNode()->use_end(); I != E; ++I) {
7445     SDNode *Op = *I;
7446     if (Op == N ||
7447         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7448       continue;
7449
7450     SDValue BasePtr;
7451     SDValue Offset;
7452     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7453     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7454       // Don't create a indexed load / store with zero offset.
7455       if (isa<ConstantSDNode>(Offset) &&
7456           cast<ConstantSDNode>(Offset)->isNullValue())
7457         continue;
7458
7459       // Try turning it into a post-indexed load / store except when
7460       // 1) All uses are load / store ops that use it as base ptr (and
7461       //    it may be folded as addressing mmode).
7462       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7463       //    nor a successor of N. Otherwise, if Op is folded that would
7464       //    create a cycle.
7465
7466       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7467         continue;
7468
7469       // Check for #1.
7470       bool TryNext = false;
7471       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7472              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7473         SDNode *Use = *II;
7474         if (Use == Ptr.getNode())
7475           continue;
7476
7477         // If all the uses are load / store addresses, then don't do the
7478         // transformation.
7479         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7480           bool RealUse = false;
7481           for (SDNode::use_iterator III = Use->use_begin(),
7482                  EEE = Use->use_end(); III != EEE; ++III) {
7483             SDNode *UseUse = *III;
7484             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7485               RealUse = true;
7486           }
7487
7488           if (!RealUse) {
7489             TryNext = true;
7490             break;
7491           }
7492         }
7493       }
7494
7495       if (TryNext)
7496         continue;
7497
7498       // Check for #2
7499       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7500         SDValue Result = isLoad
7501           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7502                                BasePtr, Offset, AM)
7503           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7504                                 BasePtr, Offset, AM);
7505         ++PostIndexedNodes;
7506         ++NodesCombined;
7507         DEBUG(dbgs() << "\nReplacing.5 ";
7508               N->dump(&DAG);
7509               dbgs() << "\nWith: ";
7510               Result.getNode()->dump(&DAG);
7511               dbgs() << '\n');
7512         WorkListRemover DeadNodes(*this);
7513         if (isLoad) {
7514           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7515           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7516         } else {
7517           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7518         }
7519
7520         // Finally, since the node is now dead, remove it from the graph.
7521         DAG.DeleteNode(N);
7522
7523         // Replace the uses of Use with uses of the updated base value.
7524         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7525                                       Result.getValue(isLoad ? 1 : 0));
7526         removeFromWorkList(Op);
7527         DAG.DeleteNode(Op);
7528         return true;
7529       }
7530     }
7531   }
7532
7533   return false;
7534 }
7535
7536 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7537   LoadSDNode *LD  = cast<LoadSDNode>(N);
7538   SDValue Chain = LD->getChain();
7539   SDValue Ptr   = LD->getBasePtr();
7540
7541   // If load is not volatile and there are no uses of the loaded value (and
7542   // the updated indexed value in case of indexed loads), change uses of the
7543   // chain value into uses of the chain input (i.e. delete the dead load).
7544   if (!LD->isVolatile()) {
7545     if (N->getValueType(1) == MVT::Other) {
7546       // Unindexed loads.
7547       if (!N->hasAnyUseOfValue(0)) {
7548         // It's not safe to use the two value CombineTo variant here. e.g.
7549         // v1, chain2 = load chain1, loc
7550         // v2, chain3 = load chain2, loc
7551         // v3         = add v2, c
7552         // Now we replace use of chain2 with chain1.  This makes the second load
7553         // isomorphic to the one we are deleting, and thus makes this load live.
7554         DEBUG(dbgs() << "\nReplacing.6 ";
7555               N->dump(&DAG);
7556               dbgs() << "\nWith chain: ";
7557               Chain.getNode()->dump(&DAG);
7558               dbgs() << "\n");
7559         WorkListRemover DeadNodes(*this);
7560         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7561
7562         if (N->use_empty()) {
7563           removeFromWorkList(N);
7564           DAG.DeleteNode(N);
7565         }
7566
7567         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7568       }
7569     } else {
7570       // Indexed loads.
7571       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7572       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7573         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7574         DEBUG(dbgs() << "\nReplacing.7 ";
7575               N->dump(&DAG);
7576               dbgs() << "\nWith: ";
7577               Undef.getNode()->dump(&DAG);
7578               dbgs() << " and 2 other values\n");
7579         WorkListRemover DeadNodes(*this);
7580         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7581         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7582                                       DAG.getUNDEF(N->getValueType(1)));
7583         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7584         removeFromWorkList(N);
7585         DAG.DeleteNode(N);
7586         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7587       }
7588     }
7589   }
7590
7591   // If this load is directly stored, replace the load value with the stored
7592   // value.
7593   // TODO: Handle store large -> read small portion.
7594   // TODO: Handle TRUNCSTORE/LOADEXT
7595   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7596     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7597       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7598       if (PrevST->getBasePtr() == Ptr &&
7599           PrevST->getValue().getValueType() == N->getValueType(0))
7600       return CombineTo(N, Chain.getOperand(1), Chain);
7601     }
7602   }
7603
7604   // Try to infer better alignment information than the load already has.
7605   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7606     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7607       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7608         SDValue NewLoad =
7609                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7610                               LD->getValueType(0),
7611                               Chain, Ptr, LD->getPointerInfo(),
7612                               LD->getMemoryVT(),
7613                               LD->isVolatile(), LD->isNonTemporal(), Align,
7614                               LD->getTBAAInfo());
7615         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7616       }
7617     }
7618   }
7619
7620   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7621     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7622   if (UseAA) {
7623     // Walk up chain skipping non-aliasing memory nodes.
7624     SDValue BetterChain = FindBetterChain(N, Chain);
7625
7626     // If there is a better chain.
7627     if (Chain != BetterChain) {
7628       SDValue ReplLoad;
7629
7630       // Replace the chain to void dependency.
7631       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7632         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7633                                BetterChain, Ptr, LD->getMemOperand());
7634       } else {
7635         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7636                                   LD->getValueType(0),
7637                                   BetterChain, Ptr, LD->getMemoryVT(),
7638                                   LD->getMemOperand());
7639       }
7640
7641       // Create token factor to keep old chain connected.
7642       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7643                                   MVT::Other, Chain, ReplLoad.getValue(1));
7644
7645       // Make sure the new and old chains are cleaned up.
7646       AddToWorkList(Token.getNode());
7647
7648       // Replace uses with load result and token factor. Don't add users
7649       // to work list.
7650       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7651     }
7652   }
7653
7654   // Try transforming N to an indexed load.
7655   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7656     return SDValue(N, 0);
7657
7658   // Try to slice up N to more direct loads if the slices are mapped to
7659   // different register banks or pairing can take place.
7660   if (SliceUpLoad(N))
7661     return SDValue(N, 0);
7662
7663   return SDValue();
7664 }
7665
7666 namespace {
7667 /// \brief Helper structure used to slice a load in smaller loads.
7668 /// Basically a slice is obtained from the following sequence:
7669 /// Origin = load Ty1, Base
7670 /// Shift = srl Ty1 Origin, CstTy Amount
7671 /// Inst = trunc Shift to Ty2
7672 ///
7673 /// Then, it will be rewriten into:
7674 /// Slice = load SliceTy, Base + SliceOffset
7675 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7676 ///
7677 /// SliceTy is deduced from the number of bits that are actually used to
7678 /// build Inst.
7679 struct LoadedSlice {
7680   /// \brief Helper structure used to compute the cost of a slice.
7681   struct Cost {
7682     /// Are we optimizing for code size.
7683     bool ForCodeSize;
7684     /// Various cost.
7685     unsigned Loads;
7686     unsigned Truncates;
7687     unsigned CrossRegisterBanksCopies;
7688     unsigned ZExts;
7689     unsigned Shift;
7690
7691     Cost(bool ForCodeSize = false)
7692         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7693           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7694
7695     /// \brief Get the cost of one isolated slice.
7696     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7697         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7698           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7699       EVT TruncType = LS.Inst->getValueType(0);
7700       EVT LoadedType = LS.getLoadedType();
7701       if (TruncType != LoadedType &&
7702           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7703         ZExts = 1;
7704     }
7705
7706     /// \brief Account for slicing gain in the current cost.
7707     /// Slicing provide a few gains like removing a shift or a
7708     /// truncate. This method allows to grow the cost of the original
7709     /// load with the gain from this slice.
7710     void addSliceGain(const LoadedSlice &LS) {
7711       // Each slice saves a truncate.
7712       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7713       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7714                               LS.Inst->getOperand(0).getValueType()))
7715         ++Truncates;
7716       // If there is a shift amount, this slice gets rid of it.
7717       if (LS.Shift)
7718         ++Shift;
7719       // If this slice can merge a cross register bank copy, account for it.
7720       if (LS.canMergeExpensiveCrossRegisterBankCopy())
7721         ++CrossRegisterBanksCopies;
7722     }
7723
7724     Cost &operator+=(const Cost &RHS) {
7725       Loads += RHS.Loads;
7726       Truncates += RHS.Truncates;
7727       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7728       ZExts += RHS.ZExts;
7729       Shift += RHS.Shift;
7730       return *this;
7731     }
7732
7733     bool operator==(const Cost &RHS) const {
7734       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7735              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7736              ZExts == RHS.ZExts && Shift == RHS.Shift;
7737     }
7738
7739     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7740
7741     bool operator<(const Cost &RHS) const {
7742       // Assume cross register banks copies are as expensive as loads.
7743       // FIXME: Do we want some more target hooks?
7744       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7745       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7746       // Unless we are optimizing for code size, consider the
7747       // expensive operation first.
7748       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7749         return ExpensiveOpsLHS < ExpensiveOpsRHS;
7750       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7751              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7752     }
7753
7754     bool operator>(const Cost &RHS) const { return RHS < *this; }
7755
7756     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7757
7758     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7759   };
7760   // The last instruction that represent the slice. This should be a
7761   // truncate instruction.
7762   SDNode *Inst;
7763   // The original load instruction.
7764   LoadSDNode *Origin;
7765   // The right shift amount in bits from the original load.
7766   unsigned Shift;
7767   // The DAG from which Origin came from.
7768   // This is used to get some contextual information about legal types, etc.
7769   SelectionDAG *DAG;
7770
7771   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7772               unsigned Shift = 0, SelectionDAG *DAG = NULL)
7773       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7774
7775   LoadedSlice(const LoadedSlice &LS)
7776       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7777
7778   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7779   /// \return Result is \p BitWidth and has used bits set to 1 and
7780   ///         not used bits set to 0.
7781   APInt getUsedBits() const {
7782     // Reproduce the trunc(lshr) sequence:
7783     // - Start from the truncated value.
7784     // - Zero extend to the desired bit width.
7785     // - Shift left.
7786     assert(Origin && "No original load to compare against.");
7787     unsigned BitWidth = Origin->getValueSizeInBits(0);
7788     assert(Inst && "This slice is not bound to an instruction");
7789     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7790            "Extracted slice is bigger than the whole type!");
7791     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7792     UsedBits.setAllBits();
7793     UsedBits = UsedBits.zext(BitWidth);
7794     UsedBits <<= Shift;
7795     return UsedBits;
7796   }
7797
7798   /// \brief Get the size of the slice to be loaded in bytes.
7799   unsigned getLoadedSize() const {
7800     unsigned SliceSize = getUsedBits().countPopulation();
7801     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7802     return SliceSize / 8;
7803   }
7804
7805   /// \brief Get the type that will be loaded for this slice.
7806   /// Note: This may not be the final type for the slice.
7807   EVT getLoadedType() const {
7808     assert(DAG && "Missing context");
7809     LLVMContext &Ctxt = *DAG->getContext();
7810     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7811   }
7812
7813   /// \brief Get the alignment of the load used for this slice.
7814   unsigned getAlignment() const {
7815     unsigned Alignment = Origin->getAlignment();
7816     unsigned Offset = getOffsetFromBase();
7817     if (Offset != 0)
7818       Alignment = MinAlign(Alignment, Alignment + Offset);
7819     return Alignment;
7820   }
7821
7822   /// \brief Check if this slice can be rewritten with legal operations.
7823   bool isLegal() const {
7824     // An invalid slice is not legal.
7825     if (!Origin || !Inst || !DAG)
7826       return false;
7827
7828     // Offsets are for indexed load only, we do not handle that.
7829     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7830       return false;
7831
7832     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7833
7834     // Check that the type is legal.
7835     EVT SliceType = getLoadedType();
7836     if (!TLI.isTypeLegal(SliceType))
7837       return false;
7838
7839     // Check that the load is legal for this type.
7840     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7841       return false;
7842
7843     // Check that the offset can be computed.
7844     // 1. Check its type.
7845     EVT PtrType = Origin->getBasePtr().getValueType();
7846     if (PtrType == MVT::Untyped || PtrType.isExtended())
7847       return false;
7848
7849     // 2. Check that it fits in the immediate.
7850     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7851       return false;
7852
7853     // 3. Check that the computation is legal.
7854     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7855       return false;
7856
7857     // Check that the zext is legal if it needs one.
7858     EVT TruncateType = Inst->getValueType(0);
7859     if (TruncateType != SliceType &&
7860         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7861       return false;
7862
7863     return true;
7864   }
7865
7866   /// \brief Get the offset in bytes of this slice in the original chunk of
7867   /// bits.
7868   /// \pre DAG != NULL.
7869   uint64_t getOffsetFromBase() const {
7870     assert(DAG && "Missing context.");
7871     bool IsBigEndian =
7872         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
7873     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
7874     uint64_t Offset = Shift / 8;
7875     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
7876     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
7877            "The size of the original loaded type is not a multiple of a"
7878            " byte.");
7879     // If Offset is bigger than TySizeInBytes, it means we are loading all
7880     // zeros. This should have been optimized before in the process.
7881     assert(TySizeInBytes > Offset &&
7882            "Invalid shift amount for given loaded size");
7883     if (IsBigEndian)
7884       Offset = TySizeInBytes - Offset - getLoadedSize();
7885     return Offset;
7886   }
7887
7888   /// \brief Generate the sequence of instructions to load the slice
7889   /// represented by this object and redirect the uses of this slice to
7890   /// this new sequence of instructions.
7891   /// \pre this->Inst && this->Origin are valid Instructions and this
7892   /// object passed the legal check: LoadedSlice::isLegal returned true.
7893   /// \return The last instruction of the sequence used to load the slice.
7894   SDValue loadSlice() const {
7895     assert(Inst && Origin && "Unable to replace a non-existing slice.");
7896     const SDValue &OldBaseAddr = Origin->getBasePtr();
7897     SDValue BaseAddr = OldBaseAddr;
7898     // Get the offset in that chunk of bytes w.r.t. the endianess.
7899     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
7900     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
7901     if (Offset) {
7902       // BaseAddr = BaseAddr + Offset.
7903       EVT ArithType = BaseAddr.getValueType();
7904       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
7905                               DAG->getConstant(Offset, ArithType));
7906     }
7907
7908     // Create the type of the loaded slice according to its size.
7909     EVT SliceType = getLoadedType();
7910
7911     // Create the load for the slice.
7912     SDValue LastInst = DAG->getLoad(
7913         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
7914         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
7915         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
7916     // If the final type is not the same as the loaded type, this means that
7917     // we have to pad with zero. Create a zero extend for that.
7918     EVT FinalType = Inst->getValueType(0);
7919     if (SliceType != FinalType)
7920       LastInst =
7921           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
7922     return LastInst;
7923   }
7924
7925   /// \brief Check if this slice can be merged with an expensive cross register
7926   /// bank copy. E.g.,
7927   /// i = load i32
7928   /// f = bitcast i32 i to float
7929   bool canMergeExpensiveCrossRegisterBankCopy() const {
7930     if (!Inst || !Inst->hasOneUse())
7931       return false;
7932     SDNode *Use = *Inst->use_begin();
7933     if (Use->getOpcode() != ISD::BITCAST)
7934       return false;
7935     assert(DAG && "Missing context");
7936     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7937     EVT ResVT = Use->getValueType(0);
7938     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
7939     const TargetRegisterClass *ArgRC =
7940         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
7941     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
7942       return false;
7943
7944     // At this point, we know that we perform a cross-register-bank copy.
7945     // Check if it is expensive.
7946     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
7947     // Assume bitcasts are cheap, unless both register classes do not
7948     // explicitly share a common sub class.
7949     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
7950       return false;
7951
7952     // Check if it will be merged with the load.
7953     // 1. Check the alignment constraint.
7954     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
7955         ResVT.getTypeForEVT(*DAG->getContext()));
7956
7957     if (RequiredAlignment > getAlignment())
7958       return false;
7959
7960     // 2. Check that the load is a legal operation for that type.
7961     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
7962       return false;
7963
7964     // 3. Check that we do not have a zext in the way.
7965     if (Inst->getValueType(0) != getLoadedType())
7966       return false;
7967
7968     return true;
7969   }
7970 };
7971 }
7972
7973 /// \brief Sorts LoadedSlice according to their offset.
7974 struct LoadedSliceSorter {
7975   bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
7976     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
7977     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
7978   }
7979 };
7980
7981 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
7982 /// \p UsedBits looks like 0..0 1..1 0..0.
7983 static bool areUsedBitsDense(const APInt &UsedBits) {
7984   // If all the bits are one, this is dense!
7985   if (UsedBits.isAllOnesValue())
7986     return true;
7987
7988   // Get rid of the unused bits on the right.
7989   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
7990   // Get rid of the unused bits on the left.
7991   if (NarrowedUsedBits.countLeadingZeros())
7992     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
7993   // Check that the chunk of bits is completely used.
7994   return NarrowedUsedBits.isAllOnesValue();
7995 }
7996
7997 /// \brief Check whether or not \p First and \p Second are next to each other
7998 /// in memory. This means that there is no hole between the bits loaded
7999 /// by \p First and the bits loaded by \p Second.
8000 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8001                                      const LoadedSlice &Second) {
8002   assert(First.Origin == Second.Origin && First.Origin &&
8003          "Unable to match different memory origins.");
8004   APInt UsedBits = First.getUsedBits();
8005   assert((UsedBits & Second.getUsedBits()) == 0 &&
8006          "Slices are not supposed to overlap.");
8007   UsedBits |= Second.getUsedBits();
8008   return areUsedBitsDense(UsedBits);
8009 }
8010
8011 /// \brief Adjust the \p GlobalLSCost according to the target
8012 /// paring capabilities and the layout of the slices.
8013 /// \pre \p GlobalLSCost should account for at least as many loads as
8014 /// there is in the slices in \p LoadedSlices.
8015 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8016                                  LoadedSlice::Cost &GlobalLSCost) {
8017   unsigned NumberOfSlices = LoadedSlices.size();
8018   // If there is less than 2 elements, no pairing is possible.
8019   if (NumberOfSlices < 2)
8020     return;
8021
8022   // Sort the slices so that elements that are likely to be next to each
8023   // other in memory are next to each other in the list.
8024   std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8025   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8026   // First (resp. Second) is the first (resp. Second) potentially candidate
8027   // to be placed in a paired load.
8028   const LoadedSlice *First = NULL;
8029   const LoadedSlice *Second = NULL;
8030   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8031                 // Set the beginning of the pair.
8032                                                            First = Second) {
8033
8034     Second = &LoadedSlices[CurrSlice];
8035
8036     // If First is NULL, it means we start a new pair.
8037     // Get to the next slice.
8038     if (!First)
8039       continue;
8040
8041     EVT LoadedType = First->getLoadedType();
8042
8043     // If the types of the slices are different, we cannot pair them.
8044     if (LoadedType != Second->getLoadedType())
8045       continue;
8046
8047     // Check if the target supplies paired loads for this type.
8048     unsigned RequiredAlignment = 0;
8049     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8050       // move to the next pair, this type is hopeless.
8051       Second = NULL;
8052       continue;
8053     }
8054     // Check if we meet the alignment requirement.
8055     if (RequiredAlignment > First->getAlignment())
8056       continue;
8057
8058     // Check that both loads are next to each other in memory.
8059     if (!areSlicesNextToEachOther(*First, *Second))
8060       continue;
8061
8062     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8063     --GlobalLSCost.Loads;
8064     // Move to the next pair.
8065     Second = NULL;
8066   }
8067 }
8068
8069 /// \brief Check the profitability of all involved LoadedSlice.
8070 /// Currently, it is considered profitable if there is exactly two
8071 /// involved slices (1) which are (2) next to each other in memory, and
8072 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8073 ///
8074 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8075 /// the elements themselves.
8076 ///
8077 /// FIXME: When the cost model will be mature enough, we can relax
8078 /// constraints (1) and (2).
8079 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8080                                 const APInt &UsedBits, bool ForCodeSize) {
8081   unsigned NumberOfSlices = LoadedSlices.size();
8082   if (StressLoadSlicing)
8083     return NumberOfSlices > 1;
8084
8085   // Check (1).
8086   if (NumberOfSlices != 2)
8087     return false;
8088
8089   // Check (2).
8090   if (!areUsedBitsDense(UsedBits))
8091     return false;
8092
8093   // Check (3).
8094   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8095   // The original code has one big load.
8096   OrigCost.Loads = 1;
8097   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8098     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8099     // Accumulate the cost of all the slices.
8100     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8101     GlobalSlicingCost += SliceCost;
8102
8103     // Account as cost in the original configuration the gain obtained
8104     // with the current slices.
8105     OrigCost.addSliceGain(LS);
8106   }
8107
8108   // If the target supports paired load, adjust the cost accordingly.
8109   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8110   return OrigCost > GlobalSlicingCost;
8111 }
8112
8113 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8114 /// operations, split it in the various pieces being extracted.
8115 ///
8116 /// This sort of thing is introduced by SROA.
8117 /// This slicing takes care not to insert overlapping loads.
8118 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8119 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8120   if (Level < AfterLegalizeDAG)
8121     return false;
8122
8123   LoadSDNode *LD = cast<LoadSDNode>(N);
8124   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8125       !LD->getValueType(0).isInteger())
8126     return false;
8127
8128   // Keep track of already used bits to detect overlapping values.
8129   // In that case, we will just abort the transformation.
8130   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8131
8132   SmallVector<LoadedSlice, 4> LoadedSlices;
8133
8134   // Check if this load is used as several smaller chunks of bits.
8135   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8136   // of computation for each trunc.
8137   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8138        UI != UIEnd; ++UI) {
8139     // Skip the uses of the chain.
8140     if (UI.getUse().getResNo() != 0)
8141       continue;
8142
8143     SDNode *User = *UI;
8144     unsigned Shift = 0;
8145
8146     // Check if this is a trunc(lshr).
8147     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8148         isa<ConstantSDNode>(User->getOperand(1))) {
8149       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8150       User = *User->use_begin();
8151     }
8152
8153     // At this point, User is a Truncate, iff we encountered, trunc or
8154     // trunc(lshr).
8155     if (User->getOpcode() != ISD::TRUNCATE)
8156       return false;
8157
8158     // The width of the type must be a power of 2 and greater than 8-bits.
8159     // Otherwise the load cannot be represented in LLVM IR.
8160     // Moreover, if we shifted with a non-8-bits multiple, the slice
8161     // will be accross several bytes. We do not support that.
8162     unsigned Width = User->getValueSizeInBits(0);
8163     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8164       return 0;
8165
8166     // Build the slice for this chain of computations.
8167     LoadedSlice LS(User, LD, Shift, &DAG);
8168     APInt CurrentUsedBits = LS.getUsedBits();
8169
8170     // Check if this slice overlaps with another.
8171     if ((CurrentUsedBits & UsedBits) != 0)
8172       return false;
8173     // Update the bits used globally.
8174     UsedBits |= CurrentUsedBits;
8175
8176     // Check if the new slice would be legal.
8177     if (!LS.isLegal())
8178       return false;
8179
8180     // Record the slice.
8181     LoadedSlices.push_back(LS);
8182   }
8183
8184   // Abort slicing if it does not seem to be profitable.
8185   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8186     return false;
8187
8188   ++SlicedLoads;
8189
8190   // Rewrite each chain to use an independent load.
8191   // By construction, each chain can be represented by a unique load.
8192
8193   // Prepare the argument for the new token factor for all the slices.
8194   SmallVector<SDValue, 8> ArgChains;
8195   for (SmallVectorImpl<LoadedSlice>::const_iterator
8196            LSIt = LoadedSlices.begin(),
8197            LSItEnd = LoadedSlices.end();
8198        LSIt != LSItEnd; ++LSIt) {
8199     SDValue SliceInst = LSIt->loadSlice();
8200     CombineTo(LSIt->Inst, SliceInst, true);
8201     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8202       SliceInst = SliceInst.getOperand(0);
8203     assert(SliceInst->getOpcode() == ISD::LOAD &&
8204            "It takes more than a zext to get to the loaded slice!!");
8205     ArgChains.push_back(SliceInst.getValue(1));
8206   }
8207
8208   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8209                               &ArgChains[0], ArgChains.size());
8210   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8211   return true;
8212 }
8213
8214 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8215 /// load is having specific bytes cleared out.  If so, return the byte size
8216 /// being masked out and the shift amount.
8217 static std::pair<unsigned, unsigned>
8218 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8219   std::pair<unsigned, unsigned> Result(0, 0);
8220
8221   // Check for the structure we're looking for.
8222   if (V->getOpcode() != ISD::AND ||
8223       !isa<ConstantSDNode>(V->getOperand(1)) ||
8224       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8225     return Result;
8226
8227   // Check the chain and pointer.
8228   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8229   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8230
8231   // The store should be chained directly to the load or be an operand of a
8232   // tokenfactor.
8233   if (LD == Chain.getNode())
8234     ; // ok.
8235   else if (Chain->getOpcode() != ISD::TokenFactor)
8236     return Result; // Fail.
8237   else {
8238     bool isOk = false;
8239     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8240       if (Chain->getOperand(i).getNode() == LD) {
8241         isOk = true;
8242         break;
8243       }
8244     if (!isOk) return Result;
8245   }
8246
8247   // This only handles simple types.
8248   if (V.getValueType() != MVT::i16 &&
8249       V.getValueType() != MVT::i32 &&
8250       V.getValueType() != MVT::i64)
8251     return Result;
8252
8253   // Check the constant mask.  Invert it so that the bits being masked out are
8254   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8255   // follow the sign bit for uniformity.
8256   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8257   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8258   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8259   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8260   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8261   if (NotMaskLZ == 64) return Result;  // All zero mask.
8262
8263   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8264   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8265     return Result;
8266
8267   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8268   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8269     NotMaskLZ -= 64-V.getValueSizeInBits();
8270
8271   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8272   switch (MaskedBytes) {
8273   case 1:
8274   case 2:
8275   case 4: break;
8276   default: return Result; // All one mask, or 5-byte mask.
8277   }
8278
8279   // Verify that the first bit starts at a multiple of mask so that the access
8280   // is aligned the same as the access width.
8281   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8282
8283   Result.first = MaskedBytes;
8284   Result.second = NotMaskTZ/8;
8285   return Result;
8286 }
8287
8288
8289 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8290 /// provides a value as specified by MaskInfo.  If so, replace the specified
8291 /// store with a narrower store of truncated IVal.
8292 static SDNode *
8293 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8294                                 SDValue IVal, StoreSDNode *St,
8295                                 DAGCombiner *DC) {
8296   unsigned NumBytes = MaskInfo.first;
8297   unsigned ByteShift = MaskInfo.second;
8298   SelectionDAG &DAG = DC->getDAG();
8299
8300   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8301   // that uses this.  If not, this is not a replacement.
8302   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8303                                   ByteShift*8, (ByteShift+NumBytes)*8);
8304   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8305
8306   // Check that it is legal on the target to do this.  It is legal if the new
8307   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8308   // legalization.
8309   MVT VT = MVT::getIntegerVT(NumBytes*8);
8310   if (!DC->isTypeLegal(VT))
8311     return 0;
8312
8313   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8314   // shifted by ByteShift and truncated down to NumBytes.
8315   if (ByteShift)
8316     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8317                        DAG.getConstant(ByteShift*8,
8318                                     DC->getShiftAmountTy(IVal.getValueType())));
8319
8320   // Figure out the offset for the store and the alignment of the access.
8321   unsigned StOffset;
8322   unsigned NewAlign = St->getAlignment();
8323
8324   if (DAG.getTargetLoweringInfo().isLittleEndian())
8325     StOffset = ByteShift;
8326   else
8327     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8328
8329   SDValue Ptr = St->getBasePtr();
8330   if (StOffset) {
8331     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8332                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8333     NewAlign = MinAlign(NewAlign, StOffset);
8334   }
8335
8336   // Truncate down to the new size.
8337   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8338
8339   ++OpsNarrowed;
8340   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8341                       St->getPointerInfo().getWithOffset(StOffset),
8342                       false, false, NewAlign).getNode();
8343 }
8344
8345
8346 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8347 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8348 /// of the loaded bits, try narrowing the load and store if it would end up
8349 /// being a win for performance or code size.
8350 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8351   StoreSDNode *ST  = cast<StoreSDNode>(N);
8352   if (ST->isVolatile())
8353     return SDValue();
8354
8355   SDValue Chain = ST->getChain();
8356   SDValue Value = ST->getValue();
8357   SDValue Ptr   = ST->getBasePtr();
8358   EVT VT = Value.getValueType();
8359
8360   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8361     return SDValue();
8362
8363   unsigned Opc = Value.getOpcode();
8364
8365   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8366   // is a byte mask indicating a consecutive number of bytes, check to see if
8367   // Y is known to provide just those bytes.  If so, we try to replace the
8368   // load + replace + store sequence with a single (narrower) store, which makes
8369   // the load dead.
8370   if (Opc == ISD::OR) {
8371     std::pair<unsigned, unsigned> MaskedLoad;
8372     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8373     if (MaskedLoad.first)
8374       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8375                                                   Value.getOperand(1), ST,this))
8376         return SDValue(NewST, 0);
8377
8378     // Or is commutative, so try swapping X and Y.
8379     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8380     if (MaskedLoad.first)
8381       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8382                                                   Value.getOperand(0), ST,this))
8383         return SDValue(NewST, 0);
8384   }
8385
8386   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8387       Value.getOperand(1).getOpcode() != ISD::Constant)
8388     return SDValue();
8389
8390   SDValue N0 = Value.getOperand(0);
8391   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8392       Chain == SDValue(N0.getNode(), 1)) {
8393     LoadSDNode *LD = cast<LoadSDNode>(N0);
8394     if (LD->getBasePtr() != Ptr ||
8395         LD->getPointerInfo().getAddrSpace() !=
8396         ST->getPointerInfo().getAddrSpace())
8397       return SDValue();
8398
8399     // Find the type to narrow it the load / op / store to.
8400     SDValue N1 = Value.getOperand(1);
8401     unsigned BitWidth = N1.getValueSizeInBits();
8402     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8403     if (Opc == ISD::AND)
8404       Imm ^= APInt::getAllOnesValue(BitWidth);
8405     if (Imm == 0 || Imm.isAllOnesValue())
8406       return SDValue();
8407     unsigned ShAmt = Imm.countTrailingZeros();
8408     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8409     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8410     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8411     while (NewBW < BitWidth &&
8412            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8413              TLI.isNarrowingProfitable(VT, NewVT))) {
8414       NewBW = NextPowerOf2(NewBW);
8415       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8416     }
8417     if (NewBW >= BitWidth)
8418       return SDValue();
8419
8420     // If the lsb changed does not start at the type bitwidth boundary,
8421     // start at the previous one.
8422     if (ShAmt % NewBW)
8423       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8424     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8425                                    std::min(BitWidth, ShAmt + NewBW));
8426     if ((Imm & Mask) == Imm) {
8427       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8428       if (Opc == ISD::AND)
8429         NewImm ^= APInt::getAllOnesValue(NewBW);
8430       uint64_t PtrOff = ShAmt / 8;
8431       // For big endian targets, we need to adjust the offset to the pointer to
8432       // load the correct bytes.
8433       if (TLI.isBigEndian())
8434         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8435
8436       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8437       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8438       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8439         return SDValue();
8440
8441       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8442                                    Ptr.getValueType(), Ptr,
8443                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8444       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8445                                   LD->getChain(), NewPtr,
8446                                   LD->getPointerInfo().getWithOffset(PtrOff),
8447                                   LD->isVolatile(), LD->isNonTemporal(),
8448                                   LD->isInvariant(), NewAlign,
8449                                   LD->getTBAAInfo());
8450       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8451                                    DAG.getConstant(NewImm, NewVT));
8452       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8453                                    NewVal, NewPtr,
8454                                    ST->getPointerInfo().getWithOffset(PtrOff),
8455                                    false, false, NewAlign);
8456
8457       AddToWorkList(NewPtr.getNode());
8458       AddToWorkList(NewLD.getNode());
8459       AddToWorkList(NewVal.getNode());
8460       WorkListRemover DeadNodes(*this);
8461       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8462       ++OpsNarrowed;
8463       return NewST;
8464     }
8465   }
8466
8467   return SDValue();
8468 }
8469
8470 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8471 /// if the load value isn't used by any other operations, then consider
8472 /// transforming the pair to integer load / store operations if the target
8473 /// deems the transformation profitable.
8474 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8475   StoreSDNode *ST  = cast<StoreSDNode>(N);
8476   SDValue Chain = ST->getChain();
8477   SDValue Value = ST->getValue();
8478   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8479       Value.hasOneUse() &&
8480       Chain == SDValue(Value.getNode(), 1)) {
8481     LoadSDNode *LD = cast<LoadSDNode>(Value);
8482     EVT VT = LD->getMemoryVT();
8483     if (!VT.isFloatingPoint() ||
8484         VT != ST->getMemoryVT() ||
8485         LD->isNonTemporal() ||
8486         ST->isNonTemporal() ||
8487         LD->getPointerInfo().getAddrSpace() != 0 ||
8488         ST->getPointerInfo().getAddrSpace() != 0)
8489       return SDValue();
8490
8491     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8492     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8493         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8494         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8495         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8496       return SDValue();
8497
8498     unsigned LDAlign = LD->getAlignment();
8499     unsigned STAlign = ST->getAlignment();
8500     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8501     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8502     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8503       return SDValue();
8504
8505     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8506                                 LD->getChain(), LD->getBasePtr(),
8507                                 LD->getPointerInfo(),
8508                                 false, false, false, LDAlign);
8509
8510     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8511                                  NewLD, ST->getBasePtr(),
8512                                  ST->getPointerInfo(),
8513                                  false, false, STAlign);
8514
8515     AddToWorkList(NewLD.getNode());
8516     AddToWorkList(NewST.getNode());
8517     WorkListRemover DeadNodes(*this);
8518     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8519     ++LdStFP2Int;
8520     return NewST;
8521   }
8522
8523   return SDValue();
8524 }
8525
8526 /// Helper struct to parse and store a memory address as base + index + offset.
8527 /// We ignore sign extensions when it is safe to do so.
8528 /// The following two expressions are not equivalent. To differentiate we need
8529 /// to store whether there was a sign extension involved in the index
8530 /// computation.
8531 ///  (load (i64 add (i64 copyfromreg %c)
8532 ///                 (i64 signextend (add (i8 load %index)
8533 ///                                      (i8 1))))
8534 /// vs
8535 ///
8536 /// (load (i64 add (i64 copyfromreg %c)
8537 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8538 ///                                         (i32 1)))))
8539 struct BaseIndexOffset {
8540   SDValue Base;
8541   SDValue Index;
8542   int64_t Offset;
8543   bool IsIndexSignExt;
8544
8545   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8546
8547   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8548                   bool IsIndexSignExt) :
8549     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8550
8551   bool equalBaseIndex(const BaseIndexOffset &Other) {
8552     return Other.Base == Base && Other.Index == Index &&
8553       Other.IsIndexSignExt == IsIndexSignExt;
8554   }
8555
8556   /// Parses tree in Ptr for base, index, offset addresses.
8557   static BaseIndexOffset match(SDValue Ptr) {
8558     bool IsIndexSignExt = false;
8559
8560     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8561     // instruction, then it could be just the BASE or everything else we don't
8562     // know how to handle. Just use Ptr as BASE and give up.
8563     if (Ptr->getOpcode() != ISD::ADD)
8564       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8565
8566     // We know that we have at least an ADD instruction. Try to pattern match
8567     // the simple case of BASE + OFFSET.
8568     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8569       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8570       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8571                               IsIndexSignExt);
8572     }
8573
8574     // Inside a loop the current BASE pointer is calculated using an ADD and a
8575     // MUL instruction. In this case Ptr is the actual BASE pointer.
8576     // (i64 add (i64 %array_ptr)
8577     //          (i64 mul (i64 %induction_var)
8578     //                   (i64 %element_size)))
8579     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8580       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8581
8582     // Look at Base + Index + Offset cases.
8583     SDValue Base = Ptr->getOperand(0);
8584     SDValue IndexOffset = Ptr->getOperand(1);
8585
8586     // Skip signextends.
8587     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8588       IndexOffset = IndexOffset->getOperand(0);
8589       IsIndexSignExt = true;
8590     }
8591
8592     // Either the case of Base + Index (no offset) or something else.
8593     if (IndexOffset->getOpcode() != ISD::ADD)
8594       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8595
8596     // Now we have the case of Base + Index + offset.
8597     SDValue Index = IndexOffset->getOperand(0);
8598     SDValue Offset = IndexOffset->getOperand(1);
8599
8600     if (!isa<ConstantSDNode>(Offset))
8601       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8602
8603     // Ignore signextends.
8604     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8605       Index = Index->getOperand(0);
8606       IsIndexSignExt = true;
8607     } else IsIndexSignExt = false;
8608
8609     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8610     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8611   }
8612 };
8613
8614 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8615 /// is located in a sequence of memory operations connected by a chain.
8616 struct MemOpLink {
8617   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8618     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8619   // Ptr to the mem node.
8620   LSBaseSDNode *MemNode;
8621   // Offset from the base ptr.
8622   int64_t OffsetFromBase;
8623   // What is the sequence number of this mem node.
8624   // Lowest mem operand in the DAG starts at zero.
8625   unsigned SequenceNum;
8626 };
8627
8628 /// Sorts store nodes in a link according to their offset from a shared
8629 // base ptr.
8630 struct ConsecutiveMemoryChainSorter {
8631   bool operator()(MemOpLink LHS, MemOpLink RHS) {
8632     return LHS.OffsetFromBase < RHS.OffsetFromBase;
8633   }
8634 };
8635
8636 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8637   EVT MemVT = St->getMemoryVT();
8638   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8639   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8640     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8641
8642   // Don't merge vectors into wider inputs.
8643   if (MemVT.isVector() || !MemVT.isSimple())
8644     return false;
8645
8646   // Perform an early exit check. Do not bother looking at stored values that
8647   // are not constants or loads.
8648   SDValue StoredVal = St->getValue();
8649   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8650   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8651       !IsLoadSrc)
8652     return false;
8653
8654   // Only look at ends of store sequences.
8655   SDValue Chain = SDValue(St, 1);
8656   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8657     return false;
8658
8659   // This holds the base pointer, index, and the offset in bytes from the base
8660   // pointer.
8661   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8662
8663   // We must have a base and an offset.
8664   if (!BasePtr.Base.getNode())
8665     return false;
8666
8667   // Do not handle stores to undef base pointers.
8668   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8669     return false;
8670
8671   // Save the LoadSDNodes that we find in the chain.
8672   // We need to make sure that these nodes do not interfere with
8673   // any of the store nodes.
8674   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8675
8676   // Save the StoreSDNodes that we find in the chain.
8677   SmallVector<MemOpLink, 8> StoreNodes;
8678
8679   // Walk up the chain and look for nodes with offsets from the same
8680   // base pointer. Stop when reaching an instruction with a different kind
8681   // or instruction which has a different base pointer.
8682   unsigned Seq = 0;
8683   StoreSDNode *Index = St;
8684   while (Index) {
8685     // If the chain has more than one use, then we can't reorder the mem ops.
8686     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8687       break;
8688
8689     // Find the base pointer and offset for this memory node.
8690     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8691
8692     // Check that the base pointer is the same as the original one.
8693     if (!Ptr.equalBaseIndex(BasePtr))
8694       break;
8695
8696     // Check that the alignment is the same.
8697     if (Index->getAlignment() != St->getAlignment())
8698       break;
8699
8700     // The memory operands must not be volatile.
8701     if (Index->isVolatile() || Index->isIndexed())
8702       break;
8703
8704     // No truncation.
8705     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8706       if (St->isTruncatingStore())
8707         break;
8708
8709     // The stored memory type must be the same.
8710     if (Index->getMemoryVT() != MemVT)
8711       break;
8712
8713     // We do not allow unaligned stores because we want to prevent overriding
8714     // stores.
8715     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8716       break;
8717
8718     // We found a potential memory operand to merge.
8719     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8720
8721     // Find the next memory operand in the chain. If the next operand in the
8722     // chain is a store then move up and continue the scan with the next
8723     // memory operand. If the next operand is a load save it and use alias
8724     // information to check if it interferes with anything.
8725     SDNode *NextInChain = Index->getChain().getNode();
8726     while (1) {
8727       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8728         // We found a store node. Use it for the next iteration.
8729         Index = STn;
8730         break;
8731       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8732         if (Ldn->isVolatile()) {
8733           Index = NULL;
8734           break;
8735         }
8736
8737         // Save the load node for later. Continue the scan.
8738         AliasLoadNodes.push_back(Ldn);
8739         NextInChain = Ldn->getChain().getNode();
8740         continue;
8741       } else {
8742         Index = NULL;
8743         break;
8744       }
8745     }
8746   }
8747
8748   // Check if there is anything to merge.
8749   if (StoreNodes.size() < 2)
8750     return false;
8751
8752   // Sort the memory operands according to their distance from the base pointer.
8753   std::sort(StoreNodes.begin(), StoreNodes.end(),
8754             ConsecutiveMemoryChainSorter());
8755
8756   // Scan the memory operations on the chain and find the first non-consecutive
8757   // store memory address.
8758   unsigned LastConsecutiveStore = 0;
8759   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8760   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8761
8762     // Check that the addresses are consecutive starting from the second
8763     // element in the list of stores.
8764     if (i > 0) {
8765       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8766       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8767         break;
8768     }
8769
8770     bool Alias = false;
8771     // Check if this store interferes with any of the loads that we found.
8772     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8773       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8774         Alias = true;
8775         break;
8776       }
8777     // We found a load that alias with this store. Stop the sequence.
8778     if (Alias)
8779       break;
8780
8781     // Mark this node as useful.
8782     LastConsecutiveStore = i;
8783   }
8784
8785   // The node with the lowest store address.
8786   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8787
8788   // Store the constants into memory as one consecutive store.
8789   if (!IsLoadSrc) {
8790     unsigned LastLegalType = 0;
8791     unsigned LastLegalVectorType = 0;
8792     bool NonZero = false;
8793     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8794       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8795       SDValue StoredVal = St->getValue();
8796
8797       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8798         NonZero |= !C->isNullValue();
8799       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8800         NonZero |= !C->getConstantFPValue()->isNullValue();
8801       } else {
8802         // Non-constant.
8803         break;
8804       }
8805
8806       // Find a legal type for the constant store.
8807       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8808       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8809       if (TLI.isTypeLegal(StoreTy))
8810         LastLegalType = i+1;
8811       // Or check whether a truncstore is legal.
8812       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8813                TargetLowering::TypePromoteInteger) {
8814         EVT LegalizedStoredValueTy =
8815           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8816         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8817           LastLegalType = i+1;
8818       }
8819
8820       // Find a legal type for the vector store.
8821       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8822       if (TLI.isTypeLegal(Ty))
8823         LastLegalVectorType = i + 1;
8824     }
8825
8826     // We only use vectors if the constant is known to be zero and the
8827     // function is not marked with the noimplicitfloat attribute.
8828     if (NonZero || NoVectors)
8829       LastLegalVectorType = 0;
8830
8831     // Check if we found a legal integer type to store.
8832     if (LastLegalType == 0 && LastLegalVectorType == 0)
8833       return false;
8834
8835     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8836     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8837
8838     // Make sure we have something to merge.
8839     if (NumElem < 2)
8840       return false;
8841
8842     unsigned EarliestNodeUsed = 0;
8843     for (unsigned i=0; i < NumElem; ++i) {
8844       // Find a chain for the new wide-store operand. Notice that some
8845       // of the store nodes that we found may not be selected for inclusion
8846       // in the wide store. The chain we use needs to be the chain of the
8847       // earliest store node which is *used* and replaced by the wide store.
8848       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8849         EarliestNodeUsed = i;
8850     }
8851
8852     // The earliest Node in the DAG.
8853     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8854     SDLoc DL(StoreNodes[0].MemNode);
8855
8856     SDValue StoredVal;
8857     if (UseVector) {
8858       // Find a legal type for the vector store.
8859       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8860       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8861       StoredVal = DAG.getConstant(0, Ty);
8862     } else {
8863       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8864       APInt StoreInt(StoreBW, 0);
8865
8866       // Construct a single integer constant which is made of the smaller
8867       // constant inputs.
8868       bool IsLE = TLI.isLittleEndian();
8869       for (unsigned i = 0; i < NumElem ; ++i) {
8870         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8871         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8872         SDValue Val = St->getValue();
8873         StoreInt<<=ElementSizeBytes*8;
8874         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8875           StoreInt|=C->getAPIntValue().zext(StoreBW);
8876         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8877           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8878         } else {
8879           assert(false && "Invalid constant element type");
8880         }
8881       }
8882
8883       // Create the new Load and Store operations.
8884       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8885       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8886     }
8887
8888     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8889                                     FirstInChain->getBasePtr(),
8890                                     FirstInChain->getPointerInfo(),
8891                                     false, false,
8892                                     FirstInChain->getAlignment());
8893
8894     // Replace the first store with the new store
8895     CombineTo(EarliestOp, NewStore);
8896     // Erase all other stores.
8897     for (unsigned i = 0; i < NumElem ; ++i) {
8898       if (StoreNodes[i].MemNode == EarliestOp)
8899         continue;
8900       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8901       // ReplaceAllUsesWith will replace all uses that existed when it was
8902       // called, but graph optimizations may cause new ones to appear. For
8903       // example, the case in pr14333 looks like
8904       //
8905       //  St's chain -> St -> another store -> X
8906       //
8907       // And the only difference from St to the other store is the chain.
8908       // When we change it's chain to be St's chain they become identical,
8909       // get CSEed and the net result is that X is now a use of St.
8910       // Since we know that St is redundant, just iterate.
8911       while (!St->use_empty())
8912         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8913       removeFromWorkList(St);
8914       DAG.DeleteNode(St);
8915     }
8916
8917     return true;
8918   }
8919
8920   // Below we handle the case of multiple consecutive stores that
8921   // come from multiple consecutive loads. We merge them into a single
8922   // wide load and a single wide store.
8923
8924   // Look for load nodes which are used by the stored values.
8925   SmallVector<MemOpLink, 8> LoadNodes;
8926
8927   // Find acceptable loads. Loads need to have the same chain (token factor),
8928   // must not be zext, volatile, indexed, and they must be consecutive.
8929   BaseIndexOffset LdBasePtr;
8930   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8931     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8932     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8933     if (!Ld) break;
8934
8935     // Loads must only have one use.
8936     if (!Ld->hasNUsesOfValue(1, 0))
8937       break;
8938
8939     // Check that the alignment is the same as the stores.
8940     if (Ld->getAlignment() != St->getAlignment())
8941       break;
8942
8943     // The memory operands must not be volatile.
8944     if (Ld->isVolatile() || Ld->isIndexed())
8945       break;
8946
8947     // We do not accept ext loads.
8948     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8949       break;
8950
8951     // The stored memory type must be the same.
8952     if (Ld->getMemoryVT() != MemVT)
8953       break;
8954
8955     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8956     // If this is not the first ptr that we check.
8957     if (LdBasePtr.Base.getNode()) {
8958       // The base ptr must be the same.
8959       if (!LdPtr.equalBaseIndex(LdBasePtr))
8960         break;
8961     } else {
8962       // Check that all other base pointers are the same as this one.
8963       LdBasePtr = LdPtr;
8964     }
8965
8966     // We found a potential memory operand to merge.
8967     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8968   }
8969
8970   if (LoadNodes.size() < 2)
8971     return false;
8972
8973   // Scan the memory operations on the chain and find the first non-consecutive
8974   // load memory address. These variables hold the index in the store node
8975   // array.
8976   unsigned LastConsecutiveLoad = 0;
8977   // This variable refers to the size and not index in the array.
8978   unsigned LastLegalVectorType = 0;
8979   unsigned LastLegalIntegerType = 0;
8980   StartAddress = LoadNodes[0].OffsetFromBase;
8981   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8982   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8983     // All loads much share the same chain.
8984     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8985       break;
8986
8987     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8988     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8989       break;
8990     LastConsecutiveLoad = i;
8991
8992     // Find a legal type for the vector store.
8993     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8994     if (TLI.isTypeLegal(StoreTy))
8995       LastLegalVectorType = i + 1;
8996
8997     // Find a legal type for the integer store.
8998     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8999     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9000     if (TLI.isTypeLegal(StoreTy))
9001       LastLegalIntegerType = i + 1;
9002     // Or check whether a truncstore and extload is legal.
9003     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9004              TargetLowering::TypePromoteInteger) {
9005       EVT LegalizedStoredValueTy =
9006         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9007       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9008           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9009           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9010           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9011         LastLegalIntegerType = i+1;
9012     }
9013   }
9014
9015   // Only use vector types if the vector type is larger than the integer type.
9016   // If they are the same, use integers.
9017   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9018   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9019
9020   // We add +1 here because the LastXXX variables refer to location while
9021   // the NumElem refers to array/index size.
9022   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9023   NumElem = std::min(LastLegalType, NumElem);
9024
9025   if (NumElem < 2)
9026     return false;
9027
9028   // The earliest Node in the DAG.
9029   unsigned EarliestNodeUsed = 0;
9030   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9031   for (unsigned i=1; i<NumElem; ++i) {
9032     // Find a chain for the new wide-store operand. Notice that some
9033     // of the store nodes that we found may not be selected for inclusion
9034     // in the wide store. The chain we use needs to be the chain of the
9035     // earliest store node which is *used* and replaced by the wide store.
9036     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9037       EarliestNodeUsed = i;
9038   }
9039
9040   // Find if it is better to use vectors or integers to load and store
9041   // to memory.
9042   EVT JointMemOpVT;
9043   if (UseVectorTy) {
9044     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9045   } else {
9046     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9047     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9048   }
9049
9050   SDLoc LoadDL(LoadNodes[0].MemNode);
9051   SDLoc StoreDL(StoreNodes[0].MemNode);
9052
9053   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9054   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9055                                 FirstLoad->getChain(),
9056                                 FirstLoad->getBasePtr(),
9057                                 FirstLoad->getPointerInfo(),
9058                                 false, false, false,
9059                                 FirstLoad->getAlignment());
9060
9061   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9062                                   FirstInChain->getBasePtr(),
9063                                   FirstInChain->getPointerInfo(), false, false,
9064                                   FirstInChain->getAlignment());
9065
9066   // Replace one of the loads with the new load.
9067   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9068   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9069                                 SDValue(NewLoad.getNode(), 1));
9070
9071   // Remove the rest of the load chains.
9072   for (unsigned i = 1; i < NumElem ; ++i) {
9073     // Replace all chain users of the old load nodes with the chain of the new
9074     // load node.
9075     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9076     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9077   }
9078
9079   // Replace the first store with the new store.
9080   CombineTo(EarliestOp, NewStore);
9081   // Erase all other stores.
9082   for (unsigned i = 0; i < NumElem ; ++i) {
9083     // Remove all Store nodes.
9084     if (StoreNodes[i].MemNode == EarliestOp)
9085       continue;
9086     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9087     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9088     removeFromWorkList(St);
9089     DAG.DeleteNode(St);
9090   }
9091
9092   return true;
9093 }
9094
9095 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9096   StoreSDNode *ST  = cast<StoreSDNode>(N);
9097   SDValue Chain = ST->getChain();
9098   SDValue Value = ST->getValue();
9099   SDValue Ptr   = ST->getBasePtr();
9100
9101   // If this is a store of a bit convert, store the input value if the
9102   // resultant store does not need a higher alignment than the original.
9103   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9104       ST->isUnindexed()) {
9105     unsigned OrigAlign = ST->getAlignment();
9106     EVT SVT = Value.getOperand(0).getValueType();
9107     unsigned Align = TLI.getDataLayout()->
9108       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9109     if (Align <= OrigAlign &&
9110         ((!LegalOperations && !ST->isVolatile()) ||
9111          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9112       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9113                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9114                           ST->isNonTemporal(), OrigAlign,
9115                           ST->getTBAAInfo());
9116   }
9117
9118   // Turn 'store undef, Ptr' -> nothing.
9119   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9120     return Chain;
9121
9122   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9123   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9124     // NOTE: If the original store is volatile, this transform must not increase
9125     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9126     // processor operation but an i64 (which is not legal) requires two.  So the
9127     // transform should not be done in this case.
9128     if (Value.getOpcode() != ISD::TargetConstantFP) {
9129       SDValue Tmp;
9130       switch (CFP->getSimpleValueType(0).SimpleTy) {
9131       default: llvm_unreachable("Unknown FP type");
9132       case MVT::f16:    // We don't do this for these yet.
9133       case MVT::f80:
9134       case MVT::f128:
9135       case MVT::ppcf128:
9136         break;
9137       case MVT::f32:
9138         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9139             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9140           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9141                               bitcastToAPInt().getZExtValue(), MVT::i32);
9142           return DAG.getStore(Chain, SDLoc(N), Tmp,
9143                               Ptr, ST->getMemOperand());
9144         }
9145         break;
9146       case MVT::f64:
9147         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9148              !ST->isVolatile()) ||
9149             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9150           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9151                                 getZExtValue(), MVT::i64);
9152           return DAG.getStore(Chain, SDLoc(N), Tmp,
9153                               Ptr, ST->getMemOperand());
9154         }
9155
9156         if (!ST->isVolatile() &&
9157             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9158           // Many FP stores are not made apparent until after legalize, e.g. for
9159           // argument passing.  Since this is so common, custom legalize the
9160           // 64-bit integer store into two 32-bit stores.
9161           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9162           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9163           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9164           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9165
9166           unsigned Alignment = ST->getAlignment();
9167           bool isVolatile = ST->isVolatile();
9168           bool isNonTemporal = ST->isNonTemporal();
9169           const MDNode *TBAAInfo = ST->getTBAAInfo();
9170
9171           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9172                                      Ptr, ST->getPointerInfo(),
9173                                      isVolatile, isNonTemporal,
9174                                      ST->getAlignment(), TBAAInfo);
9175           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9176                             DAG.getConstant(4, Ptr.getValueType()));
9177           Alignment = MinAlign(Alignment, 4U);
9178           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9179                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9180                                      isVolatile, isNonTemporal,
9181                                      Alignment, TBAAInfo);
9182           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9183                              St0, St1);
9184         }
9185
9186         break;
9187       }
9188     }
9189   }
9190
9191   // Try to infer better alignment information than the store already has.
9192   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9193     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9194       if (Align > ST->getAlignment())
9195         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9196                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9197                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9198                                  ST->getTBAAInfo());
9199     }
9200   }
9201
9202   // Try transforming a pair floating point load / store ops to integer
9203   // load / store ops.
9204   SDValue NewST = TransformFPLoadStorePair(N);
9205   if (NewST.getNode())
9206     return NewST;
9207
9208   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9209     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9210   if (UseAA) {
9211     // Walk up chain skipping non-aliasing memory nodes.
9212     SDValue BetterChain = FindBetterChain(N, Chain);
9213
9214     // If there is a better chain.
9215     if (Chain != BetterChain) {
9216       SDValue ReplStore;
9217
9218       // Replace the chain to avoid dependency.
9219       if (ST->isTruncatingStore()) {
9220         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9221                                       ST->getMemoryVT(), ST->getMemOperand());
9222       } else {
9223         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9224                                  ST->getMemOperand());
9225       }
9226
9227       // Create token to keep both nodes around.
9228       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9229                                   MVT::Other, Chain, ReplStore);
9230
9231       // Make sure the new and old chains are cleaned up.
9232       AddToWorkList(Token.getNode());
9233
9234       // Don't add users to work list.
9235       return CombineTo(N, Token, false);
9236     }
9237   }
9238
9239   // Try transforming N to an indexed store.
9240   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9241     return SDValue(N, 0);
9242
9243   // FIXME: is there such a thing as a truncating indexed store?
9244   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9245       Value.getValueType().isInteger()) {
9246     // See if we can simplify the input to this truncstore with knowledge that
9247     // only the low bits are being used.  For example:
9248     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9249     SDValue Shorter =
9250       GetDemandedBits(Value,
9251                       APInt::getLowBitsSet(
9252                         Value.getValueType().getScalarType().getSizeInBits(),
9253                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9254     AddToWorkList(Value.getNode());
9255     if (Shorter.getNode())
9256       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9257                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9258
9259     // Otherwise, see if we can simplify the operation with
9260     // SimplifyDemandedBits, which only works if the value has a single use.
9261     if (SimplifyDemandedBits(Value,
9262                         APInt::getLowBitsSet(
9263                           Value.getValueType().getScalarType().getSizeInBits(),
9264                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9265       return SDValue(N, 0);
9266   }
9267
9268   // If this is a load followed by a store to the same location, then the store
9269   // is dead/noop.
9270   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9271     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9272         ST->isUnindexed() && !ST->isVolatile() &&
9273         // There can't be any side effects between the load and store, such as
9274         // a call or store.
9275         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9276       // The store is dead, remove it.
9277       return Chain;
9278     }
9279   }
9280
9281   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9282   // truncating store.  We can do this even if this is already a truncstore.
9283   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9284       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9285       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9286                             ST->getMemoryVT())) {
9287     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9288                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9289   }
9290
9291   // Only perform this optimization before the types are legal, because we
9292   // don't want to perform this optimization on every DAGCombine invocation.
9293   if (!LegalTypes) {
9294     bool EverChanged = false;
9295
9296     do {
9297       // There can be multiple store sequences on the same chain.
9298       // Keep trying to merge store sequences until we are unable to do so
9299       // or until we merge the last store on the chain.
9300       bool Changed = MergeConsecutiveStores(ST);
9301       EverChanged |= Changed;
9302       if (!Changed) break;
9303     } while (ST->getOpcode() != ISD::DELETED_NODE);
9304
9305     if (EverChanged)
9306       return SDValue(N, 0);
9307   }
9308
9309   return ReduceLoadOpStoreWidth(N);
9310 }
9311
9312 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9313   SDValue InVec = N->getOperand(0);
9314   SDValue InVal = N->getOperand(1);
9315   SDValue EltNo = N->getOperand(2);
9316   SDLoc dl(N);
9317
9318   // If the inserted element is an UNDEF, just use the input vector.
9319   if (InVal.getOpcode() == ISD::UNDEF)
9320     return InVec;
9321
9322   EVT VT = InVec.getValueType();
9323
9324   // If we can't generate a legal BUILD_VECTOR, exit
9325   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9326     return SDValue();
9327
9328   // Check that we know which element is being inserted
9329   if (!isa<ConstantSDNode>(EltNo))
9330     return SDValue();
9331   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9332
9333   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9334   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9335   // vector elements.
9336   SmallVector<SDValue, 8> Ops;
9337   // Do not combine these two vectors if the output vector will not replace
9338   // the input vector.
9339   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9340     Ops.append(InVec.getNode()->op_begin(),
9341                InVec.getNode()->op_end());
9342   } else if (InVec.getOpcode() == ISD::UNDEF) {
9343     unsigned NElts = VT.getVectorNumElements();
9344     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9345   } else {
9346     return SDValue();
9347   }
9348
9349   // Insert the element
9350   if (Elt < Ops.size()) {
9351     // All the operands of BUILD_VECTOR must have the same type;
9352     // we enforce that here.
9353     EVT OpVT = Ops[0].getValueType();
9354     if (InVal.getValueType() != OpVT)
9355       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9356                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9357                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9358     Ops[Elt] = InVal;
9359   }
9360
9361   // Return the new vector
9362   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9363                      VT, &Ops[0], Ops.size());
9364 }
9365
9366 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9367   // (vextract (scalar_to_vector val, 0) -> val
9368   SDValue InVec = N->getOperand(0);
9369   EVT VT = InVec.getValueType();
9370   EVT NVT = N->getValueType(0);
9371
9372   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9373     // Check if the result type doesn't match the inserted element type. A
9374     // SCALAR_TO_VECTOR may truncate the inserted element and the
9375     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9376     SDValue InOp = InVec.getOperand(0);
9377     if (InOp.getValueType() != NVT) {
9378       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9379       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9380     }
9381     return InOp;
9382   }
9383
9384   SDValue EltNo = N->getOperand(1);
9385   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9386
9387   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9388   // We only perform this optimization before the op legalization phase because
9389   // we may introduce new vector instructions which are not backed by TD
9390   // patterns. For example on AVX, extracting elements from a wide vector
9391   // without using extract_subvector.
9392   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9393       && ConstEltNo && !LegalOperations) {
9394     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9395     int NumElem = VT.getVectorNumElements();
9396     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9397     // Find the new index to extract from.
9398     int OrigElt = SVOp->getMaskElt(Elt);
9399
9400     // Extracting an undef index is undef.
9401     if (OrigElt == -1)
9402       return DAG.getUNDEF(NVT);
9403
9404     // Select the right vector half to extract from.
9405     if (OrigElt < NumElem) {
9406       InVec = InVec->getOperand(0);
9407     } else {
9408       InVec = InVec->getOperand(1);
9409       OrigElt -= NumElem;
9410     }
9411
9412     EVT IndexTy = TLI.getVectorIdxTy();
9413     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9414                        InVec, DAG.getConstant(OrigElt, IndexTy));
9415   }
9416
9417   // Perform only after legalization to ensure build_vector / vector_shuffle
9418   // optimizations have already been done.
9419   if (!LegalOperations) return SDValue();
9420
9421   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9422   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9423   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9424
9425   if (ConstEltNo) {
9426     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9427     bool NewLoad = false;
9428     bool BCNumEltsChanged = false;
9429     EVT ExtVT = VT.getVectorElementType();
9430     EVT LVT = ExtVT;
9431
9432     // If the result of load has to be truncated, then it's not necessarily
9433     // profitable.
9434     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9435       return SDValue();
9436
9437     if (InVec.getOpcode() == ISD::BITCAST) {
9438       // Don't duplicate a load with other uses.
9439       if (!InVec.hasOneUse())
9440         return SDValue();
9441
9442       EVT BCVT = InVec.getOperand(0).getValueType();
9443       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9444         return SDValue();
9445       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9446         BCNumEltsChanged = true;
9447       InVec = InVec.getOperand(0);
9448       ExtVT = BCVT.getVectorElementType();
9449       NewLoad = true;
9450     }
9451
9452     LoadSDNode *LN0 = NULL;
9453     const ShuffleVectorSDNode *SVN = NULL;
9454     if (ISD::isNormalLoad(InVec.getNode())) {
9455       LN0 = cast<LoadSDNode>(InVec);
9456     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9457                InVec.getOperand(0).getValueType() == ExtVT &&
9458                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9459       // Don't duplicate a load with other uses.
9460       if (!InVec.hasOneUse())
9461         return SDValue();
9462
9463       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9464     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9465       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9466       // =>
9467       // (load $addr+1*size)
9468
9469       // Don't duplicate a load with other uses.
9470       if (!InVec.hasOneUse())
9471         return SDValue();
9472
9473       // If the bit convert changed the number of elements, it is unsafe
9474       // to examine the mask.
9475       if (BCNumEltsChanged)
9476         return SDValue();
9477
9478       // Select the input vector, guarding against out of range extract vector.
9479       unsigned NumElems = VT.getVectorNumElements();
9480       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9481       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9482
9483       if (InVec.getOpcode() == ISD::BITCAST) {
9484         // Don't duplicate a load with other uses.
9485         if (!InVec.hasOneUse())
9486           return SDValue();
9487
9488         InVec = InVec.getOperand(0);
9489       }
9490       if (ISD::isNormalLoad(InVec.getNode())) {
9491         LN0 = cast<LoadSDNode>(InVec);
9492         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9493       }
9494     }
9495
9496     // Make sure we found a non-volatile load and the extractelement is
9497     // the only use.
9498     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9499       return SDValue();
9500
9501     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9502     if (Elt == -1)
9503       return DAG.getUNDEF(LVT);
9504
9505     unsigned Align = LN0->getAlignment();
9506     if (NewLoad) {
9507       // Check the resultant load doesn't need a higher alignment than the
9508       // original load.
9509       unsigned NewAlign =
9510         TLI.getDataLayout()
9511             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9512
9513       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9514         return SDValue();
9515
9516       Align = NewAlign;
9517     }
9518
9519     SDValue NewPtr = LN0->getBasePtr();
9520     unsigned PtrOff = 0;
9521
9522     if (Elt) {
9523       PtrOff = LVT.getSizeInBits() * Elt / 8;
9524       EVT PtrType = NewPtr.getValueType();
9525       if (TLI.isBigEndian())
9526         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9527       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9528                            DAG.getConstant(PtrOff, PtrType));
9529     }
9530
9531     // The replacement we need to do here is a little tricky: we need to
9532     // replace an extractelement of a load with a load.
9533     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9534     // Note that this replacement assumes that the extractvalue is the only
9535     // use of the load; that's okay because we don't want to perform this
9536     // transformation in other cases anyway.
9537     SDValue Load;
9538     SDValue Chain;
9539     if (NVT.bitsGT(LVT)) {
9540       // If the result type of vextract is wider than the load, then issue an
9541       // extending load instead.
9542       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9543         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9544       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9545                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9546                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9547                             Align, LN0->getTBAAInfo());
9548       Chain = Load.getValue(1);
9549     } else {
9550       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9551                          LN0->getPointerInfo().getWithOffset(PtrOff),
9552                          LN0->isVolatile(), LN0->isNonTemporal(),
9553                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9554       Chain = Load.getValue(1);
9555       if (NVT.bitsLT(LVT))
9556         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9557       else
9558         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9559     }
9560     WorkListRemover DeadNodes(*this);
9561     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9562     SDValue To[] = { Load, Chain };
9563     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9564     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9565     // worklist explicitly as well.
9566     AddToWorkList(Load.getNode());
9567     AddUsersToWorkList(Load.getNode()); // Add users too
9568     // Make sure to revisit this node to clean it up; it will usually be dead.
9569     AddToWorkList(N);
9570     return SDValue(N, 0);
9571   }
9572
9573   return SDValue();
9574 }
9575
9576 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9577 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9578   // We perform this optimization post type-legalization because
9579   // the type-legalizer often scalarizes integer-promoted vectors.
9580   // Performing this optimization before may create bit-casts which
9581   // will be type-legalized to complex code sequences.
9582   // We perform this optimization only before the operation legalizer because we
9583   // may introduce illegal operations.
9584   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9585     return SDValue();
9586
9587   unsigned NumInScalars = N->getNumOperands();
9588   SDLoc dl(N);
9589   EVT VT = N->getValueType(0);
9590
9591   // Check to see if this is a BUILD_VECTOR of a bunch of values
9592   // which come from any_extend or zero_extend nodes. If so, we can create
9593   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9594   // optimizations. We do not handle sign-extend because we can't fill the sign
9595   // using shuffles.
9596   EVT SourceType = MVT::Other;
9597   bool AllAnyExt = true;
9598
9599   for (unsigned i = 0; i != NumInScalars; ++i) {
9600     SDValue In = N->getOperand(i);
9601     // Ignore undef inputs.
9602     if (In.getOpcode() == ISD::UNDEF) continue;
9603
9604     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9605     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9606
9607     // Abort if the element is not an extension.
9608     if (!ZeroExt && !AnyExt) {
9609       SourceType = MVT::Other;
9610       break;
9611     }
9612
9613     // The input is a ZeroExt or AnyExt. Check the original type.
9614     EVT InTy = In.getOperand(0).getValueType();
9615
9616     // Check that all of the widened source types are the same.
9617     if (SourceType == MVT::Other)
9618       // First time.
9619       SourceType = InTy;
9620     else if (InTy != SourceType) {
9621       // Multiple income types. Abort.
9622       SourceType = MVT::Other;
9623       break;
9624     }
9625
9626     // Check if all of the extends are ANY_EXTENDs.
9627     AllAnyExt &= AnyExt;
9628   }
9629
9630   // In order to have valid types, all of the inputs must be extended from the
9631   // same source type and all of the inputs must be any or zero extend.
9632   // Scalar sizes must be a power of two.
9633   EVT OutScalarTy = VT.getScalarType();
9634   bool ValidTypes = SourceType != MVT::Other &&
9635                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9636                  isPowerOf2_32(SourceType.getSizeInBits());
9637
9638   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9639   // turn into a single shuffle instruction.
9640   if (!ValidTypes)
9641     return SDValue();
9642
9643   bool isLE = TLI.isLittleEndian();
9644   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9645   assert(ElemRatio > 1 && "Invalid element size ratio");
9646   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9647                                DAG.getConstant(0, SourceType);
9648
9649   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9650   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9651
9652   // Populate the new build_vector
9653   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9654     SDValue Cast = N->getOperand(i);
9655     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9656             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9657             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9658     SDValue In;
9659     if (Cast.getOpcode() == ISD::UNDEF)
9660       In = DAG.getUNDEF(SourceType);
9661     else
9662       In = Cast->getOperand(0);
9663     unsigned Index = isLE ? (i * ElemRatio) :
9664                             (i * ElemRatio + (ElemRatio - 1));
9665
9666     assert(Index < Ops.size() && "Invalid index");
9667     Ops[Index] = In;
9668   }
9669
9670   // The type of the new BUILD_VECTOR node.
9671   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9672   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9673          "Invalid vector size");
9674   // Check if the new vector type is legal.
9675   if (!isTypeLegal(VecVT)) return SDValue();
9676
9677   // Make the new BUILD_VECTOR.
9678   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9679
9680   // The new BUILD_VECTOR node has the potential to be further optimized.
9681   AddToWorkList(BV.getNode());
9682   // Bitcast to the desired type.
9683   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9684 }
9685
9686 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9687   EVT VT = N->getValueType(0);
9688
9689   unsigned NumInScalars = N->getNumOperands();
9690   SDLoc dl(N);
9691
9692   EVT SrcVT = MVT::Other;
9693   unsigned Opcode = ISD::DELETED_NODE;
9694   unsigned NumDefs = 0;
9695
9696   for (unsigned i = 0; i != NumInScalars; ++i) {
9697     SDValue In = N->getOperand(i);
9698     unsigned Opc = In.getOpcode();
9699
9700     if (Opc == ISD::UNDEF)
9701       continue;
9702
9703     // If all scalar values are floats and converted from integers.
9704     if (Opcode == ISD::DELETED_NODE &&
9705         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9706       Opcode = Opc;
9707     }
9708
9709     if (Opc != Opcode)
9710       return SDValue();
9711
9712     EVT InVT = In.getOperand(0).getValueType();
9713
9714     // If all scalar values are typed differently, bail out. It's chosen to
9715     // simplify BUILD_VECTOR of integer types.
9716     if (SrcVT == MVT::Other)
9717       SrcVT = InVT;
9718     if (SrcVT != InVT)
9719       return SDValue();
9720     NumDefs++;
9721   }
9722
9723   // If the vector has just one element defined, it's not worth to fold it into
9724   // a vectorized one.
9725   if (NumDefs < 2)
9726     return SDValue();
9727
9728   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9729          && "Should only handle conversion from integer to float.");
9730   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9731
9732   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9733
9734   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9735     return SDValue();
9736
9737   SmallVector<SDValue, 8> Opnds;
9738   for (unsigned i = 0; i != NumInScalars; ++i) {
9739     SDValue In = N->getOperand(i);
9740
9741     if (In.getOpcode() == ISD::UNDEF)
9742       Opnds.push_back(DAG.getUNDEF(SrcVT));
9743     else
9744       Opnds.push_back(In.getOperand(0));
9745   }
9746   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9747                            &Opnds[0], Opnds.size());
9748   AddToWorkList(BV.getNode());
9749
9750   return DAG.getNode(Opcode, dl, VT, BV);
9751 }
9752
9753 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9754   unsigned NumInScalars = N->getNumOperands();
9755   SDLoc dl(N);
9756   EVT VT = N->getValueType(0);
9757
9758   // A vector built entirely of undefs is undef.
9759   if (ISD::allOperandsUndef(N))
9760     return DAG.getUNDEF(VT);
9761
9762   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9763   if (V.getNode())
9764     return V;
9765
9766   V = reduceBuildVecConvertToConvertBuildVec(N);
9767   if (V.getNode())
9768     return V;
9769
9770   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9771   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9772   // at most two distinct vectors, turn this into a shuffle node.
9773
9774   // May only combine to shuffle after legalize if shuffle is legal.
9775   if (LegalOperations &&
9776       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9777     return SDValue();
9778
9779   SDValue VecIn1, VecIn2;
9780   for (unsigned i = 0; i != NumInScalars; ++i) {
9781     // Ignore undef inputs.
9782     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9783
9784     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9785     // constant index, bail out.
9786     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9787         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9788       VecIn1 = VecIn2 = SDValue(0, 0);
9789       break;
9790     }
9791
9792     // We allow up to two distinct input vectors.
9793     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9794     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9795       continue;
9796
9797     if (VecIn1.getNode() == 0) {
9798       VecIn1 = ExtractedFromVec;
9799     } else if (VecIn2.getNode() == 0) {
9800       VecIn2 = ExtractedFromVec;
9801     } else {
9802       // Too many inputs.
9803       VecIn1 = VecIn2 = SDValue(0, 0);
9804       break;
9805     }
9806   }
9807
9808     // If everything is good, we can make a shuffle operation.
9809   if (VecIn1.getNode()) {
9810     SmallVector<int, 8> Mask;
9811     for (unsigned i = 0; i != NumInScalars; ++i) {
9812       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9813         Mask.push_back(-1);
9814         continue;
9815       }
9816
9817       // If extracting from the first vector, just use the index directly.
9818       SDValue Extract = N->getOperand(i);
9819       SDValue ExtVal = Extract.getOperand(1);
9820       if (Extract.getOperand(0) == VecIn1) {
9821         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9822         if (ExtIndex > VT.getVectorNumElements())
9823           return SDValue();
9824
9825         Mask.push_back(ExtIndex);
9826         continue;
9827       }
9828
9829       // Otherwise, use InIdx + VecSize
9830       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9831       Mask.push_back(Idx+NumInScalars);
9832     }
9833
9834     // We can't generate a shuffle node with mismatched input and output types.
9835     // Attempt to transform a single input vector to the correct type.
9836     if ((VT != VecIn1.getValueType())) {
9837       // We don't support shuffeling between TWO values of different types.
9838       if (VecIn2.getNode() != 0)
9839         return SDValue();
9840
9841       // We only support widening of vectors which are half the size of the
9842       // output registers. For example XMM->YMM widening on X86 with AVX.
9843       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9844         return SDValue();
9845
9846       // If the input vector type has a different base type to the output
9847       // vector type, bail out.
9848       if (VecIn1.getValueType().getVectorElementType() !=
9849           VT.getVectorElementType())
9850         return SDValue();
9851
9852       // Widen the input vector by adding undef values.
9853       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9854                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9855     }
9856
9857     // If VecIn2 is unused then change it to undef.
9858     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9859
9860     // Check that we were able to transform all incoming values to the same
9861     // type.
9862     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9863         VecIn1.getValueType() != VT)
9864           return SDValue();
9865
9866     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9867     if (!isTypeLegal(VT))
9868       return SDValue();
9869
9870     // Return the new VECTOR_SHUFFLE node.
9871     SDValue Ops[2];
9872     Ops[0] = VecIn1;
9873     Ops[1] = VecIn2;
9874     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9875   }
9876
9877   return SDValue();
9878 }
9879
9880 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9881   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9882   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9883   // inputs come from at most two distinct vectors, turn this into a shuffle
9884   // node.
9885
9886   // If we only have one input vector, we don't need to do any concatenation.
9887   if (N->getNumOperands() == 1)
9888     return N->getOperand(0);
9889
9890   // Check if all of the operands are undefs.
9891   EVT VT = N->getValueType(0);
9892   if (ISD::allOperandsUndef(N))
9893     return DAG.getUNDEF(VT);
9894
9895   // Optimize concat_vectors where one of the vectors is undef.
9896   if (N->getNumOperands() == 2 &&
9897       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
9898     SDValue In = N->getOperand(0);
9899     assert(In.getValueType().isVector() && "Must concat vectors");
9900
9901     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
9902     if (In->getOpcode() == ISD::BITCAST &&
9903         !In->getOperand(0)->getValueType(0).isVector()) {
9904       SDValue Scalar = In->getOperand(0);
9905       EVT SclTy = Scalar->getValueType(0);
9906
9907       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
9908         return SDValue();
9909
9910       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
9911                                  VT.getSizeInBits() / SclTy.getSizeInBits());
9912       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
9913         return SDValue();
9914
9915       SDLoc dl = SDLoc(N);
9916       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
9917       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
9918     }
9919   }
9920
9921   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9922   // nodes often generate nop CONCAT_VECTOR nodes.
9923   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9924   // place the incoming vectors at the exact same location.
9925   SDValue SingleSource = SDValue();
9926   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9927
9928   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9929     SDValue Op = N->getOperand(i);
9930
9931     if (Op.getOpcode() == ISD::UNDEF)
9932       continue;
9933
9934     // Check if this is the identity extract:
9935     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9936       return SDValue();
9937
9938     // Find the single incoming vector for the extract_subvector.
9939     if (SingleSource.getNode()) {
9940       if (Op.getOperand(0) != SingleSource)
9941         return SDValue();
9942     } else {
9943       SingleSource = Op.getOperand(0);
9944
9945       // Check the source type is the same as the type of the result.
9946       // If not, this concat may extend the vector, so we can not
9947       // optimize it away.
9948       if (SingleSource.getValueType() != N->getValueType(0))
9949         return SDValue();
9950     }
9951
9952     unsigned IdentityIndex = i * PartNumElem;
9953     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9954     // The extract index must be constant.
9955     if (!CS)
9956       return SDValue();
9957
9958     // Check that we are reading from the identity index.
9959     if (CS->getZExtValue() != IdentityIndex)
9960       return SDValue();
9961   }
9962
9963   if (SingleSource.getNode())
9964     return SingleSource;
9965
9966   return SDValue();
9967 }
9968
9969 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9970   EVT NVT = N->getValueType(0);
9971   SDValue V = N->getOperand(0);
9972
9973   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9974     // Combine:
9975     //    (extract_subvec (concat V1, V2, ...), i)
9976     // Into:
9977     //    Vi if possible
9978     // Only operand 0 is checked as 'concat' assumes all inputs of the same
9979     // type.
9980     if (V->getOperand(0).getValueType() != NVT)
9981       return SDValue();
9982     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9983     unsigned NumElems = NVT.getVectorNumElements();
9984     assert((Idx % NumElems) == 0 &&
9985            "IDX in concat is not a multiple of the result vector length.");
9986     return V->getOperand(Idx / NumElems);
9987   }
9988
9989   // Skip bitcasting
9990   if (V->getOpcode() == ISD::BITCAST)
9991     V = V.getOperand(0);
9992
9993   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9994     SDLoc dl(N);
9995     // Handle only simple case where vector being inserted and vector
9996     // being extracted are of same type, and are half size of larger vectors.
9997     EVT BigVT = V->getOperand(0).getValueType();
9998     EVT SmallVT = V->getOperand(1).getValueType();
9999     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10000       return SDValue();
10001
10002     // Only handle cases where both indexes are constants with the same type.
10003     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10004     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10005
10006     if (InsIdx && ExtIdx &&
10007         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10008         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10009       // Combine:
10010       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10011       // Into:
10012       //    indices are equal or bit offsets are equal => V1
10013       //    otherwise => (extract_subvec V1, ExtIdx)
10014       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10015           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10016         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10017       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10018                          DAG.getNode(ISD::BITCAST, dl,
10019                                      N->getOperand(0).getValueType(),
10020                                      V->getOperand(0)), N->getOperand(1));
10021     }
10022   }
10023
10024   return SDValue();
10025 }
10026
10027 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10028 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10029   EVT VT = N->getValueType(0);
10030   unsigned NumElts = VT.getVectorNumElements();
10031
10032   SDValue N0 = N->getOperand(0);
10033   SDValue N1 = N->getOperand(1);
10034   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10035
10036   SmallVector<SDValue, 4> Ops;
10037   EVT ConcatVT = N0.getOperand(0).getValueType();
10038   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10039   unsigned NumConcats = NumElts / NumElemsPerConcat;
10040
10041   // Look at every vector that's inserted. We're looking for exact
10042   // subvector-sized copies from a concatenated vector
10043   for (unsigned I = 0; I != NumConcats; ++I) {
10044     // Make sure we're dealing with a copy.
10045     unsigned Begin = I * NumElemsPerConcat;
10046     bool AllUndef = true, NoUndef = true;
10047     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10048       if (SVN->getMaskElt(J) >= 0)
10049         AllUndef = false;
10050       else
10051         NoUndef = false;
10052     }
10053
10054     if (NoUndef) {
10055       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10056         return SDValue();
10057
10058       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10059         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10060           return SDValue();
10061
10062       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10063       if (FirstElt < N0.getNumOperands())
10064         Ops.push_back(N0.getOperand(FirstElt));
10065       else
10066         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10067
10068     } else if (AllUndef) {
10069       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10070     } else { // Mixed with general masks and undefs, can't do optimization.
10071       return SDValue();
10072     }
10073   }
10074
10075   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10076                      Ops.size());
10077 }
10078
10079 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10080   EVT VT = N->getValueType(0);
10081   unsigned NumElts = VT.getVectorNumElements();
10082
10083   SDValue N0 = N->getOperand(0);
10084   SDValue N1 = N->getOperand(1);
10085
10086   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10087
10088   // Canonicalize shuffle undef, undef -> undef
10089   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10090     return DAG.getUNDEF(VT);
10091
10092   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10093
10094   // Canonicalize shuffle v, v -> v, undef
10095   if (N0 == N1) {
10096     SmallVector<int, 8> NewMask;
10097     for (unsigned i = 0; i != NumElts; ++i) {
10098       int Idx = SVN->getMaskElt(i);
10099       if (Idx >= (int)NumElts) Idx -= NumElts;
10100       NewMask.push_back(Idx);
10101     }
10102     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10103                                 &NewMask[0]);
10104   }
10105
10106   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10107   if (N0.getOpcode() == ISD::UNDEF) {
10108     SmallVector<int, 8> NewMask;
10109     for (unsigned i = 0; i != NumElts; ++i) {
10110       int Idx = SVN->getMaskElt(i);
10111       if (Idx >= 0) {
10112         if (Idx >= (int)NumElts)
10113           Idx -= NumElts;
10114         else
10115           Idx = -1; // remove reference to lhs
10116       }
10117       NewMask.push_back(Idx);
10118     }
10119     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10120                                 &NewMask[0]);
10121   }
10122
10123   // Remove references to rhs if it is undef
10124   if (N1.getOpcode() == ISD::UNDEF) {
10125     bool Changed = false;
10126     SmallVector<int, 8> NewMask;
10127     for (unsigned i = 0; i != NumElts; ++i) {
10128       int Idx = SVN->getMaskElt(i);
10129       if (Idx >= (int)NumElts) {
10130         Idx = -1;
10131         Changed = true;
10132       }
10133       NewMask.push_back(Idx);
10134     }
10135     if (Changed)
10136       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10137   }
10138
10139   // If it is a splat, check if the argument vector is another splat or a
10140   // build_vector with all scalar elements the same.
10141   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10142     SDNode *V = N0.getNode();
10143
10144     // If this is a bit convert that changes the element type of the vector but
10145     // not the number of vector elements, look through it.  Be careful not to
10146     // look though conversions that change things like v4f32 to v2f64.
10147     if (V->getOpcode() == ISD::BITCAST) {
10148       SDValue ConvInput = V->getOperand(0);
10149       if (ConvInput.getValueType().isVector() &&
10150           ConvInput.getValueType().getVectorNumElements() == NumElts)
10151         V = ConvInput.getNode();
10152     }
10153
10154     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10155       assert(V->getNumOperands() == NumElts &&
10156              "BUILD_VECTOR has wrong number of operands");
10157       SDValue Base;
10158       bool AllSame = true;
10159       for (unsigned i = 0; i != NumElts; ++i) {
10160         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10161           Base = V->getOperand(i);
10162           break;
10163         }
10164       }
10165       // Splat of <u, u, u, u>, return <u, u, u, u>
10166       if (!Base.getNode())
10167         return N0;
10168       for (unsigned i = 0; i != NumElts; ++i) {
10169         if (V->getOperand(i) != Base) {
10170           AllSame = false;
10171           break;
10172         }
10173       }
10174       // Splat of <x, x, x, x>, return <x, x, x, x>
10175       if (AllSame)
10176         return N0;
10177     }
10178   }
10179
10180   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10181       Level < AfterLegalizeVectorOps &&
10182       (N1.getOpcode() == ISD::UNDEF ||
10183       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10184        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10185     SDValue V = partitionShuffleOfConcats(N, DAG);
10186
10187     if (V.getNode())
10188       return V;
10189   }
10190
10191   // If this shuffle node is simply a swizzle of another shuffle node,
10192   // and it reverses the swizzle of the previous shuffle then we can
10193   // optimize shuffle(shuffle(x, undef), undef) -> x.
10194   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10195       N1.getOpcode() == ISD::UNDEF) {
10196
10197     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10198
10199     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10200     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10201       return SDValue();
10202
10203     // The incoming shuffle must be of the same type as the result of the
10204     // current shuffle.
10205     assert(OtherSV->getOperand(0).getValueType() == VT &&
10206            "Shuffle types don't match");
10207
10208     for (unsigned i = 0; i != NumElts; ++i) {
10209       int Idx = SVN->getMaskElt(i);
10210       assert(Idx < (int)NumElts && "Index references undef operand");
10211       // Next, this index comes from the first value, which is the incoming
10212       // shuffle. Adopt the incoming index.
10213       if (Idx >= 0)
10214         Idx = OtherSV->getMaskElt(Idx);
10215
10216       // The combined shuffle must map each index to itself.
10217       if (Idx >= 0 && (unsigned)Idx != i)
10218         return SDValue();
10219     }
10220
10221     return OtherSV->getOperand(0);
10222   }
10223
10224   return SDValue();
10225 }
10226
10227 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10228 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10229 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10230 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10231 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10232   EVT VT = N->getValueType(0);
10233   SDLoc dl(N);
10234   SDValue LHS = N->getOperand(0);
10235   SDValue RHS = N->getOperand(1);
10236   if (N->getOpcode() == ISD::AND) {
10237     if (RHS.getOpcode() == ISD::BITCAST)
10238       RHS = RHS.getOperand(0);
10239     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10240       SmallVector<int, 8> Indices;
10241       unsigned NumElts = RHS.getNumOperands();
10242       for (unsigned i = 0; i != NumElts; ++i) {
10243         SDValue Elt = RHS.getOperand(i);
10244         if (!isa<ConstantSDNode>(Elt))
10245           return SDValue();
10246
10247         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10248           Indices.push_back(i);
10249         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10250           Indices.push_back(NumElts);
10251         else
10252           return SDValue();
10253       }
10254
10255       // Let's see if the target supports this vector_shuffle.
10256       EVT RVT = RHS.getValueType();
10257       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10258         return SDValue();
10259
10260       // Return the new VECTOR_SHUFFLE node.
10261       EVT EltVT = RVT.getVectorElementType();
10262       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10263                                      DAG.getConstant(0, EltVT));
10264       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10265                                  RVT, &ZeroOps[0], ZeroOps.size());
10266       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10267       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10268       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10269     }
10270   }
10271
10272   return SDValue();
10273 }
10274
10275 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10276 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10277   assert(N->getValueType(0).isVector() &&
10278          "SimplifyVBinOp only works on vectors!");
10279
10280   SDValue LHS = N->getOperand(0);
10281   SDValue RHS = N->getOperand(1);
10282   SDValue Shuffle = XformToShuffleWithZero(N);
10283   if (Shuffle.getNode()) return Shuffle;
10284
10285   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10286   // this operation.
10287   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10288       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10289     SmallVector<SDValue, 8> Ops;
10290     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10291       SDValue LHSOp = LHS.getOperand(i);
10292       SDValue RHSOp = RHS.getOperand(i);
10293       // If these two elements can't be folded, bail out.
10294       if ((LHSOp.getOpcode() != ISD::UNDEF &&
10295            LHSOp.getOpcode() != ISD::Constant &&
10296            LHSOp.getOpcode() != ISD::ConstantFP) ||
10297           (RHSOp.getOpcode() != ISD::UNDEF &&
10298            RHSOp.getOpcode() != ISD::Constant &&
10299            RHSOp.getOpcode() != ISD::ConstantFP))
10300         break;
10301
10302       // Can't fold divide by zero.
10303       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10304           N->getOpcode() == ISD::FDIV) {
10305         if ((RHSOp.getOpcode() == ISD::Constant &&
10306              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10307             (RHSOp.getOpcode() == ISD::ConstantFP &&
10308              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10309           break;
10310       }
10311
10312       EVT VT = LHSOp.getValueType();
10313       EVT RVT = RHSOp.getValueType();
10314       if (RVT != VT) {
10315         // Integer BUILD_VECTOR operands may have types larger than the element
10316         // size (e.g., when the element type is not legal).  Prior to type
10317         // legalization, the types may not match between the two BUILD_VECTORS.
10318         // Truncate one of the operands to make them match.
10319         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10320           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10321         } else {
10322           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10323           VT = RVT;
10324         }
10325       }
10326       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10327                                    LHSOp, RHSOp);
10328       if (FoldOp.getOpcode() != ISD::UNDEF &&
10329           FoldOp.getOpcode() != ISD::Constant &&
10330           FoldOp.getOpcode() != ISD::ConstantFP)
10331         break;
10332       Ops.push_back(FoldOp);
10333       AddToWorkList(FoldOp.getNode());
10334     }
10335
10336     if (Ops.size() == LHS.getNumOperands())
10337       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10338                          LHS.getValueType(), &Ops[0], Ops.size());
10339   }
10340
10341   return SDValue();
10342 }
10343
10344 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10345 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10346   assert(N->getValueType(0).isVector() &&
10347          "SimplifyVUnaryOp only works on vectors!");
10348
10349   SDValue N0 = N->getOperand(0);
10350
10351   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10352     return SDValue();
10353
10354   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10355   SmallVector<SDValue, 8> Ops;
10356   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10357     SDValue Op = N0.getOperand(i);
10358     if (Op.getOpcode() != ISD::UNDEF &&
10359         Op.getOpcode() != ISD::ConstantFP)
10360       break;
10361     EVT EltVT = Op.getValueType();
10362     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10363     if (FoldOp.getOpcode() != ISD::UNDEF &&
10364         FoldOp.getOpcode() != ISD::ConstantFP)
10365       break;
10366     Ops.push_back(FoldOp);
10367     AddToWorkList(FoldOp.getNode());
10368   }
10369
10370   if (Ops.size() != N0.getNumOperands())
10371     return SDValue();
10372
10373   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10374                      N0.getValueType(), &Ops[0], Ops.size());
10375 }
10376
10377 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10378                                     SDValue N1, SDValue N2){
10379   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10380
10381   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10382                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10383
10384   // If we got a simplified select_cc node back from SimplifySelectCC, then
10385   // break it down into a new SETCC node, and a new SELECT node, and then return
10386   // the SELECT node, since we were called with a SELECT node.
10387   if (SCC.getNode()) {
10388     // Check to see if we got a select_cc back (to turn into setcc/select).
10389     // Otherwise, just return whatever node we got back, like fabs.
10390     if (SCC.getOpcode() == ISD::SELECT_CC) {
10391       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10392                                   N0.getValueType(),
10393                                   SCC.getOperand(0), SCC.getOperand(1),
10394                                   SCC.getOperand(4));
10395       AddToWorkList(SETCC.getNode());
10396       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10397                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10398     }
10399
10400     return SCC;
10401   }
10402   return SDValue();
10403 }
10404
10405 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10406 /// are the two values being selected between, see if we can simplify the
10407 /// select.  Callers of this should assume that TheSelect is deleted if this
10408 /// returns true.  As such, they should return the appropriate thing (e.g. the
10409 /// node) back to the top-level of the DAG combiner loop to avoid it being
10410 /// looked at.
10411 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10412                                     SDValue RHS) {
10413
10414   // Cannot simplify select with vector condition
10415   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10416
10417   // If this is a select from two identical things, try to pull the operation
10418   // through the select.
10419   if (LHS.getOpcode() != RHS.getOpcode() ||
10420       !LHS.hasOneUse() || !RHS.hasOneUse())
10421     return false;
10422
10423   // If this is a load and the token chain is identical, replace the select
10424   // of two loads with a load through a select of the address to load from.
10425   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10426   // constants have been dropped into the constant pool.
10427   if (LHS.getOpcode() == ISD::LOAD) {
10428     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10429     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10430
10431     // Token chains must be identical.
10432     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10433         // Do not let this transformation reduce the number of volatile loads.
10434         LLD->isVolatile() || RLD->isVolatile() ||
10435         // If this is an EXTLOAD, the VT's must match.
10436         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10437         // If this is an EXTLOAD, the kind of extension must match.
10438         (LLD->getExtensionType() != RLD->getExtensionType() &&
10439          // The only exception is if one of the extensions is anyext.
10440          LLD->getExtensionType() != ISD::EXTLOAD &&
10441          RLD->getExtensionType() != ISD::EXTLOAD) ||
10442         // FIXME: this discards src value information.  This is
10443         // over-conservative. It would be beneficial to be able to remember
10444         // both potential memory locations.  Since we are discarding
10445         // src value info, don't do the transformation if the memory
10446         // locations are not in the default address space.
10447         LLD->getPointerInfo().getAddrSpace() != 0 ||
10448         RLD->getPointerInfo().getAddrSpace() != 0 ||
10449         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10450                                       LLD->getBasePtr().getValueType()))
10451       return false;
10452
10453     // Check that the select condition doesn't reach either load.  If so,
10454     // folding this will induce a cycle into the DAG.  If not, this is safe to
10455     // xform, so create a select of the addresses.
10456     SDValue Addr;
10457     if (TheSelect->getOpcode() == ISD::SELECT) {
10458       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10459       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10460           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10461         return false;
10462       // The loads must not depend on one another.
10463       if (LLD->isPredecessorOf(RLD) ||
10464           RLD->isPredecessorOf(LLD))
10465         return false;
10466       Addr = DAG.getSelect(SDLoc(TheSelect),
10467                            LLD->getBasePtr().getValueType(),
10468                            TheSelect->getOperand(0), LLD->getBasePtr(),
10469                            RLD->getBasePtr());
10470     } else {  // Otherwise SELECT_CC
10471       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10472       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10473
10474       if ((LLD->hasAnyUseOfValue(1) &&
10475            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10476           (RLD->hasAnyUseOfValue(1) &&
10477            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10478         return false;
10479
10480       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10481                          LLD->getBasePtr().getValueType(),
10482                          TheSelect->getOperand(0),
10483                          TheSelect->getOperand(1),
10484                          LLD->getBasePtr(), RLD->getBasePtr(),
10485                          TheSelect->getOperand(4));
10486     }
10487
10488     SDValue Load;
10489     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10490       Load = DAG.getLoad(TheSelect->getValueType(0),
10491                          SDLoc(TheSelect),
10492                          // FIXME: Discards pointer and TBAA info.
10493                          LLD->getChain(), Addr, MachinePointerInfo(),
10494                          LLD->isVolatile(), LLD->isNonTemporal(),
10495                          LLD->isInvariant(), LLD->getAlignment());
10496     } else {
10497       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10498                             RLD->getExtensionType() : LLD->getExtensionType(),
10499                             SDLoc(TheSelect),
10500                             TheSelect->getValueType(0),
10501                             // FIXME: Discards pointer and TBAA info.
10502                             LLD->getChain(), Addr, MachinePointerInfo(),
10503                             LLD->getMemoryVT(), LLD->isVolatile(),
10504                             LLD->isNonTemporal(), LLD->getAlignment());
10505     }
10506
10507     // Users of the select now use the result of the load.
10508     CombineTo(TheSelect, Load);
10509
10510     // Users of the old loads now use the new load's chain.  We know the
10511     // old-load value is dead now.
10512     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10513     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10514     return true;
10515   }
10516
10517   return false;
10518 }
10519
10520 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10521 /// where 'cond' is the comparison specified by CC.
10522 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10523                                       SDValue N2, SDValue N3,
10524                                       ISD::CondCode CC, bool NotExtCompare) {
10525   // (x ? y : y) -> y.
10526   if (N2 == N3) return N2;
10527
10528   EVT VT = N2.getValueType();
10529   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10530   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10531   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10532
10533   // Determine if the condition we're dealing with is constant
10534   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10535                               N0, N1, CC, DL, false);
10536   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10537   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10538
10539   // fold select_cc true, x, y -> x
10540   if (SCCC && !SCCC->isNullValue())
10541     return N2;
10542   // fold select_cc false, x, y -> y
10543   if (SCCC && SCCC->isNullValue())
10544     return N3;
10545
10546   // Check to see if we can simplify the select into an fabs node
10547   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10548     // Allow either -0.0 or 0.0
10549     if (CFP->getValueAPF().isZero()) {
10550       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10551       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10552           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10553           N2 == N3.getOperand(0))
10554         return DAG.getNode(ISD::FABS, DL, VT, N0);
10555
10556       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10557       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10558           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10559           N2.getOperand(0) == N3)
10560         return DAG.getNode(ISD::FABS, DL, VT, N3);
10561     }
10562   }
10563
10564   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10565   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10566   // in it.  This is a win when the constant is not otherwise available because
10567   // it replaces two constant pool loads with one.  We only do this if the FP
10568   // type is known to be legal, because if it isn't, then we are before legalize
10569   // types an we want the other legalization to happen first (e.g. to avoid
10570   // messing with soft float) and if the ConstantFP is not legal, because if
10571   // it is legal, we may not need to store the FP constant in a constant pool.
10572   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10573     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10574       if (TLI.isTypeLegal(N2.getValueType()) &&
10575           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10576            TargetLowering::Legal) &&
10577           // If both constants have multiple uses, then we won't need to do an
10578           // extra load, they are likely around in registers for other users.
10579           (TV->hasOneUse() || FV->hasOneUse())) {
10580         Constant *Elts[] = {
10581           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10582           const_cast<ConstantFP*>(TV->getConstantFPValue())
10583         };
10584         Type *FPTy = Elts[0]->getType();
10585         const DataLayout &TD = *TLI.getDataLayout();
10586
10587         // Create a ConstantArray of the two constants.
10588         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10589         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10590                                             TD.getPrefTypeAlignment(FPTy));
10591         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10592
10593         // Get the offsets to the 0 and 1 element of the array so that we can
10594         // select between them.
10595         SDValue Zero = DAG.getIntPtrConstant(0);
10596         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10597         SDValue One = DAG.getIntPtrConstant(EltSize);
10598
10599         SDValue Cond = DAG.getSetCC(DL,
10600                                     getSetCCResultType(N0.getValueType()),
10601                                     N0, N1, CC);
10602         AddToWorkList(Cond.getNode());
10603         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10604                                           Cond, One, Zero);
10605         AddToWorkList(CstOffset.getNode());
10606         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10607                             CstOffset);
10608         AddToWorkList(CPIdx.getNode());
10609         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10610                            MachinePointerInfo::getConstantPool(), false,
10611                            false, false, Alignment);
10612
10613       }
10614     }
10615
10616   // Check to see if we can perform the "gzip trick", transforming
10617   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10618   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10619       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10620        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10621     EVT XType = N0.getValueType();
10622     EVT AType = N2.getValueType();
10623     if (XType.bitsGE(AType)) {
10624       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10625       // single-bit constant.
10626       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10627         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10628         ShCtV = XType.getSizeInBits()-ShCtV-1;
10629         SDValue ShCt = DAG.getConstant(ShCtV,
10630                                        getShiftAmountTy(N0.getValueType()));
10631         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10632                                     XType, N0, ShCt);
10633         AddToWorkList(Shift.getNode());
10634
10635         if (XType.bitsGT(AType)) {
10636           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10637           AddToWorkList(Shift.getNode());
10638         }
10639
10640         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10641       }
10642
10643       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10644                                   XType, N0,
10645                                   DAG.getConstant(XType.getSizeInBits()-1,
10646                                          getShiftAmountTy(N0.getValueType())));
10647       AddToWorkList(Shift.getNode());
10648
10649       if (XType.bitsGT(AType)) {
10650         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10651         AddToWorkList(Shift.getNode());
10652       }
10653
10654       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10655     }
10656   }
10657
10658   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10659   // where y is has a single bit set.
10660   // A plaintext description would be, we can turn the SELECT_CC into an AND
10661   // when the condition can be materialized as an all-ones register.  Any
10662   // single bit-test can be materialized as an all-ones register with
10663   // shift-left and shift-right-arith.
10664   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10665       N0->getValueType(0) == VT &&
10666       N1C && N1C->isNullValue() &&
10667       N2C && N2C->isNullValue()) {
10668     SDValue AndLHS = N0->getOperand(0);
10669     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10670     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10671       // Shift the tested bit over the sign bit.
10672       APInt AndMask = ConstAndRHS->getAPIntValue();
10673       SDValue ShlAmt =
10674         DAG.getConstant(AndMask.countLeadingZeros(),
10675                         getShiftAmountTy(AndLHS.getValueType()));
10676       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10677
10678       // Now arithmetic right shift it all the way over, so the result is either
10679       // all-ones, or zero.
10680       SDValue ShrAmt =
10681         DAG.getConstant(AndMask.getBitWidth()-1,
10682                         getShiftAmountTy(Shl.getValueType()));
10683       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10684
10685       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10686     }
10687   }
10688
10689   // fold select C, 16, 0 -> shl C, 4
10690   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10691     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10692       TargetLowering::ZeroOrOneBooleanContent) {
10693
10694     // If the caller doesn't want us to simplify this into a zext of a compare,
10695     // don't do it.
10696     if (NotExtCompare && N2C->getAPIntValue() == 1)
10697       return SDValue();
10698
10699     // Get a SetCC of the condition
10700     // NOTE: Don't create a SETCC if it's not legal on this target.
10701     if (!LegalOperations ||
10702         TLI.isOperationLegal(ISD::SETCC,
10703           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10704       SDValue Temp, SCC;
10705       // cast from setcc result type to select result type
10706       if (LegalTypes) {
10707         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10708                             N0, N1, CC);
10709         if (N2.getValueType().bitsLT(SCC.getValueType()))
10710           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10711                                         N2.getValueType());
10712         else
10713           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10714                              N2.getValueType(), SCC);
10715       } else {
10716         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10717         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10718                            N2.getValueType(), SCC);
10719       }
10720
10721       AddToWorkList(SCC.getNode());
10722       AddToWorkList(Temp.getNode());
10723
10724       if (N2C->getAPIntValue() == 1)
10725         return Temp;
10726
10727       // shl setcc result by log2 n2c
10728       return DAG.getNode(
10729           ISD::SHL, DL, N2.getValueType(), Temp,
10730           DAG.getConstant(N2C->getAPIntValue().logBase2(),
10731                           getShiftAmountTy(Temp.getValueType())));
10732     }
10733   }
10734
10735   // Check to see if this is the equivalent of setcc
10736   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10737   // otherwise, go ahead with the folds.
10738   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10739     EVT XType = N0.getValueType();
10740     if (!LegalOperations ||
10741         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10742       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10743       if (Res.getValueType() != VT)
10744         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10745       return Res;
10746     }
10747
10748     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10749     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10750         (!LegalOperations ||
10751          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10752       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10753       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10754                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10755                                        getShiftAmountTy(Ctlz.getValueType())));
10756     }
10757     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10758     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10759       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10760                                   XType, DAG.getConstant(0, XType), N0);
10761       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10762       return DAG.getNode(ISD::SRL, DL, XType,
10763                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10764                          DAG.getConstant(XType.getSizeInBits()-1,
10765                                          getShiftAmountTy(XType)));
10766     }
10767     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10768     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10769       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10770                                  DAG.getConstant(XType.getSizeInBits()-1,
10771                                          getShiftAmountTy(N0.getValueType())));
10772       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10773     }
10774   }
10775
10776   // Check to see if this is an integer abs.
10777   // select_cc setg[te] X,  0,  X, -X ->
10778   // select_cc setgt    X, -1,  X, -X ->
10779   // select_cc setl[te] X,  0, -X,  X ->
10780   // select_cc setlt    X,  1, -X,  X ->
10781   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10782   if (N1C) {
10783     ConstantSDNode *SubC = NULL;
10784     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10785          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10786         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10787       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10788     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10789               (N1C->isOne() && CC == ISD::SETLT)) &&
10790              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10791       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10792
10793     EVT XType = N0.getValueType();
10794     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10795       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10796                                   N0,
10797                                   DAG.getConstant(XType.getSizeInBits()-1,
10798                                          getShiftAmountTy(N0.getValueType())));
10799       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10800                                 XType, N0, Shift);
10801       AddToWorkList(Shift.getNode());
10802       AddToWorkList(Add.getNode());
10803       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10804     }
10805   }
10806
10807   return SDValue();
10808 }
10809
10810 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10811 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10812                                    SDValue N1, ISD::CondCode Cond,
10813                                    SDLoc DL, bool foldBooleans) {
10814   TargetLowering::DAGCombinerInfo
10815     DagCombineInfo(DAG, Level, false, this);
10816   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10817 }
10818
10819 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10820 /// return a DAG expression to select that will generate the same value by
10821 /// multiplying by a magic number.  See:
10822 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10823 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10824   std::vector<SDNode*> Built;
10825   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10826
10827   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10828        ii != ee; ++ii)
10829     AddToWorkList(*ii);
10830   return S;
10831 }
10832
10833 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10834 /// return a DAG expression to select that will generate the same value by
10835 /// multiplying by a magic number.  See:
10836 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10837 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10838   std::vector<SDNode*> Built;
10839   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10840
10841   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10842        ii != ee; ++ii)
10843     AddToWorkList(*ii);
10844   return S;
10845 }
10846
10847 /// FindBaseOffset - Return true if base is a frame index, which is known not
10848 // to alias with anything but itself.  Provides base object and offset as
10849 // results.
10850 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10851                            const GlobalValue *&GV, const void *&CV) {
10852   // Assume it is a primitive operation.
10853   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10854
10855   // If it's an adding a simple constant then integrate the offset.
10856   if (Base.getOpcode() == ISD::ADD) {
10857     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10858       Base = Base.getOperand(0);
10859       Offset += C->getZExtValue();
10860     }
10861   }
10862
10863   // Return the underlying GlobalValue, and update the Offset.  Return false
10864   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10865   // by multiple nodes with different offsets.
10866   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10867     GV = G->getGlobal();
10868     Offset += G->getOffset();
10869     return false;
10870   }
10871
10872   // Return the underlying Constant value, and update the Offset.  Return false
10873   // for ConstantSDNodes since the same constant pool entry may be represented
10874   // by multiple nodes with different offsets.
10875   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10876     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10877                                          : (const void *)C->getConstVal();
10878     Offset += C->getOffset();
10879     return false;
10880   }
10881   // If it's any of the following then it can't alias with anything but itself.
10882   return isa<FrameIndexSDNode>(Base);
10883 }
10884
10885 /// isAlias - Return true if there is any possibility that the two addresses
10886 /// overlap.
10887 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
10888                           const Value *SrcValue1, int SrcValueOffset1,
10889                           unsigned SrcValueAlign1,
10890                           const MDNode *TBAAInfo1,
10891                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
10892                           const Value *SrcValue2, int SrcValueOffset2,
10893                           unsigned SrcValueAlign2,
10894                           const MDNode *TBAAInfo2) const {
10895   // If they are the same then they must be aliases.
10896   if (Ptr1 == Ptr2) return true;
10897
10898   // If they are both volatile then they cannot be reordered.
10899   if (IsVolatile1 && IsVolatile2) return true;
10900
10901   // Gather base node and offset information.
10902   SDValue Base1, Base2;
10903   int64_t Offset1, Offset2;
10904   const GlobalValue *GV1, *GV2;
10905   const void *CV1, *CV2;
10906   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10907   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10908
10909   // If they have a same base address then check to see if they overlap.
10910   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10911     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10912
10913   // It is possible for different frame indices to alias each other, mostly
10914   // when tail call optimization reuses return address slots for arguments.
10915   // To catch this case, look up the actual index of frame indices to compute
10916   // the real alias relationship.
10917   if (isFrameIndex1 && isFrameIndex2) {
10918     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10919     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10920     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10921     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10922   }
10923
10924   // Otherwise, if we know what the bases are, and they aren't identical, then
10925   // we know they cannot alias.
10926   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10927     return false;
10928
10929   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10930   // compared to the size and offset of the access, we may be able to prove they
10931   // do not alias.  This check is conservative for now to catch cases created by
10932   // splitting vector types.
10933   if ((SrcValueAlign1 == SrcValueAlign2) &&
10934       (SrcValueOffset1 != SrcValueOffset2) &&
10935       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10936     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10937     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10938
10939     // There is no overlap between these relatively aligned accesses of similar
10940     // size, return no alias.
10941     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10942       return false;
10943   }
10944
10945   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10946     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10947   if (UseAA && SrcValue1 && SrcValue2) {
10948     // Use alias analysis information.
10949     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10950     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10951     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10952     AliasAnalysis::AliasResult AAResult =
10953       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10954                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10955     if (AAResult == AliasAnalysis::NoAlias)
10956       return false;
10957   }
10958
10959   // Otherwise we have to assume they alias.
10960   return true;
10961 }
10962
10963 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10964   SDValue Ptr0, Ptr1;
10965   int64_t Size0, Size1;
10966   bool IsVolatile0, IsVolatile1;
10967   const Value *SrcValue0, *SrcValue1;
10968   int SrcValueOffset0, SrcValueOffset1;
10969   unsigned SrcValueAlign0, SrcValueAlign1;
10970   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10971   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10972                 SrcValueAlign0, SrcTBAAInfo0);
10973   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10974                 SrcValueAlign1, SrcTBAAInfo1);
10975   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
10976                  SrcValueAlign0, SrcTBAAInfo0,
10977                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
10978                  SrcValueAlign1, SrcTBAAInfo1);
10979 }
10980
10981 /// FindAliasInfo - Extracts the relevant alias information from the memory
10982 /// node.  Returns true if the operand was a nonvolatile load.
10983 bool DAGCombiner::FindAliasInfo(SDNode *N,
10984                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
10985                                 const Value *&SrcValue,
10986                                 int &SrcValueOffset,
10987                                 unsigned &SrcValueAlign,
10988                                 const MDNode *&TBAAInfo) const {
10989   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10990
10991   Ptr = LS->getBasePtr();
10992   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10993   IsVolatile = LS->isVolatile();
10994   SrcValue = LS->getSrcValue();
10995   SrcValueOffset = LS->getSrcValueOffset();
10996   SrcValueAlign = LS->getOriginalAlignment();
10997   TBAAInfo = LS->getTBAAInfo();
10998   return isa<LoadSDNode>(LS) && !IsVolatile;
10999 }
11000
11001 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11002 /// looking for aliasing nodes and adding them to the Aliases vector.
11003 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11004                                    SmallVectorImpl<SDValue> &Aliases) {
11005   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11006   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11007
11008   // Get alias information for node.
11009   SDValue Ptr;
11010   int64_t Size;
11011   bool IsVolatile;
11012   const Value *SrcValue;
11013   int SrcValueOffset;
11014   unsigned SrcValueAlign;
11015   const MDNode *SrcTBAAInfo;
11016   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11017                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11018
11019   // Starting off.
11020   Chains.push_back(OriginalChain);
11021   unsigned Depth = 0;
11022
11023   // Look at each chain and determine if it is an alias.  If so, add it to the
11024   // aliases list.  If not, then continue up the chain looking for the next
11025   // candidate.
11026   while (!Chains.empty()) {
11027     SDValue Chain = Chains.back();
11028     Chains.pop_back();
11029
11030     // For TokenFactor nodes, look at each operand and only continue up the
11031     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11032     // find more and revert to original chain since the xform is unlikely to be
11033     // profitable.
11034     //
11035     // FIXME: The depth check could be made to return the last non-aliasing
11036     // chain we found before we hit a tokenfactor rather than the original
11037     // chain.
11038     if (Depth > 6 || Aliases.size() == 2) {
11039       Aliases.clear();
11040       Aliases.push_back(OriginalChain);
11041       break;
11042     }
11043
11044     // Don't bother if we've been before.
11045     if (!Visited.insert(Chain.getNode()))
11046       continue;
11047
11048     switch (Chain.getOpcode()) {
11049     case ISD::EntryToken:
11050       // Entry token is ideal chain operand, but handled in FindBetterChain.
11051       break;
11052
11053     case ISD::LOAD:
11054     case ISD::STORE: {
11055       // Get alias information for Chain.
11056       SDValue OpPtr;
11057       int64_t OpSize;
11058       bool OpIsVolatile;
11059       const Value *OpSrcValue;
11060       int OpSrcValueOffset;
11061       unsigned OpSrcValueAlign;
11062       const MDNode *OpSrcTBAAInfo;
11063       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11064                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11065                                     OpSrcValueAlign,
11066                                     OpSrcTBAAInfo);
11067
11068       // If chain is alias then stop here.
11069       if (!(IsLoad && IsOpLoad) &&
11070           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11071                   SrcValueAlign, SrcTBAAInfo,
11072                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11073                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11074         Aliases.push_back(Chain);
11075       } else {
11076         // Look further up the chain.
11077         Chains.push_back(Chain.getOperand(0));
11078         ++Depth;
11079       }
11080       break;
11081     }
11082
11083     case ISD::TokenFactor:
11084       // We have to check each of the operands of the token factor for "small"
11085       // token factors, so we queue them up.  Adding the operands to the queue
11086       // (stack) in reverse order maintains the original order and increases the
11087       // likelihood that getNode will find a matching token factor (CSE.)
11088       if (Chain.getNumOperands() > 16) {
11089         Aliases.push_back(Chain);
11090         break;
11091       }
11092       for (unsigned n = Chain.getNumOperands(); n;)
11093         Chains.push_back(Chain.getOperand(--n));
11094       ++Depth;
11095       break;
11096
11097     default:
11098       // For all other instructions we will just have to take what we can get.
11099       Aliases.push_back(Chain);
11100       break;
11101     }
11102   }
11103 }
11104
11105 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11106 /// for a better chain (aliasing node.)
11107 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11108   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11109
11110   // Accumulate all the aliases to this node.
11111   GatherAllAliases(N, OldChain, Aliases);
11112
11113   // If no operands then chain to entry token.
11114   if (Aliases.size() == 0)
11115     return DAG.getEntryNode();
11116
11117   // If a single operand then chain to it.  We don't need to revisit it.
11118   if (Aliases.size() == 1)
11119     return Aliases[0];
11120
11121   // Construct a custom tailored token factor.
11122   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11123                      &Aliases[0], Aliases.size());
11124 }
11125
11126 // SelectionDAG::Combine - This is the entry point for the file.
11127 //
11128 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11129                            CodeGenOpt::Level OptLevel) {
11130   /// run - This is the main entry point to this class.
11131   ///
11132   DAGCombiner(*this, AA, OptLevel).Run(Level);
11133 }