Prevent alias from pointing to weak aliases.
[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("Enable DAG combiner alias-analysis heuristics"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Enable DAG combiner's use of IR alias analysis"));
58
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 //   1. Stack coloring does not update TBAA when merging allocas
61 //   2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 //      Because BasicAA does not handle inttoptr, we'll often miss basic type
63 //      punning idioms that we need to catch so we don't miscompile real-world
64 //      code.
65   static cl::opt<bool>
66     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67                cl::desc("Enable DAG combiner's use of TBAA"));
68
69 #ifndef NDEBUG
70   static cl::opt<std::string>
71     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72                cl::desc("Only use DAG-combiner alias analysis in this"
73                         " function"));
74 #endif
75
76   /// Hidden option to stress test load slicing, i.e., when this option
77   /// is enabled, load slicing bypasses most of its profitability guards.
78   static cl::opt<bool>
79   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80                     cl::desc("Bypass the profitability model of load "
81                              "slicing"),
82                     cl::init(false));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     // Worklist of all of the nodes that need to be simplified.
96     //
97     // This has the semantics that when adding to the worklist,
98     // the item added must be next to be processed. It should
99     // also only appear once. The naive approach to this takes
100     // linear time.
101     //
102     // To reduce the insert/remove time to logarithmic, we use
103     // a set and a vector to maintain our worklist.
104     //
105     // The set contains the items on the worklist, but does not
106     // maintain the order they should be visited.
107     //
108     // The vector maintains the order nodes should be visited, but may
109     // contain duplicate or removed nodes. When choosing a node to
110     // visit, we pop off the order stack until we find an item that is
111     // also in the contents set. All operations are O(log N).
112     SmallPtrSet<SDNode*, 64> WorkListContents;
113     SmallVector<SDNode*, 64> WorkListOrder;
114
115     // AA - Used for DAG load/store alias analysis.
116     AliasAnalysis &AA;
117
118     /// AddUsersToWorkList - When an instruction is simplified, add all users of
119     /// the instruction to the work lists because they might get more simplified
120     /// now.
121     ///
122     void AddUsersToWorkList(SDNode *N) {
123       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
124            UI != UE; ++UI)
125         AddToWorkList(*UI);
126     }
127
128     /// visit - call the node-specific routine that knows how to fold each
129     /// particular type of node.
130     SDValue visit(SDNode *N);
131
132   public:
133     /// AddToWorkList - Add to the work list making sure its instance is at the
134     /// back (next to be processed.)
135     void AddToWorkList(SDNode *N) {
136       WorkListContents.insert(N);
137       WorkListOrder.push_back(N);
138     }
139
140     /// removeFromWorkList - remove all instances of N from the worklist.
141     ///
142     void removeFromWorkList(SDNode *N) {
143       WorkListContents.erase(N);
144     }
145
146     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
147                       bool AddTo = true);
148
149     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150       return CombineTo(N, &Res, 1, AddTo);
151     }
152
153     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
154                       bool AddTo = true) {
155       SDValue To[] = { Res0, Res1 };
156       return CombineTo(N, To, 2, AddTo);
157     }
158
159     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
160
161   private:
162
163     /// SimplifyDemandedBits - Check the specified integer node value to see if
164     /// it can be simplified or if things it uses can be simplified by bit
165     /// propagation.  If so, return true.
166     bool SimplifyDemandedBits(SDValue Op) {
167       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168       APInt Demanded = APInt::getAllOnesValue(BitWidth);
169       return SimplifyDemandedBits(Op, Demanded);
170     }
171
172     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
173
174     bool CombineToPreIndexedLoadStore(SDNode *N);
175     bool CombineToPostIndexedLoadStore(SDNode *N);
176     bool SliceUpLoad(SDNode *N);
177
178     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182     SDValue PromoteIntBinOp(SDValue Op);
183     SDValue PromoteIntShiftOp(SDValue Op);
184     SDValue PromoteExtend(SDValue Op);
185     bool PromoteLoad(SDValue Op);
186
187     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189                          ISD::NodeType ExtType);
190
191     /// combine - call the node-specific routine that knows how to fold each
192     /// particular type of node. If that doesn't do anything, try the
193     /// target-specific DAG combines.
194     SDValue combine(SDNode *N);
195
196     // Visitation implementation - Implement dag node combining for different
197     // node types.  The semantics are as follows:
198     // Return Value:
199     //   SDValue.getNode() == 0 - No change was made
200     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
201     //   otherwise              - N should be replaced by the returned Operand.
202     //
203     SDValue visitTokenFactor(SDNode *N);
204     SDValue visitMERGE_VALUES(SDNode *N);
205     SDValue visitADD(SDNode *N);
206     SDValue visitSUB(SDNode *N);
207     SDValue visitADDC(SDNode *N);
208     SDValue visitSUBC(SDNode *N);
209     SDValue visitADDE(SDNode *N);
210     SDValue visitSUBE(SDNode *N);
211     SDValue visitMUL(SDNode *N);
212     SDValue visitSDIV(SDNode *N);
213     SDValue visitUDIV(SDNode *N);
214     SDValue visitSREM(SDNode *N);
215     SDValue visitUREM(SDNode *N);
216     SDValue visitMULHU(SDNode *N);
217     SDValue visitMULHS(SDNode *N);
218     SDValue visitSMUL_LOHI(SDNode *N);
219     SDValue visitUMUL_LOHI(SDNode *N);
220     SDValue visitSMULO(SDNode *N);
221     SDValue visitUMULO(SDNode *N);
222     SDValue visitSDIVREM(SDNode *N);
223     SDValue visitUDIVREM(SDNode *N);
224     SDValue visitAND(SDNode *N);
225     SDValue visitOR(SDNode *N);
226     SDValue visitXOR(SDNode *N);
227     SDValue SimplifyVBinOp(SDNode *N);
228     SDValue SimplifyVUnaryOp(SDNode *N);
229     SDValue visitSHL(SDNode *N);
230     SDValue visitSRA(SDNode *N);
231     SDValue visitSRL(SDNode *N);
232     SDValue visitRotate(SDNode *N);
233     SDValue visitCTLZ(SDNode *N);
234     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
235     SDValue visitCTTZ(SDNode *N);
236     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
237     SDValue visitCTPOP(SDNode *N);
238     SDValue visitSELECT(SDNode *N);
239     SDValue visitVSELECT(SDNode *N);
240     SDValue visitSELECT_CC(SDNode *N);
241     SDValue visitSETCC(SDNode *N);
242     SDValue visitSIGN_EXTEND(SDNode *N);
243     SDValue visitZERO_EXTEND(SDNode *N);
244     SDValue visitANY_EXTEND(SDNode *N);
245     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
246     SDValue visitTRUNCATE(SDNode *N);
247     SDValue visitBITCAST(SDNode *N);
248     SDValue visitBUILD_PAIR(SDNode *N);
249     SDValue visitFADD(SDNode *N);
250     SDValue visitFSUB(SDNode *N);
251     SDValue visitFMUL(SDNode *N);
252     SDValue visitFMA(SDNode *N);
253     SDValue visitFDIV(SDNode *N);
254     SDValue visitFREM(SDNode *N);
255     SDValue visitFCOPYSIGN(SDNode *N);
256     SDValue visitSINT_TO_FP(SDNode *N);
257     SDValue visitUINT_TO_FP(SDNode *N);
258     SDValue visitFP_TO_SINT(SDNode *N);
259     SDValue visitFP_TO_UINT(SDNode *N);
260     SDValue visitFP_ROUND(SDNode *N);
261     SDValue visitFP_ROUND_INREG(SDNode *N);
262     SDValue visitFP_EXTEND(SDNode *N);
263     SDValue visitFNEG(SDNode *N);
264     SDValue visitFABS(SDNode *N);
265     SDValue visitFCEIL(SDNode *N);
266     SDValue visitFTRUNC(SDNode *N);
267     SDValue visitFFLOOR(SDNode *N);
268     SDValue visitBRCOND(SDNode *N);
269     SDValue visitBR_CC(SDNode *N);
270     SDValue visitLOAD(SDNode *N);
271     SDValue visitSTORE(SDNode *N);
272     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
273     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
274     SDValue visitBUILD_VECTOR(SDNode *N);
275     SDValue visitCONCAT_VECTORS(SDNode *N);
276     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
277     SDValue visitVECTOR_SHUFFLE(SDNode *N);
278     SDValue visitINSERT_SUBVECTOR(SDNode *N);
279
280     SDValue XformToShuffleWithZero(SDNode *N);
281     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
282
283     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
284
285     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
286     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
287     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
288     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
289                              SDValue N3, ISD::CondCode CC,
290                              bool NotExtCompare = false);
291     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
292                           SDLoc DL, bool foldBooleans = true);
293     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
294                                          unsigned HiOp);
295     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
296     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
297     SDValue BuildSDIV(SDNode *N);
298     SDValue BuildUDIV(SDNode *N);
299     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
300                                bool DemandHighBits = true);
301     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
302     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
303                               SDValue InnerPos, SDValue InnerNeg,
304                               unsigned PosOpcode, unsigned NegOpcode,
305                               SDLoc DL);
306     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
307     SDValue ReduceLoadWidth(SDNode *N);
308     SDValue ReduceLoadOpStoreWidth(SDNode *N);
309     SDValue TransformFPLoadStorePair(SDNode *N);
310     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
311     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
312
313     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
314
315     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
316     /// looking for aliasing nodes and adding them to the Aliases vector.
317     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
318                           SmallVectorImpl<SDValue> &Aliases);
319
320     /// isAlias - Return true if there is any possibility that the two addresses
321     /// overlap.
322     bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
323                  const Value *SrcValue1, int SrcValueOffset1,
324                  unsigned SrcValueAlign1,
325                  const MDNode *TBAAInfo1,
326                  SDValue Ptr2, int64_t Size2, bool IsVolatile2,
327                  const Value *SrcValue2, int SrcValueOffset2,
328                  unsigned SrcValueAlign2,
329                  const MDNode *TBAAInfo2) const;
330
331     /// isAlias - Return true if there is any possibility that the two addresses
332     /// overlap.
333     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
334
335     /// FindAliasInfo - Extracts the relevant alias information from the memory
336     /// node.  Returns true if the operand was a load.
337     bool FindAliasInfo(SDNode *N,
338                        SDValue &Ptr, int64_t &Size, bool &IsVolatile,
339                        const Value *&SrcValue, int &SrcValueOffset,
340                        unsigned &SrcValueAlignment,
341                        const MDNode *&TBAAInfo) const;
342
343     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
344     /// looking for a better chain (aliasing node.)
345     SDValue FindBetterChain(SDNode *N, SDValue Chain);
346
347     /// Merge consecutive store operations into a wide store.
348     /// This optimization uses wide integers or vectors when possible.
349     /// \return True if some memory operations were changed.
350     bool MergeConsecutiveStores(StoreSDNode *N);
351
352     /// \brief Try to transform a truncation where C is a constant:
353     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
354     ///
355     /// \p N needs to be a truncation and its first operand an AND. Other
356     /// requirements are checked by the function (e.g. that trunc is
357     /// single-use) and if missed an empty SDValue is returned.
358     SDValue distributeTruncateThroughAnd(SDNode *N);
359
360   public:
361     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
362         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
363           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
364       AttributeSet FnAttrs =
365           DAG.getMachineFunction().getFunction()->getAttributes();
366       ForCodeSize =
367           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
368                                Attribute::OptimizeForSize) ||
369           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
370     }
371
372     /// Run - runs the dag combiner on all nodes in the work list
373     void Run(CombineLevel AtLevel);
374
375     SelectionDAG &getDAG() const { return DAG; }
376
377     /// getShiftAmountTy - Returns a type large enough to hold any valid
378     /// shift amount - before type legalization these can be huge.
379     EVT getShiftAmountTy(EVT LHSTy) {
380       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
381       if (LHSTy.isVector())
382         return LHSTy;
383       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
384                         : TLI.getPointerTy();
385     }
386
387     /// isTypeLegal - This method returns true if we are running before type
388     /// legalization or if the specified VT is legal.
389     bool isTypeLegal(const EVT &VT) {
390       if (!LegalTypes) return true;
391       return TLI.isTypeLegal(VT);
392     }
393
394     /// getSetCCResultType - Convenience wrapper around
395     /// TargetLowering::getSetCCResultType
396     EVT getSetCCResultType(EVT VT) const {
397       return TLI.getSetCCResultType(*DAG.getContext(), VT);
398     }
399   };
400 }
401
402
403 namespace {
404 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
405 /// nodes from the worklist.
406 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
407   DAGCombiner &DC;
408 public:
409   explicit WorkListRemover(DAGCombiner &dc)
410     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
411
412   void NodeDeleted(SDNode *N, SDNode *E) override {
413     DC.removeFromWorkList(N);
414   }
415 };
416 }
417
418 //===----------------------------------------------------------------------===//
419 //  TargetLowering::DAGCombinerInfo implementation
420 //===----------------------------------------------------------------------===//
421
422 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
423   ((DAGCombiner*)DC)->AddToWorkList(N);
424 }
425
426 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
427   ((DAGCombiner*)DC)->removeFromWorkList(N);
428 }
429
430 SDValue TargetLowering::DAGCombinerInfo::
431 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
432   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
433 }
434
435 SDValue TargetLowering::DAGCombinerInfo::
436 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
437   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
438 }
439
440
441 SDValue TargetLowering::DAGCombinerInfo::
442 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
443   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
444 }
445
446 void TargetLowering::DAGCombinerInfo::
447 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
448   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
449 }
450
451 //===----------------------------------------------------------------------===//
452 // Helper Functions
453 //===----------------------------------------------------------------------===//
454
455 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
456 /// specified expression for the same cost as the expression itself, or 2 if we
457 /// can compute the negated form more cheaply than the expression itself.
458 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
459                                const TargetLowering &TLI,
460                                const TargetOptions *Options,
461                                unsigned Depth = 0) {
462   // fneg is removable even if it has multiple uses.
463   if (Op.getOpcode() == ISD::FNEG) return 2;
464
465   // Don't allow anything with multiple uses.
466   if (!Op.hasOneUse()) return 0;
467
468   // Don't recurse exponentially.
469   if (Depth > 6) return 0;
470
471   switch (Op.getOpcode()) {
472   default: return false;
473   case ISD::ConstantFP:
474     // Don't invert constant FP values after legalize.  The negated constant
475     // isn't necessarily legal.
476     return LegalOperations ? 0 : 1;
477   case ISD::FADD:
478     // FIXME: determine better conditions for this xform.
479     if (!Options->UnsafeFPMath) return 0;
480
481     // After operation legalization, it might not be legal to create new FSUBs.
482     if (LegalOperations &&
483         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
484       return 0;
485
486     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
487     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
488                                     Options, Depth + 1))
489       return V;
490     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
491     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
492                               Depth + 1);
493   case ISD::FSUB:
494     // We can't turn -(A-B) into B-A when we honor signed zeros.
495     if (!Options->UnsafeFPMath) return 0;
496
497     // fold (fneg (fsub A, B)) -> (fsub B, A)
498     return 1;
499
500   case ISD::FMUL:
501   case ISD::FDIV:
502     if (Options->HonorSignDependentRoundingFPMath()) return 0;
503
504     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
505     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
506                                     Options, Depth + 1))
507       return V;
508
509     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
510                               Depth + 1);
511
512   case ISD::FP_EXTEND:
513   case ISD::FP_ROUND:
514   case ISD::FSIN:
515     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
516                               Depth + 1);
517   }
518 }
519
520 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
521 /// returns the newly negated expression.
522 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
523                                     bool LegalOperations, unsigned Depth = 0) {
524   // fneg is removable even if it has multiple uses.
525   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
526
527   // Don't allow anything with multiple uses.
528   assert(Op.hasOneUse() && "Unknown reuse!");
529
530   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
531   switch (Op.getOpcode()) {
532   default: llvm_unreachable("Unknown code");
533   case ISD::ConstantFP: {
534     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
535     V.changeSign();
536     return DAG.getConstantFP(V, Op.getValueType());
537   }
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     assert(DAG.getTarget().Options.UnsafeFPMath);
541
542     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
543     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
544                            DAG.getTargetLoweringInfo(),
545                            &DAG.getTarget().Options, Depth+1))
546       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
547                          GetNegatedExpression(Op.getOperand(0), DAG,
548                                               LegalOperations, Depth+1),
549                          Op.getOperand(1));
550     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
551     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
552                        GetNegatedExpression(Op.getOperand(1), DAG,
553                                             LegalOperations, Depth+1),
554                        Op.getOperand(0));
555   case ISD::FSUB:
556     // We can't turn -(A-B) into B-A when we honor signed zeros.
557     assert(DAG.getTarget().Options.UnsafeFPMath);
558
559     // fold (fneg (fsub 0, B)) -> B
560     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
561       if (N0CFP->getValueAPF().isZero())
562         return Op.getOperand(1);
563
564     // fold (fneg (fsub A, B)) -> (fsub B, A)
565     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
566                        Op.getOperand(1), Op.getOperand(0));
567
568   case ISD::FMUL:
569   case ISD::FDIV:
570     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
571
572     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
573     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
574                            DAG.getTargetLoweringInfo(),
575                            &DAG.getTarget().Options, Depth+1))
576       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
577                          GetNegatedExpression(Op.getOperand(0), DAG,
578                                               LegalOperations, Depth+1),
579                          Op.getOperand(1));
580
581     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
582     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
583                        Op.getOperand(0),
584                        GetNegatedExpression(Op.getOperand(1), DAG,
585                                             LegalOperations, Depth+1));
586
587   case ISD::FP_EXTEND:
588   case ISD::FSIN:
589     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
590                        GetNegatedExpression(Op.getOperand(0), DAG,
591                                             LegalOperations, Depth+1));
592   case ISD::FP_ROUND:
593       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
594                          GetNegatedExpression(Op.getOperand(0), DAG,
595                                               LegalOperations, Depth+1),
596                          Op.getOperand(1));
597   }
598 }
599
600
601 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
602 // that selects between the values 1 and 0, making it equivalent to a setcc.
603 // Also, set the incoming LHS, RHS, and CC references to the appropriate
604 // nodes based on the type of node we are checking.  This simplifies life a
605 // bit for the callers.
606 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
607                               SDValue &CC) {
608   if (N.getOpcode() == ISD::SETCC) {
609     LHS = N.getOperand(0);
610     RHS = N.getOperand(1);
611     CC  = N.getOperand(2);
612     return true;
613   }
614   if (N.getOpcode() == ISD::SELECT_CC &&
615       N.getOperand(2).getOpcode() == ISD::Constant &&
616       N.getOperand(3).getOpcode() == ISD::Constant &&
617       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
618       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
619     LHS = N.getOperand(0);
620     RHS = N.getOperand(1);
621     CC  = N.getOperand(4);
622     return true;
623   }
624   return false;
625 }
626
627 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
628 // one use.  If this is true, it allows the users to invert the operation for
629 // free when it is profitable to do so.
630 static bool isOneUseSetCC(SDValue N) {
631   SDValue N0, N1, N2;
632   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
633     return true;
634   return false;
635 }
636
637 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
638 /// elements are all the same constant or undefined.
639 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
640   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
641   if (!C)
642     return false;
643
644   APInt SplatUndef;
645   unsigned SplatBitSize;
646   bool HasAnyUndefs;
647   EVT EltVT = N->getValueType(0).getVectorElementType();
648   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
649                              HasAnyUndefs) &&
650           EltVT.getSizeInBits() >= SplatBitSize);
651 }
652
653 // \brief Returns the SDNode if it is a constant BuildVector or constant.
654 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
655   if (isa<ConstantSDNode>(N))
656     return N.getNode();
657   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
658   if(BV && BV->isConstant())
659     return BV;
660   return NULL;
661 }
662
663 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
664 // int.
665 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
666   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
667     return CN;
668
669   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
670     return BV->getConstantSplatValue();
671
672   return nullptr;
673 }
674
675 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
676                                     SDValue N0, SDValue N1) {
677   EVT VT = N0.getValueType();
678   if (N0.getOpcode() == Opc) {
679     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
680       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
681         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
682         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
683         if (!OpNode.getNode())
684           return SDValue();
685         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
686       }
687       if (N0.hasOneUse()) {
688         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
689         // use
690         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
691         if (!OpNode.getNode())
692           return SDValue();
693         AddToWorkList(OpNode.getNode());
694         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
695       }
696     }
697   }
698
699   if (N1.getOpcode() == Opc) {
700     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
701       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
702         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
703         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
704         if (!OpNode.getNode())
705           return SDValue();
706         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
707       }
708       if (N1.hasOneUse()) {
709         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
710         // use
711         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
712         if (!OpNode.getNode())
713           return SDValue();
714         AddToWorkList(OpNode.getNode());
715         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
716       }
717     }
718   }
719
720   return SDValue();
721 }
722
723 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
724                                bool AddTo) {
725   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
726   ++NodesCombined;
727   DEBUG(dbgs() << "\nReplacing.1 ";
728         N->dump(&DAG);
729         dbgs() << "\nWith: ";
730         To[0].getNode()->dump(&DAG);
731         dbgs() << " and " << NumTo-1 << " other values\n";
732         for (unsigned i = 0, e = NumTo; i != e; ++i)
733           assert((!To[i].getNode() ||
734                   N->getValueType(i) == To[i].getValueType()) &&
735                  "Cannot combine value to value of different type!"));
736   WorkListRemover DeadNodes(*this);
737   DAG.ReplaceAllUsesWith(N, To);
738   if (AddTo) {
739     // Push the new nodes and any users onto the worklist
740     for (unsigned i = 0, e = NumTo; i != e; ++i) {
741       if (To[i].getNode()) {
742         AddToWorkList(To[i].getNode());
743         AddUsersToWorkList(To[i].getNode());
744       }
745     }
746   }
747
748   // Finally, if the node is now dead, remove it from the graph.  The node
749   // may not be dead if the replacement process recursively simplified to
750   // something else needing this node.
751   if (N->use_empty()) {
752     // Nodes can be reintroduced into the worklist.  Make sure we do not
753     // process a node that has been replaced.
754     removeFromWorkList(N);
755
756     // Finally, since the node is now dead, remove it from the graph.
757     DAG.DeleteNode(N);
758   }
759   return SDValue(N, 0);
760 }
761
762 void DAGCombiner::
763 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
764   // Replace all uses.  If any nodes become isomorphic to other nodes and
765   // are deleted, make sure to remove them from our worklist.
766   WorkListRemover DeadNodes(*this);
767   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
768
769   // Push the new node and any (possibly new) users onto the worklist.
770   AddToWorkList(TLO.New.getNode());
771   AddUsersToWorkList(TLO.New.getNode());
772
773   // Finally, if the node is now dead, remove it from the graph.  The node
774   // may not be dead if the replacement process recursively simplified to
775   // something else needing this node.
776   if (TLO.Old.getNode()->use_empty()) {
777     removeFromWorkList(TLO.Old.getNode());
778
779     // If the operands of this node are only used by the node, they will now
780     // be dead.  Make sure to visit them first to delete dead nodes early.
781     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
782       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
783         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
784
785     DAG.DeleteNode(TLO.Old.getNode());
786   }
787 }
788
789 /// SimplifyDemandedBits - Check the specified integer node value to see if
790 /// it can be simplified or if things it uses can be simplified by bit
791 /// propagation.  If so, return true.
792 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
793   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
794   APInt KnownZero, KnownOne;
795   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
796     return false;
797
798   // Revisit the node.
799   AddToWorkList(Op.getNode());
800
801   // Replace the old value with the new one.
802   ++NodesCombined;
803   DEBUG(dbgs() << "\nReplacing.2 ";
804         TLO.Old.getNode()->dump(&DAG);
805         dbgs() << "\nWith: ";
806         TLO.New.getNode()->dump(&DAG);
807         dbgs() << '\n');
808
809   CommitTargetLoweringOpt(TLO);
810   return true;
811 }
812
813 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
814   SDLoc dl(Load);
815   EVT VT = Load->getValueType(0);
816   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
817
818   DEBUG(dbgs() << "\nReplacing.9 ";
819         Load->dump(&DAG);
820         dbgs() << "\nWith: ";
821         Trunc.getNode()->dump(&DAG);
822         dbgs() << '\n');
823   WorkListRemover DeadNodes(*this);
824   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
825   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
826   removeFromWorkList(Load);
827   DAG.DeleteNode(Load);
828   AddToWorkList(Trunc.getNode());
829 }
830
831 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
832   Replace = false;
833   SDLoc dl(Op);
834   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
835     EVT MemVT = LD->getMemoryVT();
836     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
837       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
838                                                   : ISD::EXTLOAD)
839       : LD->getExtensionType();
840     Replace = true;
841     return DAG.getExtLoad(ExtType, dl, PVT,
842                           LD->getChain(), LD->getBasePtr(),
843                           MemVT, LD->getMemOperand());
844   }
845
846   unsigned Opc = Op.getOpcode();
847   switch (Opc) {
848   default: break;
849   case ISD::AssertSext:
850     return DAG.getNode(ISD::AssertSext, dl, PVT,
851                        SExtPromoteOperand(Op.getOperand(0), PVT),
852                        Op.getOperand(1));
853   case ISD::AssertZext:
854     return DAG.getNode(ISD::AssertZext, dl, PVT,
855                        ZExtPromoteOperand(Op.getOperand(0), PVT),
856                        Op.getOperand(1));
857   case ISD::Constant: {
858     unsigned ExtOpc =
859       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
860     return DAG.getNode(ExtOpc, dl, PVT, Op);
861   }
862   }
863
864   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
865     return SDValue();
866   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
867 }
868
869 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
870   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
871     return SDValue();
872   EVT OldVT = Op.getValueType();
873   SDLoc dl(Op);
874   bool Replace = false;
875   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
876   if (NewOp.getNode() == 0)
877     return SDValue();
878   AddToWorkList(NewOp.getNode());
879
880   if (Replace)
881     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
882   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
883                      DAG.getValueType(OldVT));
884 }
885
886 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
887   EVT OldVT = Op.getValueType();
888   SDLoc dl(Op);
889   bool Replace = false;
890   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
891   if (NewOp.getNode() == 0)
892     return SDValue();
893   AddToWorkList(NewOp.getNode());
894
895   if (Replace)
896     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
897   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
898 }
899
900 /// PromoteIntBinOp - Promote the specified integer binary operation if the
901 /// target indicates it is beneficial. e.g. On x86, it's usually better to
902 /// promote i16 operations to i32 since i16 instructions are longer.
903 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
904   if (!LegalOperations)
905     return SDValue();
906
907   EVT VT = Op.getValueType();
908   if (VT.isVector() || !VT.isInteger())
909     return SDValue();
910
911   // If operation type is 'undesirable', e.g. i16 on x86, consider
912   // promoting it.
913   unsigned Opc = Op.getOpcode();
914   if (TLI.isTypeDesirableForOp(Opc, VT))
915     return SDValue();
916
917   EVT PVT = VT;
918   // Consult target whether it is a good idea to promote this operation and
919   // what's the right type to promote it to.
920   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
921     assert(PVT != VT && "Don't know what type to promote to!");
922
923     bool Replace0 = false;
924     SDValue N0 = Op.getOperand(0);
925     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
926     if (NN0.getNode() == 0)
927       return SDValue();
928
929     bool Replace1 = false;
930     SDValue N1 = Op.getOperand(1);
931     SDValue NN1;
932     if (N0 == N1)
933       NN1 = NN0;
934     else {
935       NN1 = PromoteOperand(N1, PVT, Replace1);
936       if (NN1.getNode() == 0)
937         return SDValue();
938     }
939
940     AddToWorkList(NN0.getNode());
941     if (NN1.getNode())
942       AddToWorkList(NN1.getNode());
943
944     if (Replace0)
945       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
946     if (Replace1)
947       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
948
949     DEBUG(dbgs() << "\nPromoting ";
950           Op.getNode()->dump(&DAG));
951     SDLoc dl(Op);
952     return DAG.getNode(ISD::TRUNCATE, dl, VT,
953                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
954   }
955   return SDValue();
956 }
957
958 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
959 /// target indicates it is beneficial. e.g. On x86, it's usually better to
960 /// promote i16 operations to i32 since i16 instructions are longer.
961 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
962   if (!LegalOperations)
963     return SDValue();
964
965   EVT VT = Op.getValueType();
966   if (VT.isVector() || !VT.isInteger())
967     return SDValue();
968
969   // If operation type is 'undesirable', e.g. i16 on x86, consider
970   // promoting it.
971   unsigned Opc = Op.getOpcode();
972   if (TLI.isTypeDesirableForOp(Opc, VT))
973     return SDValue();
974
975   EVT PVT = VT;
976   // Consult target whether it is a good idea to promote this operation and
977   // what's the right type to promote it to.
978   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
979     assert(PVT != VT && "Don't know what type to promote to!");
980
981     bool Replace = false;
982     SDValue N0 = Op.getOperand(0);
983     if (Opc == ISD::SRA)
984       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
985     else if (Opc == ISD::SRL)
986       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
987     else
988       N0 = PromoteOperand(N0, PVT, Replace);
989     if (N0.getNode() == 0)
990       return SDValue();
991
992     AddToWorkList(N0.getNode());
993     if (Replace)
994       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
995
996     DEBUG(dbgs() << "\nPromoting ";
997           Op.getNode()->dump(&DAG));
998     SDLoc dl(Op);
999     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1000                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1001   }
1002   return SDValue();
1003 }
1004
1005 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1006   if (!LegalOperations)
1007     return SDValue();
1008
1009   EVT VT = Op.getValueType();
1010   if (VT.isVector() || !VT.isInteger())
1011     return SDValue();
1012
1013   // If operation type is 'undesirable', e.g. i16 on x86, consider
1014   // promoting it.
1015   unsigned Opc = Op.getOpcode();
1016   if (TLI.isTypeDesirableForOp(Opc, VT))
1017     return SDValue();
1018
1019   EVT PVT = VT;
1020   // Consult target whether it is a good idea to promote this operation and
1021   // what's the right type to promote it to.
1022   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023     assert(PVT != VT && "Don't know what type to promote to!");
1024     // fold (aext (aext x)) -> (aext x)
1025     // fold (aext (zext x)) -> (zext x)
1026     // fold (aext (sext x)) -> (sext x)
1027     DEBUG(dbgs() << "\nPromoting ";
1028           Op.getNode()->dump(&DAG));
1029     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1030   }
1031   return SDValue();
1032 }
1033
1034 bool DAGCombiner::PromoteLoad(SDValue Op) {
1035   if (!LegalOperations)
1036     return false;
1037
1038   EVT VT = Op.getValueType();
1039   if (VT.isVector() || !VT.isInteger())
1040     return false;
1041
1042   // If operation type is 'undesirable', e.g. i16 on x86, consider
1043   // promoting it.
1044   unsigned Opc = Op.getOpcode();
1045   if (TLI.isTypeDesirableForOp(Opc, VT))
1046     return false;
1047
1048   EVT PVT = VT;
1049   // Consult target whether it is a good idea to promote this operation and
1050   // what's the right type to promote it to.
1051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052     assert(PVT != VT && "Don't know what type to promote to!");
1053
1054     SDLoc dl(Op);
1055     SDNode *N = Op.getNode();
1056     LoadSDNode *LD = cast<LoadSDNode>(N);
1057     EVT MemVT = LD->getMemoryVT();
1058     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1059       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1060                                                   : ISD::EXTLOAD)
1061       : LD->getExtensionType();
1062     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1063                                    LD->getChain(), LD->getBasePtr(),
1064                                    MemVT, LD->getMemOperand());
1065     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1066
1067     DEBUG(dbgs() << "\nPromoting ";
1068           N->dump(&DAG);
1069           dbgs() << "\nTo: ";
1070           Result.getNode()->dump(&DAG);
1071           dbgs() << '\n');
1072     WorkListRemover DeadNodes(*this);
1073     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1074     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1075     removeFromWorkList(N);
1076     DAG.DeleteNode(N);
1077     AddToWorkList(Result.getNode());
1078     return true;
1079   }
1080   return false;
1081 }
1082
1083
1084 //===----------------------------------------------------------------------===//
1085 //  Main DAG Combiner implementation
1086 //===----------------------------------------------------------------------===//
1087
1088 void DAGCombiner::Run(CombineLevel AtLevel) {
1089   // set the instance variables, so that the various visit routines may use it.
1090   Level = AtLevel;
1091   LegalOperations = Level >= AfterLegalizeVectorOps;
1092   LegalTypes = Level >= AfterLegalizeTypes;
1093
1094   // Add all the dag nodes to the worklist.
1095   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1096        E = DAG.allnodes_end(); I != E; ++I)
1097     AddToWorkList(I);
1098
1099   // Create a dummy node (which is not added to allnodes), that adds a reference
1100   // to the root node, preventing it from being deleted, and tracking any
1101   // changes of the root.
1102   HandleSDNode Dummy(DAG.getRoot());
1103
1104   // The root of the dag may dangle to deleted nodes until the dag combiner is
1105   // done.  Set it to null to avoid confusion.
1106   DAG.setRoot(SDValue());
1107
1108   // while the worklist isn't empty, find a node and
1109   // try and combine it.
1110   while (!WorkListContents.empty()) {
1111     SDNode *N;
1112     // The WorkListOrder holds the SDNodes in order, but it may contain
1113     // duplicates.
1114     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1115     // worklist *should* contain, and check the node we want to visit is should
1116     // actually be visited.
1117     do {
1118       N = WorkListOrder.pop_back_val();
1119     } while (!WorkListContents.erase(N));
1120
1121     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1122     // N is deleted from the DAG, since they too may now be dead or may have a
1123     // reduced number of uses, allowing other xforms.
1124     if (N->use_empty() && N != &Dummy) {
1125       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1126         AddToWorkList(N->getOperand(i).getNode());
1127
1128       DAG.DeleteNode(N);
1129       continue;
1130     }
1131
1132     SDValue RV = combine(N);
1133
1134     if (RV.getNode() == 0)
1135       continue;
1136
1137     ++NodesCombined;
1138
1139     // If we get back the same node we passed in, rather than a new node or
1140     // zero, we know that the node must have defined multiple values and
1141     // CombineTo was used.  Since CombineTo takes care of the worklist
1142     // mechanics for us, we have no work to do in this case.
1143     if (RV.getNode() == N)
1144       continue;
1145
1146     assert(N->getOpcode() != ISD::DELETED_NODE &&
1147            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1148            "Node was deleted but visit returned new node!");
1149
1150     DEBUG(dbgs() << "\nReplacing.3 ";
1151           N->dump(&DAG);
1152           dbgs() << "\nWith: ";
1153           RV.getNode()->dump(&DAG);
1154           dbgs() << '\n');
1155
1156     // Transfer debug value.
1157     DAG.TransferDbgValues(SDValue(N, 0), RV);
1158     WorkListRemover DeadNodes(*this);
1159     if (N->getNumValues() == RV.getNode()->getNumValues())
1160       DAG.ReplaceAllUsesWith(N, RV.getNode());
1161     else {
1162       assert(N->getValueType(0) == RV.getValueType() &&
1163              N->getNumValues() == 1 && "Type mismatch");
1164       SDValue OpV = RV;
1165       DAG.ReplaceAllUsesWith(N, &OpV);
1166     }
1167
1168     // Push the new node and any users onto the worklist
1169     AddToWorkList(RV.getNode());
1170     AddUsersToWorkList(RV.getNode());
1171
1172     // Add any uses of the old node to the worklist in case this node is the
1173     // last one that uses them.  They may become dead after this node is
1174     // deleted.
1175     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1176       AddToWorkList(N->getOperand(i).getNode());
1177
1178     // Finally, if the node is now dead, remove it from the graph.  The node
1179     // may not be dead if the replacement process recursively simplified to
1180     // something else needing this node.
1181     if (N->use_empty()) {
1182       // Nodes can be reintroduced into the worklist.  Make sure we do not
1183       // process a node that has been replaced.
1184       removeFromWorkList(N);
1185
1186       // Finally, since the node is now dead, remove it from the graph.
1187       DAG.DeleteNode(N);
1188     }
1189   }
1190
1191   // If the root changed (e.g. it was a dead load, update the root).
1192   DAG.setRoot(Dummy.getValue());
1193   DAG.RemoveDeadNodes();
1194 }
1195
1196 SDValue DAGCombiner::visit(SDNode *N) {
1197   switch (N->getOpcode()) {
1198   default: break;
1199   case ISD::TokenFactor:        return visitTokenFactor(N);
1200   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1201   case ISD::ADD:                return visitADD(N);
1202   case ISD::SUB:                return visitSUB(N);
1203   case ISD::ADDC:               return visitADDC(N);
1204   case ISD::SUBC:               return visitSUBC(N);
1205   case ISD::ADDE:               return visitADDE(N);
1206   case ISD::SUBE:               return visitSUBE(N);
1207   case ISD::MUL:                return visitMUL(N);
1208   case ISD::SDIV:               return visitSDIV(N);
1209   case ISD::UDIV:               return visitUDIV(N);
1210   case ISD::SREM:               return visitSREM(N);
1211   case ISD::UREM:               return visitUREM(N);
1212   case ISD::MULHU:              return visitMULHU(N);
1213   case ISD::MULHS:              return visitMULHS(N);
1214   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1215   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1216   case ISD::SMULO:              return visitSMULO(N);
1217   case ISD::UMULO:              return visitUMULO(N);
1218   case ISD::SDIVREM:            return visitSDIVREM(N);
1219   case ISD::UDIVREM:            return visitUDIVREM(N);
1220   case ISD::AND:                return visitAND(N);
1221   case ISD::OR:                 return visitOR(N);
1222   case ISD::XOR:                return visitXOR(N);
1223   case ISD::SHL:                return visitSHL(N);
1224   case ISD::SRA:                return visitSRA(N);
1225   case ISD::SRL:                return visitSRL(N);
1226   case ISD::ROTR:
1227   case ISD::ROTL:               return visitRotate(N);
1228   case ISD::CTLZ:               return visitCTLZ(N);
1229   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1230   case ISD::CTTZ:               return visitCTTZ(N);
1231   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1232   case ISD::CTPOP:              return visitCTPOP(N);
1233   case ISD::SELECT:             return visitSELECT(N);
1234   case ISD::VSELECT:            return visitVSELECT(N);
1235   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1236   case ISD::SETCC:              return visitSETCC(N);
1237   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1238   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1239   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1240   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1241   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1242   case ISD::BITCAST:            return visitBITCAST(N);
1243   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1244   case ISD::FADD:               return visitFADD(N);
1245   case ISD::FSUB:               return visitFSUB(N);
1246   case ISD::FMUL:               return visitFMUL(N);
1247   case ISD::FMA:                return visitFMA(N);
1248   case ISD::FDIV:               return visitFDIV(N);
1249   case ISD::FREM:               return visitFREM(N);
1250   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1251   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1252   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1253   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1254   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1255   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1256   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1257   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1258   case ISD::FNEG:               return visitFNEG(N);
1259   case ISD::FABS:               return visitFABS(N);
1260   case ISD::FFLOOR:             return visitFFLOOR(N);
1261   case ISD::FCEIL:              return visitFCEIL(N);
1262   case ISD::FTRUNC:             return visitFTRUNC(N);
1263   case ISD::BRCOND:             return visitBRCOND(N);
1264   case ISD::BR_CC:              return visitBR_CC(N);
1265   case ISD::LOAD:               return visitLOAD(N);
1266   case ISD::STORE:              return visitSTORE(N);
1267   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1268   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1269   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1270   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1271   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1272   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1273   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1274   }
1275   return SDValue();
1276 }
1277
1278 SDValue DAGCombiner::combine(SDNode *N) {
1279   SDValue RV = visit(N);
1280
1281   // If nothing happened, try a target-specific DAG combine.
1282   if (RV.getNode() == 0) {
1283     assert(N->getOpcode() != ISD::DELETED_NODE &&
1284            "Node was deleted but visit returned NULL!");
1285
1286     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1287         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1288
1289       // Expose the DAG combiner to the target combiner impls.
1290       TargetLowering::DAGCombinerInfo
1291         DagCombineInfo(DAG, Level, false, this);
1292
1293       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1294     }
1295   }
1296
1297   // If nothing happened still, try promoting the operation.
1298   if (RV.getNode() == 0) {
1299     switch (N->getOpcode()) {
1300     default: break;
1301     case ISD::ADD:
1302     case ISD::SUB:
1303     case ISD::MUL:
1304     case ISD::AND:
1305     case ISD::OR:
1306     case ISD::XOR:
1307       RV = PromoteIntBinOp(SDValue(N, 0));
1308       break;
1309     case ISD::SHL:
1310     case ISD::SRA:
1311     case ISD::SRL:
1312       RV = PromoteIntShiftOp(SDValue(N, 0));
1313       break;
1314     case ISD::SIGN_EXTEND:
1315     case ISD::ZERO_EXTEND:
1316     case ISD::ANY_EXTEND:
1317       RV = PromoteExtend(SDValue(N, 0));
1318       break;
1319     case ISD::LOAD:
1320       if (PromoteLoad(SDValue(N, 0)))
1321         RV = SDValue(N, 0);
1322       break;
1323     }
1324   }
1325
1326   // If N is a commutative binary node, try commuting it to enable more
1327   // sdisel CSE.
1328   if (RV.getNode() == 0 &&
1329       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1330       N->getNumValues() == 1) {
1331     SDValue N0 = N->getOperand(0);
1332     SDValue N1 = N->getOperand(1);
1333
1334     // Constant operands are canonicalized to RHS.
1335     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1336       SDValue Ops[] = { N1, N0 };
1337       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1338                                             Ops, 2);
1339       if (CSENode)
1340         return SDValue(CSENode, 0);
1341     }
1342   }
1343
1344   return RV;
1345 }
1346
1347 /// getInputChainForNode - Given a node, return its input chain if it has one,
1348 /// otherwise return a null sd operand.
1349 static SDValue getInputChainForNode(SDNode *N) {
1350   if (unsigned NumOps = N->getNumOperands()) {
1351     if (N->getOperand(0).getValueType() == MVT::Other)
1352       return N->getOperand(0);
1353     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1354       return N->getOperand(NumOps-1);
1355     for (unsigned i = 1; i < NumOps-1; ++i)
1356       if (N->getOperand(i).getValueType() == MVT::Other)
1357         return N->getOperand(i);
1358   }
1359   return SDValue();
1360 }
1361
1362 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1363   // If N has two operands, where one has an input chain equal to the other,
1364   // the 'other' chain is redundant.
1365   if (N->getNumOperands() == 2) {
1366     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1367       return N->getOperand(0);
1368     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1369       return N->getOperand(1);
1370   }
1371
1372   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1373   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1374   SmallPtrSet<SDNode*, 16> SeenOps;
1375   bool Changed = false;             // If we should replace this token factor.
1376
1377   // Start out with this token factor.
1378   TFs.push_back(N);
1379
1380   // Iterate through token factors.  The TFs grows when new token factors are
1381   // encountered.
1382   for (unsigned i = 0; i < TFs.size(); ++i) {
1383     SDNode *TF = TFs[i];
1384
1385     // Check each of the operands.
1386     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1387       SDValue Op = TF->getOperand(i);
1388
1389       switch (Op.getOpcode()) {
1390       case ISD::EntryToken:
1391         // Entry tokens don't need to be added to the list. They are
1392         // rededundant.
1393         Changed = true;
1394         break;
1395
1396       case ISD::TokenFactor:
1397         if (Op.hasOneUse() &&
1398             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1399           // Queue up for processing.
1400           TFs.push_back(Op.getNode());
1401           // Clean up in case the token factor is removed.
1402           AddToWorkList(Op.getNode());
1403           Changed = true;
1404           break;
1405         }
1406         // Fall thru
1407
1408       default:
1409         // Only add if it isn't already in the list.
1410         if (SeenOps.insert(Op.getNode()))
1411           Ops.push_back(Op);
1412         else
1413           Changed = true;
1414         break;
1415       }
1416     }
1417   }
1418
1419   SDValue Result;
1420
1421   // If we've change things around then replace token factor.
1422   if (Changed) {
1423     if (Ops.empty()) {
1424       // The entry token is the only possible outcome.
1425       Result = DAG.getEntryNode();
1426     } else {
1427       // New and improved token factor.
1428       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1429                            MVT::Other, &Ops[0], Ops.size());
1430     }
1431
1432     // Don't add users to work list.
1433     return CombineTo(N, Result, false);
1434   }
1435
1436   return Result;
1437 }
1438
1439 /// MERGE_VALUES can always be eliminated.
1440 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1441   WorkListRemover DeadNodes(*this);
1442   // Replacing results may cause a different MERGE_VALUES to suddenly
1443   // be CSE'd with N, and carry its uses with it. Iterate until no
1444   // uses remain, to ensure that the node can be safely deleted.
1445   // First add the users of this node to the work list so that they
1446   // can be tried again once they have new operands.
1447   AddUsersToWorkList(N);
1448   do {
1449     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1450       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1451   } while (!N->use_empty());
1452   removeFromWorkList(N);
1453   DAG.DeleteNode(N);
1454   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1455 }
1456
1457 static
1458 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1459                               SelectionDAG &DAG) {
1460   EVT VT = N0.getValueType();
1461   SDValue N00 = N0.getOperand(0);
1462   SDValue N01 = N0.getOperand(1);
1463   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1464
1465   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1466       isa<ConstantSDNode>(N00.getOperand(1))) {
1467     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1468     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1469                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1470                                  N00.getOperand(0), N01),
1471                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1472                                  N00.getOperand(1), N01));
1473     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1474   }
1475
1476   return SDValue();
1477 }
1478
1479 SDValue DAGCombiner::visitADD(SDNode *N) {
1480   SDValue N0 = N->getOperand(0);
1481   SDValue N1 = N->getOperand(1);
1482   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1483   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1484   EVT VT = N0.getValueType();
1485
1486   // fold vector ops
1487   if (VT.isVector()) {
1488     SDValue FoldedVOp = SimplifyVBinOp(N);
1489     if (FoldedVOp.getNode()) return FoldedVOp;
1490
1491     // fold (add x, 0) -> x, vector edition
1492     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1493       return N0;
1494     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1495       return N1;
1496   }
1497
1498   // fold (add x, undef) -> undef
1499   if (N0.getOpcode() == ISD::UNDEF)
1500     return N0;
1501   if (N1.getOpcode() == ISD::UNDEF)
1502     return N1;
1503   // fold (add c1, c2) -> c1+c2
1504   if (N0C && N1C)
1505     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1506   // canonicalize constant to RHS
1507   if (N0C && !N1C)
1508     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1509   // fold (add x, 0) -> x
1510   if (N1C && N1C->isNullValue())
1511     return N0;
1512   // fold (add Sym, c) -> Sym+c
1513   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1514     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1515         GA->getOpcode() == ISD::GlobalAddress)
1516       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1517                                   GA->getOffset() +
1518                                     (uint64_t)N1C->getSExtValue());
1519   // fold ((c1-A)+c2) -> (c1+c2)-A
1520   if (N1C && N0.getOpcode() == ISD::SUB)
1521     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1522       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1523                          DAG.getConstant(N1C->getAPIntValue()+
1524                                          N0C->getAPIntValue(), VT),
1525                          N0.getOperand(1));
1526   // reassociate add
1527   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1528   if (RADD.getNode() != 0)
1529     return RADD;
1530   // fold ((0-A) + B) -> B-A
1531   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1532       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1533     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1534   // fold (A + (0-B)) -> A-B
1535   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1536       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1537     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1538   // fold (A+(B-A)) -> B
1539   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1540     return N1.getOperand(0);
1541   // fold ((B-A)+A) -> B
1542   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1543     return N0.getOperand(0);
1544   // fold (A+(B-(A+C))) to (B-C)
1545   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1546       N0 == N1.getOperand(1).getOperand(0))
1547     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1548                        N1.getOperand(1).getOperand(1));
1549   // fold (A+(B-(C+A))) to (B-C)
1550   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1551       N0 == N1.getOperand(1).getOperand(1))
1552     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1553                        N1.getOperand(1).getOperand(0));
1554   // fold (A+((B-A)+or-C)) to (B+or-C)
1555   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1556       N1.getOperand(0).getOpcode() == ISD::SUB &&
1557       N0 == N1.getOperand(0).getOperand(1))
1558     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1559                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1560
1561   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1562   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1563     SDValue N00 = N0.getOperand(0);
1564     SDValue N01 = N0.getOperand(1);
1565     SDValue N10 = N1.getOperand(0);
1566     SDValue N11 = N1.getOperand(1);
1567
1568     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1569       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1570                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1571                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1572   }
1573
1574   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1575     return SDValue(N, 0);
1576
1577   // fold (a+b) -> (a|b) iff a and b share no bits.
1578   if (VT.isInteger() && !VT.isVector()) {
1579     APInt LHSZero, LHSOne;
1580     APInt RHSZero, RHSOne;
1581     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1582
1583     if (LHSZero.getBoolValue()) {
1584       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1585
1586       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1587       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1588       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1589         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1590           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1591       }
1592     }
1593   }
1594
1595   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1596   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1597     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1598     if (Result.getNode()) return Result;
1599   }
1600   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1601     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1602     if (Result.getNode()) return Result;
1603   }
1604
1605   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1606   if (N1.getOpcode() == ISD::SHL &&
1607       N1.getOperand(0).getOpcode() == ISD::SUB)
1608     if (ConstantSDNode *C =
1609           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1610       if (C->getAPIntValue() == 0)
1611         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1612                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1613                                        N1.getOperand(0).getOperand(1),
1614                                        N1.getOperand(1)));
1615   if (N0.getOpcode() == ISD::SHL &&
1616       N0.getOperand(0).getOpcode() == ISD::SUB)
1617     if (ConstantSDNode *C =
1618           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1619       if (C->getAPIntValue() == 0)
1620         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1621                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1622                                        N0.getOperand(0).getOperand(1),
1623                                        N0.getOperand(1)));
1624
1625   if (N1.getOpcode() == ISD::AND) {
1626     SDValue AndOp0 = N1.getOperand(0);
1627     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1628     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1629     unsigned DestBits = VT.getScalarType().getSizeInBits();
1630
1631     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1632     // and similar xforms where the inner op is either ~0 or 0.
1633     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1634       SDLoc DL(N);
1635       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1636     }
1637   }
1638
1639   // add (sext i1), X -> sub X, (zext i1)
1640   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1641       N0.getOperand(0).getValueType() == MVT::i1 &&
1642       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1643     SDLoc DL(N);
1644     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1645     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1646   }
1647
1648   return SDValue();
1649 }
1650
1651 SDValue DAGCombiner::visitADDC(SDNode *N) {
1652   SDValue N0 = N->getOperand(0);
1653   SDValue N1 = N->getOperand(1);
1654   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1655   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1656   EVT VT = N0.getValueType();
1657
1658   // If the flag result is dead, turn this into an ADD.
1659   if (!N->hasAnyUseOfValue(1))
1660     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1661                      DAG.getNode(ISD::CARRY_FALSE,
1662                                  SDLoc(N), MVT::Glue));
1663
1664   // canonicalize constant to RHS.
1665   if (N0C && !N1C)
1666     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1667
1668   // fold (addc x, 0) -> x + no carry out
1669   if (N1C && N1C->isNullValue())
1670     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1671                                         SDLoc(N), MVT::Glue));
1672
1673   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1674   APInt LHSZero, LHSOne;
1675   APInt RHSZero, RHSOne;
1676   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1677
1678   if (LHSZero.getBoolValue()) {
1679     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1680
1681     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1682     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1683     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1684       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1685                        DAG.getNode(ISD::CARRY_FALSE,
1686                                    SDLoc(N), MVT::Glue));
1687   }
1688
1689   return SDValue();
1690 }
1691
1692 SDValue DAGCombiner::visitADDE(SDNode *N) {
1693   SDValue N0 = N->getOperand(0);
1694   SDValue N1 = N->getOperand(1);
1695   SDValue CarryIn = N->getOperand(2);
1696   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1697   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1698
1699   // canonicalize constant to RHS
1700   if (N0C && !N1C)
1701     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1702                        N1, N0, CarryIn);
1703
1704   // fold (adde x, y, false) -> (addc x, y)
1705   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1706     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1707
1708   return SDValue();
1709 }
1710
1711 // Since it may not be valid to emit a fold to zero for vector initializers
1712 // check if we can before folding.
1713 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1714                              SelectionDAG &DAG,
1715                              bool LegalOperations, bool LegalTypes) {
1716   if (!VT.isVector())
1717     return DAG.getConstant(0, VT);
1718   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1719     return DAG.getConstant(0, VT);
1720   return SDValue();
1721 }
1722
1723 SDValue DAGCombiner::visitSUB(SDNode *N) {
1724   SDValue N0 = N->getOperand(0);
1725   SDValue N1 = N->getOperand(1);
1726   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1727   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1728   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1729     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1730   EVT VT = N0.getValueType();
1731
1732   // fold vector ops
1733   if (VT.isVector()) {
1734     SDValue FoldedVOp = SimplifyVBinOp(N);
1735     if (FoldedVOp.getNode()) return FoldedVOp;
1736
1737     // fold (sub x, 0) -> x, vector edition
1738     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1739       return N0;
1740   }
1741
1742   // fold (sub x, x) -> 0
1743   // FIXME: Refactor this and xor and other similar operations together.
1744   if (N0 == N1)
1745     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1746   // fold (sub c1, c2) -> c1-c2
1747   if (N0C && N1C)
1748     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1749   // fold (sub x, c) -> (add x, -c)
1750   if (N1C)
1751     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1752                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1753   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1754   if (N0C && N0C->isAllOnesValue())
1755     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1756   // fold A-(A-B) -> B
1757   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1758     return N1.getOperand(1);
1759   // fold (A+B)-A -> B
1760   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1761     return N0.getOperand(1);
1762   // fold (A+B)-B -> A
1763   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1764     return N0.getOperand(0);
1765   // fold C2-(A+C1) -> (C2-C1)-A
1766   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1767     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1768                                    VT);
1769     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1770                        N1.getOperand(0));
1771   }
1772   // fold ((A+(B+or-C))-B) -> A+or-C
1773   if (N0.getOpcode() == ISD::ADD &&
1774       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1775        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1776       N0.getOperand(1).getOperand(0) == N1)
1777     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1778                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1779   // fold ((A+(C+B))-B) -> A+C
1780   if (N0.getOpcode() == ISD::ADD &&
1781       N0.getOperand(1).getOpcode() == ISD::ADD &&
1782       N0.getOperand(1).getOperand(1) == N1)
1783     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1784                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1785   // fold ((A-(B-C))-C) -> A-B
1786   if (N0.getOpcode() == ISD::SUB &&
1787       N0.getOperand(1).getOpcode() == ISD::SUB &&
1788       N0.getOperand(1).getOperand(1) == N1)
1789     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1790                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1791
1792   // If either operand of a sub is undef, the result is undef
1793   if (N0.getOpcode() == ISD::UNDEF)
1794     return N0;
1795   if (N1.getOpcode() == ISD::UNDEF)
1796     return N1;
1797
1798   // If the relocation model supports it, consider symbol offsets.
1799   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1800     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1801       // fold (sub Sym, c) -> Sym-c
1802       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1803         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1804                                     GA->getOffset() -
1805                                       (uint64_t)N1C->getSExtValue());
1806       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1807       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1808         if (GA->getGlobal() == GB->getGlobal())
1809           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1810                                  VT);
1811     }
1812
1813   return SDValue();
1814 }
1815
1816 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1817   SDValue N0 = N->getOperand(0);
1818   SDValue N1 = N->getOperand(1);
1819   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1820   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1821   EVT VT = N0.getValueType();
1822
1823   // If the flag result is dead, turn this into an SUB.
1824   if (!N->hasAnyUseOfValue(1))
1825     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1826                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1827                                  MVT::Glue));
1828
1829   // fold (subc x, x) -> 0 + no borrow
1830   if (N0 == N1)
1831     return CombineTo(N, DAG.getConstant(0, VT),
1832                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1833                                  MVT::Glue));
1834
1835   // fold (subc x, 0) -> x + no borrow
1836   if (N1C && N1C->isNullValue())
1837     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1838                                         MVT::Glue));
1839
1840   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1841   if (N0C && N0C->isAllOnesValue())
1842     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1843                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1844                                  MVT::Glue));
1845
1846   return SDValue();
1847 }
1848
1849 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1850   SDValue N0 = N->getOperand(0);
1851   SDValue N1 = N->getOperand(1);
1852   SDValue CarryIn = N->getOperand(2);
1853
1854   // fold (sube x, y, false) -> (subc x, y)
1855   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1856     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1857
1858   return SDValue();
1859 }
1860
1861 SDValue DAGCombiner::visitMUL(SDNode *N) {
1862   SDValue N0 = N->getOperand(0);
1863   SDValue N1 = N->getOperand(1);
1864   EVT VT = N0.getValueType();
1865
1866   // fold (mul x, undef) -> 0
1867   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1868     return DAG.getConstant(0, VT);
1869
1870   bool N0IsConst = false;
1871   bool N1IsConst = false;
1872   APInt ConstValue0, ConstValue1;
1873   // fold vector ops
1874   if (VT.isVector()) {
1875     SDValue FoldedVOp = SimplifyVBinOp(N);
1876     if (FoldedVOp.getNode()) return FoldedVOp;
1877
1878     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1879     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1880   } else {
1881     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1882     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1883                             : APInt();
1884     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1885     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1886                             : APInt();
1887   }
1888
1889   // fold (mul c1, c2) -> c1*c2
1890   if (N0IsConst && N1IsConst)
1891     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1892
1893   // canonicalize constant to RHS
1894   if (N0IsConst && !N1IsConst)
1895     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1896   // fold (mul x, 0) -> 0
1897   if (N1IsConst && ConstValue1 == 0)
1898     return N1;
1899   // We require a splat of the entire scalar bit width for non-contiguous
1900   // bit patterns.
1901   bool IsFullSplat =
1902     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1903   // fold (mul x, 1) -> x
1904   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1905     return N0;
1906   // fold (mul x, -1) -> 0-x
1907   if (N1IsConst && ConstValue1.isAllOnesValue())
1908     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1909                        DAG.getConstant(0, VT), N0);
1910   // fold (mul x, (1 << c)) -> x << c
1911   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1912     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1913                        DAG.getConstant(ConstValue1.logBase2(),
1914                                        getShiftAmountTy(N0.getValueType())));
1915   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1916   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1917     unsigned Log2Val = (-ConstValue1).logBase2();
1918     // FIXME: If the input is something that is easily negated (e.g. a
1919     // single-use add), we should put the negate there.
1920     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1921                        DAG.getConstant(0, VT),
1922                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1923                             DAG.getConstant(Log2Val,
1924                                       getShiftAmountTy(N0.getValueType()))));
1925   }
1926
1927   APInt Val;
1928   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1929   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1930       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1932     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1933                              N1, N0.getOperand(1));
1934     AddToWorkList(C3.getNode());
1935     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1936                        N0.getOperand(0), C3);
1937   }
1938
1939   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1940   // use.
1941   {
1942     SDValue Sh(0,0), Y(0,0);
1943     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1944     if (N0.getOpcode() == ISD::SHL &&
1945         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1946                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1947         N0.getNode()->hasOneUse()) {
1948       Sh = N0; Y = N1;
1949     } else if (N1.getOpcode() == ISD::SHL &&
1950                isa<ConstantSDNode>(N1.getOperand(1)) &&
1951                N1.getNode()->hasOneUse()) {
1952       Sh = N1; Y = N0;
1953     }
1954
1955     if (Sh.getNode()) {
1956       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1957                                 Sh.getOperand(0), Y);
1958       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1959                          Mul, Sh.getOperand(1));
1960     }
1961   }
1962
1963   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1964   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1965       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1966                      isa<ConstantSDNode>(N0.getOperand(1))))
1967     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1968                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1969                                    N0.getOperand(0), N1),
1970                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1971                                    N0.getOperand(1), N1));
1972
1973   // reassociate mul
1974   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1975   if (RMUL.getNode() != 0)
1976     return RMUL;
1977
1978   return SDValue();
1979 }
1980
1981 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1982   SDValue N0 = N->getOperand(0);
1983   SDValue N1 = N->getOperand(1);
1984   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1985   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1986   EVT VT = N->getValueType(0);
1987
1988   // fold vector ops
1989   if (VT.isVector()) {
1990     SDValue FoldedVOp = SimplifyVBinOp(N);
1991     if (FoldedVOp.getNode()) return FoldedVOp;
1992   }
1993
1994   // fold (sdiv c1, c2) -> c1/c2
1995   if (N0C && N1C && !N1C->isNullValue())
1996     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1997   // fold (sdiv X, 1) -> X
1998   if (N1C && N1C->getAPIntValue() == 1LL)
1999     return N0;
2000   // fold (sdiv X, -1) -> 0-X
2001   if (N1C && N1C->isAllOnesValue())
2002     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2003                        DAG.getConstant(0, VT), N0);
2004   // If we know the sign bits of both operands are zero, strength reduce to a
2005   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2006   if (!VT.isVector()) {
2007     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2008       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2009                          N0, N1);
2010   }
2011   // fold (sdiv X, pow2) -> simple ops after legalize
2012   if (N1C && !N1C->isNullValue() &&
2013       (N1C->getAPIntValue().isPowerOf2() ||
2014        (-N1C->getAPIntValue()).isPowerOf2())) {
2015     // If dividing by powers of two is cheap, then don't perform the following
2016     // fold.
2017     if (TLI.isPow2DivCheap())
2018       return SDValue();
2019
2020     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2021
2022     // Splat the sign bit into the register
2023     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2024                               DAG.getConstant(VT.getSizeInBits()-1,
2025                                        getShiftAmountTy(N0.getValueType())));
2026     AddToWorkList(SGN.getNode());
2027
2028     // Add (N0 < 0) ? abs2 - 1 : 0;
2029     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2030                               DAG.getConstant(VT.getSizeInBits() - lg2,
2031                                        getShiftAmountTy(SGN.getValueType())));
2032     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2033     AddToWorkList(SRL.getNode());
2034     AddToWorkList(ADD.getNode());    // Divide by pow2
2035     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2036                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2037
2038     // If we're dividing by a positive value, we're done.  Otherwise, we must
2039     // negate the result.
2040     if (N1C->getAPIntValue().isNonNegative())
2041       return SRA;
2042
2043     AddToWorkList(SRA.getNode());
2044     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2045                        DAG.getConstant(0, VT), SRA);
2046   }
2047
2048   // if integer divide is expensive and we satisfy the requirements, emit an
2049   // alternate sequence.
2050   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2051     SDValue Op = BuildSDIV(N);
2052     if (Op.getNode()) return Op;
2053   }
2054
2055   // undef / X -> 0
2056   if (N0.getOpcode() == ISD::UNDEF)
2057     return DAG.getConstant(0, VT);
2058   // X / undef -> undef
2059   if (N1.getOpcode() == ISD::UNDEF)
2060     return N1;
2061
2062   return SDValue();
2063 }
2064
2065 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2066   SDValue N0 = N->getOperand(0);
2067   SDValue N1 = N->getOperand(1);
2068   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2069   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2070   EVT VT = N->getValueType(0);
2071
2072   // fold vector ops
2073   if (VT.isVector()) {
2074     SDValue FoldedVOp = SimplifyVBinOp(N);
2075     if (FoldedVOp.getNode()) return FoldedVOp;
2076   }
2077
2078   // fold (udiv c1, c2) -> c1/c2
2079   if (N0C && N1C && !N1C->isNullValue())
2080     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2081   // fold (udiv x, (1 << c)) -> x >>u c
2082   if (N1C && N1C->getAPIntValue().isPowerOf2())
2083     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2084                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2085                                        getShiftAmountTy(N0.getValueType())));
2086   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2087   if (N1.getOpcode() == ISD::SHL) {
2088     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2089       if (SHC->getAPIntValue().isPowerOf2()) {
2090         EVT ADDVT = N1.getOperand(1).getValueType();
2091         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2092                                   N1.getOperand(1),
2093                                   DAG.getConstant(SHC->getAPIntValue()
2094                                                                   .logBase2(),
2095                                                   ADDVT));
2096         AddToWorkList(Add.getNode());
2097         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2098       }
2099     }
2100   }
2101   // fold (udiv x, c) -> alternate
2102   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2103     SDValue Op = BuildUDIV(N);
2104     if (Op.getNode()) return Op;
2105   }
2106
2107   // undef / X -> 0
2108   if (N0.getOpcode() == ISD::UNDEF)
2109     return DAG.getConstant(0, VT);
2110   // X / undef -> undef
2111   if (N1.getOpcode() == ISD::UNDEF)
2112     return N1;
2113
2114   return SDValue();
2115 }
2116
2117 SDValue DAGCombiner::visitSREM(SDNode *N) {
2118   SDValue N0 = N->getOperand(0);
2119   SDValue N1 = N->getOperand(1);
2120   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2121   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2122   EVT VT = N->getValueType(0);
2123
2124   // fold (srem c1, c2) -> c1%c2
2125   if (N0C && N1C && !N1C->isNullValue())
2126     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2127   // If we know the sign bits of both operands are zero, strength reduce to a
2128   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2129   if (!VT.isVector()) {
2130     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2131       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2132   }
2133
2134   // If X/C can be simplified by the division-by-constant logic, lower
2135   // X%C to the equivalent of X-X/C*C.
2136   if (N1C && !N1C->isNullValue()) {
2137     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2138     AddToWorkList(Div.getNode());
2139     SDValue OptimizedDiv = combine(Div.getNode());
2140     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2141       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2142                                 OptimizedDiv, N1);
2143       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2144       AddToWorkList(Mul.getNode());
2145       return Sub;
2146     }
2147   }
2148
2149   // undef % X -> 0
2150   if (N0.getOpcode() == ISD::UNDEF)
2151     return DAG.getConstant(0, VT);
2152   // X % undef -> undef
2153   if (N1.getOpcode() == ISD::UNDEF)
2154     return N1;
2155
2156   return SDValue();
2157 }
2158
2159 SDValue DAGCombiner::visitUREM(SDNode *N) {
2160   SDValue N0 = N->getOperand(0);
2161   SDValue N1 = N->getOperand(1);
2162   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2163   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2164   EVT VT = N->getValueType(0);
2165
2166   // fold (urem c1, c2) -> c1%c2
2167   if (N0C && N1C && !N1C->isNullValue())
2168     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2169   // fold (urem x, pow2) -> (and x, pow2-1)
2170   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2171     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2172                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2173   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2174   if (N1.getOpcode() == ISD::SHL) {
2175     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2176       if (SHC->getAPIntValue().isPowerOf2()) {
2177         SDValue Add =
2178           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2179                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2180                                  VT));
2181         AddToWorkList(Add.getNode());
2182         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2183       }
2184     }
2185   }
2186
2187   // If X/C can be simplified by the division-by-constant logic, lower
2188   // X%C to the equivalent of X-X/C*C.
2189   if (N1C && !N1C->isNullValue()) {
2190     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2191     AddToWorkList(Div.getNode());
2192     SDValue OptimizedDiv = combine(Div.getNode());
2193     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2194       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2195                                 OptimizedDiv, N1);
2196       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2197       AddToWorkList(Mul.getNode());
2198       return Sub;
2199     }
2200   }
2201
2202   // undef % X -> 0
2203   if (N0.getOpcode() == ISD::UNDEF)
2204     return DAG.getConstant(0, VT);
2205   // X % undef -> undef
2206   if (N1.getOpcode() == ISD::UNDEF)
2207     return N1;
2208
2209   return SDValue();
2210 }
2211
2212 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2213   SDValue N0 = N->getOperand(0);
2214   SDValue N1 = N->getOperand(1);
2215   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2216   EVT VT = N->getValueType(0);
2217   SDLoc DL(N);
2218
2219   // fold (mulhs x, 0) -> 0
2220   if (N1C && N1C->isNullValue())
2221     return N1;
2222   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2223   if (N1C && N1C->getAPIntValue() == 1)
2224     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2225                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2226                                        getShiftAmountTy(N0.getValueType())));
2227   // fold (mulhs x, undef) -> 0
2228   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2229     return DAG.getConstant(0, VT);
2230
2231   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2232   // plus a shift.
2233   if (VT.isSimple() && !VT.isVector()) {
2234     MVT Simple = VT.getSimpleVT();
2235     unsigned SimpleSize = Simple.getSizeInBits();
2236     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2237     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2238       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2239       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2240       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2241       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2242             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2243       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2244     }
2245   }
2246
2247   return SDValue();
2248 }
2249
2250 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2251   SDValue N0 = N->getOperand(0);
2252   SDValue N1 = N->getOperand(1);
2253   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2254   EVT VT = N->getValueType(0);
2255   SDLoc DL(N);
2256
2257   // fold (mulhu x, 0) -> 0
2258   if (N1C && N1C->isNullValue())
2259     return N1;
2260   // fold (mulhu x, 1) -> 0
2261   if (N1C && N1C->getAPIntValue() == 1)
2262     return DAG.getConstant(0, N0.getValueType());
2263   // fold (mulhu x, undef) -> 0
2264   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2265     return DAG.getConstant(0, VT);
2266
2267   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2268   // plus a shift.
2269   if (VT.isSimple() && !VT.isVector()) {
2270     MVT Simple = VT.getSimpleVT();
2271     unsigned SimpleSize = Simple.getSizeInBits();
2272     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2273     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2274       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2275       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2276       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2277       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2278             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2279       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2280     }
2281   }
2282
2283   return SDValue();
2284 }
2285
2286 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2287 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2288 /// that are being performed. Return true if a simplification was made.
2289 ///
2290 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2291                                                 unsigned HiOp) {
2292   // If the high half is not needed, just compute the low half.
2293   bool HiExists = N->hasAnyUseOfValue(1);
2294   if (!HiExists &&
2295       (!LegalOperations ||
2296        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2297     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2298                               N->op_begin(), N->getNumOperands());
2299     return CombineTo(N, Res, Res);
2300   }
2301
2302   // If the low half is not needed, just compute the high half.
2303   bool LoExists = N->hasAnyUseOfValue(0);
2304   if (!LoExists &&
2305       (!LegalOperations ||
2306        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2307     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2308                               N->op_begin(), N->getNumOperands());
2309     return CombineTo(N, Res, Res);
2310   }
2311
2312   // If both halves are used, return as it is.
2313   if (LoExists && HiExists)
2314     return SDValue();
2315
2316   // If the two computed results can be simplified separately, separate them.
2317   if (LoExists) {
2318     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2319                              N->op_begin(), N->getNumOperands());
2320     AddToWorkList(Lo.getNode());
2321     SDValue LoOpt = combine(Lo.getNode());
2322     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2323         (!LegalOperations ||
2324          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2325       return CombineTo(N, LoOpt, LoOpt);
2326   }
2327
2328   if (HiExists) {
2329     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2330                              N->op_begin(), N->getNumOperands());
2331     AddToWorkList(Hi.getNode());
2332     SDValue HiOpt = combine(Hi.getNode());
2333     if (HiOpt.getNode() && HiOpt != Hi &&
2334         (!LegalOperations ||
2335          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2336       return CombineTo(N, HiOpt, HiOpt);
2337   }
2338
2339   return SDValue();
2340 }
2341
2342 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2343   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2344   if (Res.getNode()) return Res;
2345
2346   EVT VT = N->getValueType(0);
2347   SDLoc DL(N);
2348
2349   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2350   // plus a shift.
2351   if (VT.isSimple() && !VT.isVector()) {
2352     MVT Simple = VT.getSimpleVT();
2353     unsigned SimpleSize = Simple.getSizeInBits();
2354     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2355     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2356       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2357       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2358       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2359       // Compute the high part as N1.
2360       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2361             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2362       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2363       // Compute the low part as N0.
2364       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2365       return CombineTo(N, Lo, Hi);
2366     }
2367   }
2368
2369   return SDValue();
2370 }
2371
2372 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2373   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2374   if (Res.getNode()) return Res;
2375
2376   EVT VT = N->getValueType(0);
2377   SDLoc DL(N);
2378
2379   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2380   // plus a shift.
2381   if (VT.isSimple() && !VT.isVector()) {
2382     MVT Simple = VT.getSimpleVT();
2383     unsigned SimpleSize = Simple.getSizeInBits();
2384     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2385     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2386       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2387       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2388       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2389       // Compute the high part as N1.
2390       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2391             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2392       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2393       // Compute the low part as N0.
2394       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2395       return CombineTo(N, Lo, Hi);
2396     }
2397   }
2398
2399   return SDValue();
2400 }
2401
2402 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2403   // (smulo x, 2) -> (saddo x, x)
2404   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2405     if (C2->getAPIntValue() == 2)
2406       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2407                          N->getOperand(0), N->getOperand(0));
2408
2409   return SDValue();
2410 }
2411
2412 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2413   // (umulo x, 2) -> (uaddo x, x)
2414   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2415     if (C2->getAPIntValue() == 2)
2416       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2417                          N->getOperand(0), N->getOperand(0));
2418
2419   return SDValue();
2420 }
2421
2422 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2423   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2424   if (Res.getNode()) return Res;
2425
2426   return SDValue();
2427 }
2428
2429 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2430   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2431   if (Res.getNode()) return Res;
2432
2433   return SDValue();
2434 }
2435
2436 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2437 /// two operands of the same opcode, try to simplify it.
2438 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2439   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2440   EVT VT = N0.getValueType();
2441   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2442
2443   // Bail early if none of these transforms apply.
2444   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2445
2446   // For each of OP in AND/OR/XOR:
2447   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2448   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2449   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2450   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2451   //
2452   // do not sink logical op inside of a vector extend, since it may combine
2453   // into a vsetcc.
2454   EVT Op0VT = N0.getOperand(0).getValueType();
2455   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2456        N0.getOpcode() == ISD::SIGN_EXTEND ||
2457        // Avoid infinite looping with PromoteIntBinOp.
2458        (N0.getOpcode() == ISD::ANY_EXTEND &&
2459         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2460        (N0.getOpcode() == ISD::TRUNCATE &&
2461         (!TLI.isZExtFree(VT, Op0VT) ||
2462          !TLI.isTruncateFree(Op0VT, VT)) &&
2463         TLI.isTypeLegal(Op0VT))) &&
2464       !VT.isVector() &&
2465       Op0VT == N1.getOperand(0).getValueType() &&
2466       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2467     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2468                                  N0.getOperand(0).getValueType(),
2469                                  N0.getOperand(0), N1.getOperand(0));
2470     AddToWorkList(ORNode.getNode());
2471     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2472   }
2473
2474   // For each of OP in SHL/SRL/SRA/AND...
2475   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2476   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2477   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2478   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2479        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2480       N0.getOperand(1) == N1.getOperand(1)) {
2481     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2482                                  N0.getOperand(0).getValueType(),
2483                                  N0.getOperand(0), N1.getOperand(0));
2484     AddToWorkList(ORNode.getNode());
2485     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2486                        ORNode, N0.getOperand(1));
2487   }
2488
2489   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2490   // Only perform this optimization after type legalization and before
2491   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2492   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2493   // we don't want to undo this promotion.
2494   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2495   // on scalars.
2496   if ((N0.getOpcode() == ISD::BITCAST ||
2497        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2498       Level == AfterLegalizeTypes) {
2499     SDValue In0 = N0.getOperand(0);
2500     SDValue In1 = N1.getOperand(0);
2501     EVT In0Ty = In0.getValueType();
2502     EVT In1Ty = In1.getValueType();
2503     SDLoc DL(N);
2504     // If both incoming values are integers, and the original types are the
2505     // same.
2506     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2507       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2508       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2509       AddToWorkList(Op.getNode());
2510       return BC;
2511     }
2512   }
2513
2514   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2515   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2516   // If both shuffles use the same mask, and both shuffle within a single
2517   // vector, then it is worthwhile to move the swizzle after the operation.
2518   // The type-legalizer generates this pattern when loading illegal
2519   // vector types from memory. In many cases this allows additional shuffle
2520   // optimizations.
2521   // There are other cases where moving the shuffle after the xor/and/or
2522   // is profitable even if shuffles don't perform a swizzle.
2523   // If both shuffles use the same mask, and both shuffles have the same first
2524   // or second operand, then it might still be profitable to move the shuffle
2525   // after the xor/and/or operation.
2526   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2527     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2528     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2529
2530     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2531            "Inputs to shuffles are not the same type");
2532  
2533     // Check that both shuffles use the same mask. The masks are known to be of
2534     // the same length because the result vector type is the same.
2535     // Check also that shuffles have only one use to avoid introducing extra
2536     // instructions.
2537     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2538         SVN0->getMask().equals(SVN1->getMask())) {
2539       SDValue ShOp = N0->getOperand(1);
2540
2541       // Don't try to fold this node if it requires introducing a
2542       // build vector of all zeros that might be illegal at this stage.
2543       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2544         if (!LegalTypes)
2545           ShOp = DAG.getConstant(0, VT);
2546         else
2547           ShOp = SDValue();
2548       }
2549
2550       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2551       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2552       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2553       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2554         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2555                                       N0->getOperand(0), N1->getOperand(0));
2556         AddToWorkList(NewNode.getNode());
2557         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2558                                     &SVN0->getMask()[0]);
2559       }
2560
2561       // Don't try to fold this node if it requires introducing a
2562       // build vector of all zeros that might be illegal at this stage.
2563       ShOp = N0->getOperand(0);
2564       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2565         if (!LegalTypes)
2566           ShOp = DAG.getConstant(0, VT);
2567         else
2568           ShOp = SDValue();
2569       }
2570
2571       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2572       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2573       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2574       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2575         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2576                                       N0->getOperand(1), N1->getOperand(1));
2577         AddToWorkList(NewNode.getNode());
2578         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2579                                     &SVN0->getMask()[0]);
2580       }
2581     }
2582   }
2583
2584   return SDValue();
2585 }
2586
2587 SDValue DAGCombiner::visitAND(SDNode *N) {
2588   SDValue N0 = N->getOperand(0);
2589   SDValue N1 = N->getOperand(1);
2590   SDValue LL, LR, RL, RR, CC0, CC1;
2591   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2592   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2593   EVT VT = N1.getValueType();
2594   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2595
2596   // fold vector ops
2597   if (VT.isVector()) {
2598     SDValue FoldedVOp = SimplifyVBinOp(N);
2599     if (FoldedVOp.getNode()) return FoldedVOp;
2600
2601     // fold (and x, 0) -> 0, vector edition
2602     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2603       return N0;
2604     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2605       return N1;
2606
2607     // fold (and x, -1) -> x, vector edition
2608     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2609       return N1;
2610     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2611       return N0;
2612   }
2613
2614   // fold (and x, undef) -> 0
2615   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2616     return DAG.getConstant(0, VT);
2617   // fold (and c1, c2) -> c1&c2
2618   if (N0C && N1C)
2619     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2620   // canonicalize constant to RHS
2621   if (N0C && !N1C)
2622     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2623   // fold (and x, -1) -> x
2624   if (N1C && N1C->isAllOnesValue())
2625     return N0;
2626   // if (and x, c) is known to be zero, return 0
2627   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2628                                    APInt::getAllOnesValue(BitWidth)))
2629     return DAG.getConstant(0, VT);
2630   // reassociate and
2631   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2632   if (RAND.getNode() != 0)
2633     return RAND;
2634   // fold (and (or x, C), D) -> D if (C & D) == D
2635   if (N1C && N0.getOpcode() == ISD::OR)
2636     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2637       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2638         return N1;
2639   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2640   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2641     SDValue N0Op0 = N0.getOperand(0);
2642     APInt Mask = ~N1C->getAPIntValue();
2643     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2644     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2645       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2646                                  N0.getValueType(), N0Op0);
2647
2648       // Replace uses of the AND with uses of the Zero extend node.
2649       CombineTo(N, Zext);
2650
2651       // We actually want to replace all uses of the any_extend with the
2652       // zero_extend, to avoid duplicating things.  This will later cause this
2653       // AND to be folded.
2654       CombineTo(N0.getNode(), Zext);
2655       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2656     }
2657   }
2658   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2659   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2660   // already be zero by virtue of the width of the base type of the load.
2661   //
2662   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2663   // more cases.
2664   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2665        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2666       N0.getOpcode() == ISD::LOAD) {
2667     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2668                                          N0 : N0.getOperand(0) );
2669
2670     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2671     // This can be a pure constant or a vector splat, in which case we treat the
2672     // vector as a scalar and use the splat value.
2673     APInt Constant = APInt::getNullValue(1);
2674     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2675       Constant = C->getAPIntValue();
2676     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2677       APInt SplatValue, SplatUndef;
2678       unsigned SplatBitSize;
2679       bool HasAnyUndefs;
2680       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2681                                              SplatBitSize, HasAnyUndefs);
2682       if (IsSplat) {
2683         // Undef bits can contribute to a possible optimisation if set, so
2684         // set them.
2685         SplatValue |= SplatUndef;
2686
2687         // The splat value may be something like "0x00FFFFFF", which means 0 for
2688         // the first vector value and FF for the rest, repeating. We need a mask
2689         // that will apply equally to all members of the vector, so AND all the
2690         // lanes of the constant together.
2691         EVT VT = Vector->getValueType(0);
2692         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2693
2694         // If the splat value has been compressed to a bitlength lower
2695         // than the size of the vector lane, we need to re-expand it to
2696         // the lane size.
2697         if (BitWidth > SplatBitSize)
2698           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2699                SplatBitSize < BitWidth;
2700                SplatBitSize = SplatBitSize * 2)
2701             SplatValue |= SplatValue.shl(SplatBitSize);
2702
2703         Constant = APInt::getAllOnesValue(BitWidth);
2704         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2705           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2706       }
2707     }
2708
2709     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2710     // actually legal and isn't going to get expanded, else this is a false
2711     // optimisation.
2712     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2713                                                     Load->getMemoryVT());
2714
2715     // Resize the constant to the same size as the original memory access before
2716     // extension. If it is still the AllOnesValue then this AND is completely
2717     // unneeded.
2718     Constant =
2719       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2720
2721     bool B;
2722     switch (Load->getExtensionType()) {
2723     default: B = false; break;
2724     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2725     case ISD::ZEXTLOAD:
2726     case ISD::NON_EXTLOAD: B = true; break;
2727     }
2728
2729     if (B && Constant.isAllOnesValue()) {
2730       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2731       // preserve semantics once we get rid of the AND.
2732       SDValue NewLoad(Load, 0);
2733       if (Load->getExtensionType() == ISD::EXTLOAD) {
2734         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2735                               Load->getValueType(0), SDLoc(Load),
2736                               Load->getChain(), Load->getBasePtr(),
2737                               Load->getOffset(), Load->getMemoryVT(),
2738                               Load->getMemOperand());
2739         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2740         if (Load->getNumValues() == 3) {
2741           // PRE/POST_INC loads have 3 values.
2742           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2743                            NewLoad.getValue(2) };
2744           CombineTo(Load, To, 3, true);
2745         } else {
2746           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2747         }
2748       }
2749
2750       // Fold the AND away, taking care not to fold to the old load node if we
2751       // replaced it.
2752       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2753
2754       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2755     }
2756   }
2757   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2758   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2759     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2760     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2761
2762     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2763         LL.getValueType().isInteger()) {
2764       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2765       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2766         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2767                                      LR.getValueType(), LL, RL);
2768         AddToWorkList(ORNode.getNode());
2769         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2770       }
2771       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2772       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2773         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2774                                       LR.getValueType(), LL, RL);
2775         AddToWorkList(ANDNode.getNode());
2776         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2777       }
2778       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2779       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2780         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2781                                      LR.getValueType(), LL, RL);
2782         AddToWorkList(ORNode.getNode());
2783         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2784       }
2785     }
2786     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2787     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2788         Op0 == Op1 && LL.getValueType().isInteger() &&
2789       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2790                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2791                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2792                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2793       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2794                                     LL, DAG.getConstant(1, LL.getValueType()));
2795       AddToWorkList(ADDNode.getNode());
2796       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2797                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2798     }
2799     // canonicalize equivalent to ll == rl
2800     if (LL == RR && LR == RL) {
2801       Op1 = ISD::getSetCCSwappedOperands(Op1);
2802       std::swap(RL, RR);
2803     }
2804     if (LL == RL && LR == RR) {
2805       bool isInteger = LL.getValueType().isInteger();
2806       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2807       if (Result != ISD::SETCC_INVALID &&
2808           (!LegalOperations ||
2809            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2810             TLI.isOperationLegal(ISD::SETCC,
2811                             getSetCCResultType(N0.getSimpleValueType())))))
2812         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2813                             LL, LR, Result);
2814     }
2815   }
2816
2817   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2818   if (N0.getOpcode() == N1.getOpcode()) {
2819     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2820     if (Tmp.getNode()) return Tmp;
2821   }
2822
2823   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2824   // fold (and (sra)) -> (and (srl)) when possible.
2825   if (!VT.isVector() &&
2826       SimplifyDemandedBits(SDValue(N, 0)))
2827     return SDValue(N, 0);
2828
2829   // fold (zext_inreg (extload x)) -> (zextload x)
2830   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2831     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2832     EVT MemVT = LN0->getMemoryVT();
2833     // If we zero all the possible extended bits, then we can turn this into
2834     // a zextload if we are running before legalize or the operation is legal.
2835     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2836     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2837                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2838         ((!LegalOperations && !LN0->isVolatile()) ||
2839          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2840       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2841                                        LN0->getChain(), LN0->getBasePtr(),
2842                                        MemVT, LN0->getMemOperand());
2843       AddToWorkList(N);
2844       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2845       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2846     }
2847   }
2848   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2849   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2850       N0.hasOneUse()) {
2851     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2852     EVT MemVT = LN0->getMemoryVT();
2853     // If we zero all the possible extended bits, then we can turn this into
2854     // a zextload if we are running before legalize or the operation is legal.
2855     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2856     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2857                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2858         ((!LegalOperations && !LN0->isVolatile()) ||
2859          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2860       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2861                                        LN0->getChain(), LN0->getBasePtr(),
2862                                        MemVT, LN0->getMemOperand());
2863       AddToWorkList(N);
2864       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2865       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2866     }
2867   }
2868
2869   // fold (and (load x), 255) -> (zextload x, i8)
2870   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2871   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2872   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2873               (N0.getOpcode() == ISD::ANY_EXTEND &&
2874                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2875     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2876     LoadSDNode *LN0 = HasAnyExt
2877       ? cast<LoadSDNode>(N0.getOperand(0))
2878       : cast<LoadSDNode>(N0);
2879     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2880         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2881       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2882       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2883         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2884         EVT LoadedVT = LN0->getMemoryVT();
2885
2886         if (ExtVT == LoadedVT &&
2887             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2888           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2889
2890           SDValue NewLoad =
2891             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2892                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2893                            LN0->getMemOperand());
2894           AddToWorkList(N);
2895           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2896           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2897         }
2898
2899         // Do not change the width of a volatile load.
2900         // Do not generate loads of non-round integer types since these can
2901         // be expensive (and would be wrong if the type is not byte sized).
2902         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2903             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2904           EVT PtrType = LN0->getOperand(1).getValueType();
2905
2906           unsigned Alignment = LN0->getAlignment();
2907           SDValue NewPtr = LN0->getBasePtr();
2908
2909           // For big endian targets, we need to add an offset to the pointer
2910           // to load the correct bytes.  For little endian systems, we merely
2911           // need to read fewer bytes from the same pointer.
2912           if (TLI.isBigEndian()) {
2913             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2914             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2915             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2916             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2917                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2918             Alignment = MinAlign(Alignment, PtrOff);
2919           }
2920
2921           AddToWorkList(NewPtr.getNode());
2922
2923           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2924           SDValue Load =
2925             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2926                            LN0->getChain(), NewPtr,
2927                            LN0->getPointerInfo(),
2928                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2929                            Alignment, LN0->getTBAAInfo());
2930           AddToWorkList(N);
2931           CombineTo(LN0, Load, Load.getValue(1));
2932           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2933         }
2934       }
2935     }
2936   }
2937
2938   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2939       VT.getSizeInBits() <= 64) {
2940     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2941       APInt ADDC = ADDI->getAPIntValue();
2942       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2943         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2944         // immediate for an add, but it is legal if its top c2 bits are set,
2945         // transform the ADD so the immediate doesn't need to be materialized
2946         // in a register.
2947         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2948           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2949                                              SRLI->getZExtValue());
2950           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2951             ADDC |= Mask;
2952             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2953               SDValue NewAdd =
2954                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2955                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2956               CombineTo(N0.getNode(), NewAdd);
2957               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2958             }
2959           }
2960         }
2961       }
2962     }
2963   }
2964
2965   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2966   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2967     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2968                                        N0.getOperand(1), false);
2969     if (BSwap.getNode())
2970       return BSwap;
2971   }
2972
2973   return SDValue();
2974 }
2975
2976 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2977 ///
2978 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2979                                         bool DemandHighBits) {
2980   if (!LegalOperations)
2981     return SDValue();
2982
2983   EVT VT = N->getValueType(0);
2984   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2985     return SDValue();
2986   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2987     return SDValue();
2988
2989   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2990   bool LookPassAnd0 = false;
2991   bool LookPassAnd1 = false;
2992   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2993       std::swap(N0, N1);
2994   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2995       std::swap(N0, N1);
2996   if (N0.getOpcode() == ISD::AND) {
2997     if (!N0.getNode()->hasOneUse())
2998       return SDValue();
2999     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3000     if (!N01C || N01C->getZExtValue() != 0xFF00)
3001       return SDValue();
3002     N0 = N0.getOperand(0);
3003     LookPassAnd0 = true;
3004   }
3005
3006   if (N1.getOpcode() == ISD::AND) {
3007     if (!N1.getNode()->hasOneUse())
3008       return SDValue();
3009     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3010     if (!N11C || N11C->getZExtValue() != 0xFF)
3011       return SDValue();
3012     N1 = N1.getOperand(0);
3013     LookPassAnd1 = true;
3014   }
3015
3016   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3017     std::swap(N0, N1);
3018   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3019     return SDValue();
3020   if (!N0.getNode()->hasOneUse() ||
3021       !N1.getNode()->hasOneUse())
3022     return SDValue();
3023
3024   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3025   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3026   if (!N01C || !N11C)
3027     return SDValue();
3028   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3029     return SDValue();
3030
3031   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3032   SDValue N00 = N0->getOperand(0);
3033   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3034     if (!N00.getNode()->hasOneUse())
3035       return SDValue();
3036     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3037     if (!N001C || N001C->getZExtValue() != 0xFF)
3038       return SDValue();
3039     N00 = N00.getOperand(0);
3040     LookPassAnd0 = true;
3041   }
3042
3043   SDValue N10 = N1->getOperand(0);
3044   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3045     if (!N10.getNode()->hasOneUse())
3046       return SDValue();
3047     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3048     if (!N101C || N101C->getZExtValue() != 0xFF00)
3049       return SDValue();
3050     N10 = N10.getOperand(0);
3051     LookPassAnd1 = true;
3052   }
3053
3054   if (N00 != N10)
3055     return SDValue();
3056
3057   // Make sure everything beyond the low halfword gets set to zero since the SRL
3058   // 16 will clear the top bits.
3059   unsigned OpSizeInBits = VT.getSizeInBits();
3060   if (DemandHighBits && OpSizeInBits > 16) {
3061     // If the left-shift isn't masked out then the only way this is a bswap is
3062     // if all bits beyond the low 8 are 0. In that case the entire pattern
3063     // reduces to a left shift anyway: leave it for other parts of the combiner.
3064     if (!LookPassAnd0)
3065       return SDValue();
3066
3067     // However, if the right shift isn't masked out then it might be because
3068     // it's not needed. See if we can spot that too.
3069     if (!LookPassAnd1 &&
3070         !DAG.MaskedValueIsZero(
3071             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3072       return SDValue();
3073   }
3074
3075   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3076   if (OpSizeInBits > 16)
3077     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3078                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3079   return Res;
3080 }
3081
3082 /// isBSwapHWordElement - Return true if the specified node is an element
3083 /// that makes up a 32-bit packed halfword byteswap. i.e.
3084 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3085 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3086   if (!N.getNode()->hasOneUse())
3087     return false;
3088
3089   unsigned Opc = N.getOpcode();
3090   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3091     return false;
3092
3093   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3094   if (!N1C)
3095     return false;
3096
3097   unsigned Num;
3098   switch (N1C->getZExtValue()) {
3099   default:
3100     return false;
3101   case 0xFF:       Num = 0; break;
3102   case 0xFF00:     Num = 1; break;
3103   case 0xFF0000:   Num = 2; break;
3104   case 0xFF000000: Num = 3; break;
3105   }
3106
3107   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3108   SDValue N0 = N.getOperand(0);
3109   if (Opc == ISD::AND) {
3110     if (Num == 0 || Num == 2) {
3111       // (x >> 8) & 0xff
3112       // (x >> 8) & 0xff0000
3113       if (N0.getOpcode() != ISD::SRL)
3114         return false;
3115       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3116       if (!C || C->getZExtValue() != 8)
3117         return false;
3118     } else {
3119       // (x << 8) & 0xff00
3120       // (x << 8) & 0xff000000
3121       if (N0.getOpcode() != ISD::SHL)
3122         return false;
3123       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3124       if (!C || C->getZExtValue() != 8)
3125         return false;
3126     }
3127   } else if (Opc == ISD::SHL) {
3128     // (x & 0xff) << 8
3129     // (x & 0xff0000) << 8
3130     if (Num != 0 && Num != 2)
3131       return false;
3132     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3133     if (!C || C->getZExtValue() != 8)
3134       return false;
3135   } else { // Opc == ISD::SRL
3136     // (x & 0xff00) >> 8
3137     // (x & 0xff000000) >> 8
3138     if (Num != 1 && Num != 3)
3139       return false;
3140     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3141     if (!C || C->getZExtValue() != 8)
3142       return false;
3143   }
3144
3145   if (Parts[Num])
3146     return false;
3147
3148   Parts[Num] = N0.getOperand(0).getNode();
3149   return true;
3150 }
3151
3152 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3153 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3154 /// => (rotl (bswap x), 16)
3155 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3156   if (!LegalOperations)
3157     return SDValue();
3158
3159   EVT VT = N->getValueType(0);
3160   if (VT != MVT::i32)
3161     return SDValue();
3162   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163     return SDValue();
3164
3165   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3166   // Look for either
3167   // (or (or (and), (and)), (or (and), (and)))
3168   // (or (or (or (and), (and)), (and)), (and))
3169   if (N0.getOpcode() != ISD::OR)
3170     return SDValue();
3171   SDValue N00 = N0.getOperand(0);
3172   SDValue N01 = N0.getOperand(1);
3173
3174   if (N1.getOpcode() == ISD::OR &&
3175       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3176     // (or (or (and), (and)), (or (and), (and)))
3177     SDValue N000 = N00.getOperand(0);
3178     if (!isBSwapHWordElement(N000, Parts))
3179       return SDValue();
3180
3181     SDValue N001 = N00.getOperand(1);
3182     if (!isBSwapHWordElement(N001, Parts))
3183       return SDValue();
3184     SDValue N010 = N01.getOperand(0);
3185     if (!isBSwapHWordElement(N010, Parts))
3186       return SDValue();
3187     SDValue N011 = N01.getOperand(1);
3188     if (!isBSwapHWordElement(N011, Parts))
3189       return SDValue();
3190   } else {
3191     // (or (or (or (and), (and)), (and)), (and))
3192     if (!isBSwapHWordElement(N1, Parts))
3193       return SDValue();
3194     if (!isBSwapHWordElement(N01, Parts))
3195       return SDValue();
3196     if (N00.getOpcode() != ISD::OR)
3197       return SDValue();
3198     SDValue N000 = N00.getOperand(0);
3199     if (!isBSwapHWordElement(N000, Parts))
3200       return SDValue();
3201     SDValue N001 = N00.getOperand(1);
3202     if (!isBSwapHWordElement(N001, Parts))
3203       return SDValue();
3204   }
3205
3206   // Make sure the parts are all coming from the same node.
3207   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3208     return SDValue();
3209
3210   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3211                               SDValue(Parts[0],0));
3212
3213   // Result of the bswap should be rotated by 16. If it's not legal, then
3214   // do  (x << 16) | (x >> 16).
3215   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3216   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3217     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3218   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3219     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3220   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3221                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3222                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3223 }
3224
3225 SDValue DAGCombiner::visitOR(SDNode *N) {
3226   SDValue N0 = N->getOperand(0);
3227   SDValue N1 = N->getOperand(1);
3228   SDValue LL, LR, RL, RR, CC0, CC1;
3229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3231   EVT VT = N1.getValueType();
3232
3233   // fold vector ops
3234   if (VT.isVector()) {
3235     SDValue FoldedVOp = SimplifyVBinOp(N);
3236     if (FoldedVOp.getNode()) return FoldedVOp;
3237
3238     // fold (or x, 0) -> x, vector edition
3239     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3240       return N1;
3241     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3242       return N0;
3243
3244     // fold (or x, -1) -> -1, vector edition
3245     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3246       return N0;
3247     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3248       return N1;
3249
3250     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3251     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3252     // Do this only if the resulting shuffle is legal.
3253     if (isa<ShuffleVectorSDNode>(N0) &&
3254         isa<ShuffleVectorSDNode>(N1) &&
3255         N0->getOperand(1) == N1->getOperand(1) &&
3256         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3257       bool CanFold = true;
3258       unsigned NumElts = VT.getVectorNumElements();
3259       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3260       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3261       // We construct two shuffle masks:
3262       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3263       // and N1 as the second operand.
3264       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3265       // and N0 as the second operand.
3266       // We do this because OR is commutable and therefore there might be
3267       // two ways to fold this node into a shuffle.
3268       SmallVector<int,4> Mask1;
3269       SmallVector<int,4> Mask2;
3270       
3271       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3272         int M0 = SV0->getMaskElt(i);
3273         int M1 = SV1->getMaskElt(i);
3274    
3275         // Both shuffle indexes are undef. Propagate Undef.
3276         if (M0 < 0 && M1 < 0) {
3277           Mask1.push_back(M0);
3278           Mask2.push_back(M0);
3279           continue;
3280         }
3281
3282         if (M0 < 0 || M1 < 0 ||
3283             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3284             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3285           CanFold = false;
3286           break;
3287         }
3288         
3289         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3290         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3291       }
3292
3293       if (CanFold) {
3294         // Fold this sequence only if the resulting shuffle is 'legal'.
3295         if (TLI.isShuffleMaskLegal(Mask1, VT))
3296           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3297                                       N1->getOperand(0), &Mask1[0]);
3298         if (TLI.isShuffleMaskLegal(Mask2, VT))
3299           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3300                                       N0->getOperand(0), &Mask2[0]);
3301       }
3302     }
3303   }
3304
3305   // fold (or x, undef) -> -1
3306   if (!LegalOperations &&
3307       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3308     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3309     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3310   }
3311   // fold (or c1, c2) -> c1|c2
3312   if (N0C && N1C)
3313     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3314   // canonicalize constant to RHS
3315   if (N0C && !N1C)
3316     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3317   // fold (or x, 0) -> x
3318   if (N1C && N1C->isNullValue())
3319     return N0;
3320   // fold (or x, -1) -> -1
3321   if (N1C && N1C->isAllOnesValue())
3322     return N1;
3323   // fold (or x, c) -> c iff (x & ~c) == 0
3324   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3325     return N1;
3326
3327   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3328   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3329   if (BSwap.getNode() != 0)
3330     return BSwap;
3331   BSwap = MatchBSwapHWordLow(N, N0, N1);
3332   if (BSwap.getNode() != 0)
3333     return BSwap;
3334
3335   // reassociate or
3336   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3337   if (ROR.getNode() != 0)
3338     return ROR;
3339   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3340   // iff (c1 & c2) == 0.
3341   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3342              isa<ConstantSDNode>(N0.getOperand(1))) {
3343     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3344     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3345       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3346       if (!COR.getNode())
3347         return SDValue();
3348       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3349                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3350                                      N0.getOperand(0), N1), COR);
3351     }
3352   }
3353   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3354   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3355     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3356     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3357
3358     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3359         LL.getValueType().isInteger()) {
3360       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3361       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3362       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3363           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3364         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3365                                      LR.getValueType(), LL, RL);
3366         AddToWorkList(ORNode.getNode());
3367         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3368       }
3369       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3370       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3371       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3372           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3373         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3374                                       LR.getValueType(), LL, RL);
3375         AddToWorkList(ANDNode.getNode());
3376         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3377       }
3378     }
3379     // canonicalize equivalent to ll == rl
3380     if (LL == RR && LR == RL) {
3381       Op1 = ISD::getSetCCSwappedOperands(Op1);
3382       std::swap(RL, RR);
3383     }
3384     if (LL == RL && LR == RR) {
3385       bool isInteger = LL.getValueType().isInteger();
3386       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3387       if (Result != ISD::SETCC_INVALID &&
3388           (!LegalOperations ||
3389            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3390             TLI.isOperationLegal(ISD::SETCC,
3391               getSetCCResultType(N0.getValueType())))))
3392         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3393                             LL, LR, Result);
3394     }
3395   }
3396
3397   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3398   if (N0.getOpcode() == N1.getOpcode()) {
3399     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3400     if (Tmp.getNode()) return Tmp;
3401   }
3402
3403   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3404   if (N0.getOpcode() == ISD::AND &&
3405       N1.getOpcode() == ISD::AND &&
3406       N0.getOperand(1).getOpcode() == ISD::Constant &&
3407       N1.getOperand(1).getOpcode() == ISD::Constant &&
3408       // Don't increase # computations.
3409       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3410     // We can only do this xform if we know that bits from X that are set in C2
3411     // but not in C1 are already zero.  Likewise for Y.
3412     const APInt &LHSMask =
3413       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3414     const APInt &RHSMask =
3415       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3416
3417     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3418         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3419       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3420                               N0.getOperand(0), N1.getOperand(0));
3421       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3422                          DAG.getConstant(LHSMask | RHSMask, VT));
3423     }
3424   }
3425
3426   // See if this is some rotate idiom.
3427   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3428     return SDValue(Rot, 0);
3429
3430   // Simplify the operands using demanded-bits information.
3431   if (!VT.isVector() &&
3432       SimplifyDemandedBits(SDValue(N, 0)))
3433     return SDValue(N, 0);
3434
3435   return SDValue();
3436 }
3437
3438 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3439 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3440   if (Op.getOpcode() == ISD::AND) {
3441     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3442       Mask = Op.getOperand(1);
3443       Op = Op.getOperand(0);
3444     } else {
3445       return false;
3446     }
3447   }
3448
3449   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3450     Shift = Op;
3451     return true;
3452   }
3453
3454   return false;
3455 }
3456
3457 // Return true if we can prove that, whenever Neg and Pos are both in the
3458 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3459 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3460 //
3461 //     (or (shift1 X, Neg), (shift2 X, Pos))
3462 //
3463 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3464 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3465 // to consider shift amounts with defined behavior.
3466 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3467   // If OpSize is a power of 2 then:
3468   //
3469   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3470   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3471   //
3472   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3473   // for the stronger condition:
3474   //
3475   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3476   //
3477   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3478   // we can just replace Neg with Neg' for the rest of the function.
3479   //
3480   // In other cases we check for the even stronger condition:
3481   //
3482   //     Neg == OpSize - Pos                                    [B]
3483   //
3484   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3485   // behavior if Pos == 0 (and consequently Neg == OpSize).
3486   //
3487   // We could actually use [A] whenever OpSize is a power of 2, but the
3488   // only extra cases that it would match are those uninteresting ones
3489   // where Neg and Pos are never in range at the same time.  E.g. for
3490   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3491   // as well as (sub 32, Pos), but:
3492   //
3493   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3494   //
3495   // always invokes undefined behavior for 32-bit X.
3496   //
3497   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3498   unsigned MaskLoBits = 0;
3499   if (Neg.getOpcode() == ISD::AND &&
3500       isPowerOf2_64(OpSize) &&
3501       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3502       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3503     Neg = Neg.getOperand(0);
3504     MaskLoBits = Log2_64(OpSize);
3505   }
3506
3507   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3508   if (Neg.getOpcode() != ISD::SUB)
3509     return 0;
3510   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3511   if (!NegC)
3512     return 0;
3513   SDValue NegOp1 = Neg.getOperand(1);
3514
3515   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3516   // Pos'.  The truncation is redundant for the purpose of the equality.
3517   if (MaskLoBits &&
3518       Pos.getOpcode() == ISD::AND &&
3519       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3520       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3521     Pos = Pos.getOperand(0);
3522
3523   // The condition we need is now:
3524   //
3525   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3526   //
3527   // If NegOp1 == Pos then we need:
3528   //
3529   //              OpSize & Mask == NegC & Mask
3530   //
3531   // (because "x & Mask" is a truncation and distributes through subtraction).
3532   APInt Width;
3533   if (Pos == NegOp1)
3534     Width = NegC->getAPIntValue();
3535   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3536   // Then the condition we want to prove becomes:
3537   //
3538   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3539   //
3540   // which, again because "x & Mask" is a truncation, becomes:
3541   //
3542   //                NegC & Mask == (OpSize - PosC) & Mask
3543   //              OpSize & Mask == (NegC + PosC) & Mask
3544   else if (Pos.getOpcode() == ISD::ADD &&
3545            Pos.getOperand(0) == NegOp1 &&
3546            Pos.getOperand(1).getOpcode() == ISD::Constant)
3547     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3548              NegC->getAPIntValue());
3549   else
3550     return false;
3551
3552   // Now we just need to check that OpSize & Mask == Width & Mask.
3553   if (MaskLoBits)
3554     // Opsize & Mask is 0 since Mask is Opsize - 1.
3555     return Width.getLoBits(MaskLoBits) == 0;
3556   return Width == OpSize;
3557 }
3558
3559 // A subroutine of MatchRotate used once we have found an OR of two opposite
3560 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3561 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3562 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3563 // Neg with outer conversions stripped away.
3564 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3565                                        SDValue Neg, SDValue InnerPos,
3566                                        SDValue InnerNeg, unsigned PosOpcode,
3567                                        unsigned NegOpcode, SDLoc DL) {
3568   // fold (or (shl x, (*ext y)),
3569   //          (srl x, (*ext (sub 32, y)))) ->
3570   //   (rotl x, y) or (rotr x, (sub 32, y))
3571   //
3572   // fold (or (shl x, (*ext (sub 32, y))),
3573   //          (srl x, (*ext y))) ->
3574   //   (rotr x, y) or (rotl x, (sub 32, y))
3575   EVT VT = Shifted.getValueType();
3576   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3577     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3578     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3579                        HasPos ? Pos : Neg).getNode();
3580   }
3581
3582   // fold (or (shl (*ext x), (*ext y)),
3583   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3584   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3585   //
3586   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3587   //          (srl (*ext x), (*ext y))) ->
3588   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3589   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3590       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3591     SDValue InnerShifted = Shifted.getOperand(0);
3592     EVT InnerVT = InnerShifted.getValueType();
3593     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3594     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3595       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3596         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3597                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3598         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3599       }
3600     }
3601   }
3602
3603   return 0;
3604 }
3605
3606 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3607 // idioms for rotate, and if the target supports rotation instructions, generate
3608 // a rot[lr].
3609 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3610   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3611   EVT VT = LHS.getValueType();
3612   if (!TLI.isTypeLegal(VT)) return 0;
3613
3614   // The target must have at least one rotate flavor.
3615   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3616   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3617   if (!HasROTL && !HasROTR) return 0;
3618
3619   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3620   SDValue LHSShift;   // The shift.
3621   SDValue LHSMask;    // AND value if any.
3622   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3623     return 0; // Not part of a rotate.
3624
3625   SDValue RHSShift;   // The shift.
3626   SDValue RHSMask;    // AND value if any.
3627   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3628     return 0; // Not part of a rotate.
3629
3630   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3631     return 0;   // Not shifting the same value.
3632
3633   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3634     return 0;   // Shifts must disagree.
3635
3636   // Canonicalize shl to left side in a shl/srl pair.
3637   if (RHSShift.getOpcode() == ISD::SHL) {
3638     std::swap(LHS, RHS);
3639     std::swap(LHSShift, RHSShift);
3640     std::swap(LHSMask , RHSMask );
3641   }
3642
3643   unsigned OpSizeInBits = VT.getSizeInBits();
3644   SDValue LHSShiftArg = LHSShift.getOperand(0);
3645   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3646   SDValue RHSShiftArg = RHSShift.getOperand(0);
3647   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3648
3649   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3650   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3651   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3652       RHSShiftAmt.getOpcode() == ISD::Constant) {
3653     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3654     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3655     if ((LShVal + RShVal) != OpSizeInBits)
3656       return 0;
3657
3658     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3659                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3660
3661     // If there is an AND of either shifted operand, apply it to the result.
3662     if (LHSMask.getNode() || RHSMask.getNode()) {
3663       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3664
3665       if (LHSMask.getNode()) {
3666         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3667         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3668       }
3669       if (RHSMask.getNode()) {
3670         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3671         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3672       }
3673
3674       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3675     }
3676
3677     return Rot.getNode();
3678   }
3679
3680   // If there is a mask here, and we have a variable shift, we can't be sure
3681   // that we're masking out the right stuff.
3682   if (LHSMask.getNode() || RHSMask.getNode())
3683     return 0;
3684
3685   // If the shift amount is sign/zext/any-extended just peel it off.
3686   SDValue LExtOp0 = LHSShiftAmt;
3687   SDValue RExtOp0 = RHSShiftAmt;
3688   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3689        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3690        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3691        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3692       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3693        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3694        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3695        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3696     LExtOp0 = LHSShiftAmt.getOperand(0);
3697     RExtOp0 = RHSShiftAmt.getOperand(0);
3698   }
3699
3700   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3701                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3702   if (TryL)
3703     return TryL;
3704
3705   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3706                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3707   if (TryR)
3708     return TryR;
3709
3710   return 0;
3711 }
3712
3713 SDValue DAGCombiner::visitXOR(SDNode *N) {
3714   SDValue N0 = N->getOperand(0);
3715   SDValue N1 = N->getOperand(1);
3716   SDValue LHS, RHS, CC;
3717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3719   EVT VT = N0.getValueType();
3720
3721   // fold vector ops
3722   if (VT.isVector()) {
3723     SDValue FoldedVOp = SimplifyVBinOp(N);
3724     if (FoldedVOp.getNode()) return FoldedVOp;
3725
3726     // fold (xor x, 0) -> x, vector edition
3727     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3728       return N1;
3729     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3730       return N0;
3731   }
3732
3733   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3734   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3735     return DAG.getConstant(0, VT);
3736   // fold (xor x, undef) -> undef
3737   if (N0.getOpcode() == ISD::UNDEF)
3738     return N0;
3739   if (N1.getOpcode() == ISD::UNDEF)
3740     return N1;
3741   // fold (xor c1, c2) -> c1^c2
3742   if (N0C && N1C)
3743     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3744   // canonicalize constant to RHS
3745   if (N0C && !N1C)
3746     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3747   // fold (xor x, 0) -> x
3748   if (N1C && N1C->isNullValue())
3749     return N0;
3750   // reassociate xor
3751   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3752   if (RXOR.getNode() != 0)
3753     return RXOR;
3754
3755   // fold !(x cc y) -> (x !cc y)
3756   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3757     bool isInt = LHS.getValueType().isInteger();
3758     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3759                                                isInt);
3760
3761     if (!LegalOperations ||
3762         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3763       switch (N0.getOpcode()) {
3764       default:
3765         llvm_unreachable("Unhandled SetCC Equivalent!");
3766       case ISD::SETCC:
3767         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3768       case ISD::SELECT_CC:
3769         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3770                                N0.getOperand(3), NotCC);
3771       }
3772     }
3773   }
3774
3775   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3776   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3777       N0.getNode()->hasOneUse() &&
3778       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3779     SDValue V = N0.getOperand(0);
3780     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3781                     DAG.getConstant(1, V.getValueType()));
3782     AddToWorkList(V.getNode());
3783     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3784   }
3785
3786   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3787   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3788       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3789     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3790     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3791       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3792       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3793       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3794       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3795       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3796     }
3797   }
3798   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3799   if (N1C && N1C->isAllOnesValue() &&
3800       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3801     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3802     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3803       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3804       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3805       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3806       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3807       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3808     }
3809   }
3810   // fold (xor (and x, y), y) -> (and (not x), y)
3811   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3812       N0->getOperand(1) == N1) {
3813     SDValue X = N0->getOperand(0);
3814     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3815     AddToWorkList(NotX.getNode());
3816     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3817   }
3818   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3819   if (N1C && N0.getOpcode() == ISD::XOR) {
3820     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3821     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3822     if (N00C)
3823       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3824                          DAG.getConstant(N1C->getAPIntValue() ^
3825                                          N00C->getAPIntValue(), VT));
3826     if (N01C)
3827       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3828                          DAG.getConstant(N1C->getAPIntValue() ^
3829                                          N01C->getAPIntValue(), VT));
3830   }
3831   // fold (xor x, x) -> 0
3832   if (N0 == N1)
3833     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3834
3835   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3836   if (N0.getOpcode() == N1.getOpcode()) {
3837     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3838     if (Tmp.getNode()) return Tmp;
3839   }
3840
3841   // Simplify the expression using non-local knowledge.
3842   if (!VT.isVector() &&
3843       SimplifyDemandedBits(SDValue(N, 0)))
3844     return SDValue(N, 0);
3845
3846   return SDValue();
3847 }
3848
3849 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3850 /// the shift amount is a constant.
3851 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3852   // We can't and shouldn't fold opaque constants.
3853   if (Amt->isOpaque())
3854     return SDValue();
3855
3856   SDNode *LHS = N->getOperand(0).getNode();
3857   if (!LHS->hasOneUse()) return SDValue();
3858
3859   // We want to pull some binops through shifts, so that we have (and (shift))
3860   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3861   // thing happens with address calculations, so it's important to canonicalize
3862   // it.
3863   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3864
3865   switch (LHS->getOpcode()) {
3866   default: return SDValue();
3867   case ISD::OR:
3868   case ISD::XOR:
3869     HighBitSet = false; // We can only transform sra if the high bit is clear.
3870     break;
3871   case ISD::AND:
3872     HighBitSet = true;  // We can only transform sra if the high bit is set.
3873     break;
3874   case ISD::ADD:
3875     if (N->getOpcode() != ISD::SHL)
3876       return SDValue(); // only shl(add) not sr[al](add).
3877     HighBitSet = false; // We can only transform sra if the high bit is clear.
3878     break;
3879   }
3880
3881   // We require the RHS of the binop to be a constant and not opaque as well.
3882   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3883   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3884
3885   // FIXME: disable this unless the input to the binop is a shift by a constant.
3886   // If it is not a shift, it pessimizes some common cases like:
3887   //
3888   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3889   //    int bar(int *X, int i) { return X[i & 255]; }
3890   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3891   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3892        BinOpLHSVal->getOpcode() != ISD::SRA &&
3893        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3894       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3895     return SDValue();
3896
3897   EVT VT = N->getValueType(0);
3898
3899   // If this is a signed shift right, and the high bit is modified by the
3900   // logical operation, do not perform the transformation. The highBitSet
3901   // boolean indicates the value of the high bit of the constant which would
3902   // cause it to be modified for this operation.
3903   if (N->getOpcode() == ISD::SRA) {
3904     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3905     if (BinOpRHSSignSet != HighBitSet)
3906       return SDValue();
3907   }
3908
3909   // Fold the constants, shifting the binop RHS by the shift amount.
3910   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3911                                N->getValueType(0),
3912                                LHS->getOperand(1), N->getOperand(1));
3913   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3914
3915   // Create the new shift.
3916   SDValue NewShift = DAG.getNode(N->getOpcode(),
3917                                  SDLoc(LHS->getOperand(0)),
3918                                  VT, LHS->getOperand(0), N->getOperand(1));
3919
3920   // Create the new binop.
3921   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3922 }
3923
3924 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3925   assert(N->getOpcode() == ISD::TRUNCATE);
3926   assert(N->getOperand(0).getOpcode() == ISD::AND);
3927
3928   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3929   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3930     SDValue N01 = N->getOperand(0).getOperand(1);
3931
3932     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3933       EVT TruncVT = N->getValueType(0);
3934       SDValue N00 = N->getOperand(0).getOperand(0);
3935       APInt TruncC = N01C->getAPIntValue();
3936       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3937
3938       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3939                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3940                          DAG.getConstant(TruncC, TruncVT));
3941     }
3942   }
3943
3944   return SDValue();
3945 }
3946
3947 SDValue DAGCombiner::visitRotate(SDNode *N) {
3948   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3949   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3950       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3951     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3952     if (NewOp1.getNode())
3953       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3954                          N->getOperand(0), NewOp1);
3955   }
3956   return SDValue();
3957 }
3958
3959 SDValue DAGCombiner::visitSHL(SDNode *N) {
3960   SDValue N0 = N->getOperand(0);
3961   SDValue N1 = N->getOperand(1);
3962   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3963   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3964   EVT VT = N0.getValueType();
3965   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3966
3967   // fold vector ops
3968   if (VT.isVector()) {
3969     SDValue FoldedVOp = SimplifyVBinOp(N);
3970     if (FoldedVOp.getNode()) return FoldedVOp;
3971
3972     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3973     // If setcc produces all-one true value then:
3974     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3975     if (N1CV && N1CV->isConstant()) {
3976       if (N0.getOpcode() == ISD::AND &&
3977           TLI.getBooleanContents(true) ==
3978           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3979         SDValue N00 = N0->getOperand(0);
3980         SDValue N01 = N0->getOperand(1);
3981         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3982
3983         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3984           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3985           if (C.getNode())
3986             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3987         }
3988       } else {
3989         N1C = isConstOrConstSplat(N1);
3990       }
3991     }
3992   }
3993
3994   // fold (shl c1, c2) -> c1<<c2
3995   if (N0C && N1C)
3996     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3997   // fold (shl 0, x) -> 0
3998   if (N0C && N0C->isNullValue())
3999     return N0;
4000   // fold (shl x, c >= size(x)) -> undef
4001   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4002     return DAG.getUNDEF(VT);
4003   // fold (shl x, 0) -> x
4004   if (N1C && N1C->isNullValue())
4005     return N0;
4006   // fold (shl undef, x) -> 0
4007   if (N0.getOpcode() == ISD::UNDEF)
4008     return DAG.getConstant(0, VT);
4009   // if (shl x, c) is known to be zero, return 0
4010   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4011                             APInt::getAllOnesValue(OpSizeInBits)))
4012     return DAG.getConstant(0, VT);
4013   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4014   if (N1.getOpcode() == ISD::TRUNCATE &&
4015       N1.getOperand(0).getOpcode() == ISD::AND) {
4016     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4017     if (NewOp1.getNode())
4018       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4019   }
4020
4021   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4022     return SDValue(N, 0);
4023
4024   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4025   if (N1C && N0.getOpcode() == ISD::SHL) {
4026     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4027       uint64_t c1 = N0C1->getZExtValue();
4028       uint64_t c2 = N1C->getZExtValue();
4029       if (c1 + c2 >= OpSizeInBits)
4030         return DAG.getConstant(0, VT);
4031       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4032                          DAG.getConstant(c1 + c2, N1.getValueType()));
4033     }
4034   }
4035
4036   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4037   // For this to be valid, the second form must not preserve any of the bits
4038   // that are shifted out by the inner shift in the first form.  This means
4039   // the outer shift size must be >= the number of bits added by the ext.
4040   // As a corollary, we don't care what kind of ext it is.
4041   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4042               N0.getOpcode() == ISD::ANY_EXTEND ||
4043               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4044       N0.getOperand(0).getOpcode() == ISD::SHL) {
4045     SDValue N0Op0 = N0.getOperand(0);
4046     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4047       uint64_t c1 = N0Op0C1->getZExtValue();
4048       uint64_t c2 = N1C->getZExtValue();
4049       EVT InnerShiftVT = N0Op0.getValueType();
4050       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4051       if (c2 >= OpSizeInBits - InnerShiftSize) {
4052         if (c1 + c2 >= OpSizeInBits)
4053           return DAG.getConstant(0, VT);
4054         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4055                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4056                                        N0Op0->getOperand(0)),
4057                            DAG.getConstant(c1 + c2, N1.getValueType()));
4058       }
4059     }
4060   }
4061
4062   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4063   // Only fold this if the inner zext has no other uses to avoid increasing
4064   // the total number of instructions.
4065   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4066       N0.getOperand(0).getOpcode() == ISD::SRL) {
4067     SDValue N0Op0 = N0.getOperand(0);
4068     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4069       uint64_t c1 = N0Op0C1->getZExtValue();
4070       if (c1 < VT.getScalarSizeInBits()) {
4071         uint64_t c2 = N1C->getZExtValue();
4072         if (c1 == c2) {
4073           SDValue NewOp0 = N0.getOperand(0);
4074           EVT CountVT = NewOp0.getOperand(1).getValueType();
4075           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4076                                        NewOp0, DAG.getConstant(c2, CountVT));
4077           AddToWorkList(NewSHL.getNode());
4078           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4079         }
4080       }
4081     }
4082   }
4083
4084   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4085   //                               (and (srl x, (sub c1, c2), MASK)
4086   // Only fold this if the inner shift has no other uses -- if it does, folding
4087   // this will increase the total number of instructions.
4088   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4089     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4090       uint64_t c1 = N0C1->getZExtValue();
4091       if (c1 < OpSizeInBits) {
4092         uint64_t c2 = N1C->getZExtValue();
4093         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4094         SDValue Shift;
4095         if (c2 > c1) {
4096           Mask = Mask.shl(c2 - c1);
4097           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4098                               DAG.getConstant(c2 - c1, N1.getValueType()));
4099         } else {
4100           Mask = Mask.lshr(c1 - c2);
4101           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4102                               DAG.getConstant(c1 - c2, N1.getValueType()));
4103         }
4104         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4105                            DAG.getConstant(Mask, VT));
4106       }
4107     }
4108   }
4109   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4110   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4111     unsigned BitSize = VT.getScalarSizeInBits();
4112     SDValue HiBitsMask =
4113       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4114                                             BitSize - N1C->getZExtValue()), VT);
4115     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4116                        HiBitsMask);
4117   }
4118
4119   if (N1C) {
4120     SDValue NewSHL = visitShiftByConstant(N, N1C);
4121     if (NewSHL.getNode())
4122       return NewSHL;
4123   }
4124
4125   return SDValue();
4126 }
4127
4128 SDValue DAGCombiner::visitSRA(SDNode *N) {
4129   SDValue N0 = N->getOperand(0);
4130   SDValue N1 = N->getOperand(1);
4131   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4132   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4133   EVT VT = N0.getValueType();
4134   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4135
4136   // fold vector ops
4137   if (VT.isVector()) {
4138     SDValue FoldedVOp = SimplifyVBinOp(N);
4139     if (FoldedVOp.getNode()) return FoldedVOp;
4140
4141     N1C = isConstOrConstSplat(N1);
4142   }
4143
4144   // fold (sra c1, c2) -> (sra c1, c2)
4145   if (N0C && N1C)
4146     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4147   // fold (sra 0, x) -> 0
4148   if (N0C && N0C->isNullValue())
4149     return N0;
4150   // fold (sra -1, x) -> -1
4151   if (N0C && N0C->isAllOnesValue())
4152     return N0;
4153   // fold (sra x, (setge c, size(x))) -> undef
4154   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4155     return DAG.getUNDEF(VT);
4156   // fold (sra x, 0) -> x
4157   if (N1C && N1C->isNullValue())
4158     return N0;
4159   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4160   // sext_inreg.
4161   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4162     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4163     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4164     if (VT.isVector())
4165       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4166                                ExtVT, VT.getVectorNumElements());
4167     if ((!LegalOperations ||
4168          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4169       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4170                          N0.getOperand(0), DAG.getValueType(ExtVT));
4171   }
4172
4173   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4174   if (N1C && N0.getOpcode() == ISD::SRA) {
4175     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4176       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4177       if (Sum >= OpSizeInBits)
4178         Sum = OpSizeInBits - 1;
4179       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4180                          DAG.getConstant(Sum, N1.getValueType()));
4181     }
4182   }
4183
4184   // fold (sra (shl X, m), (sub result_size, n))
4185   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4186   // result_size - n != m.
4187   // If truncate is free for the target sext(shl) is likely to result in better
4188   // code.
4189   if (N0.getOpcode() == ISD::SHL && N1C) {
4190     // Get the two constanst of the shifts, CN0 = m, CN = n.
4191     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4192     if (N01C) {
4193       LLVMContext &Ctx = *DAG.getContext();
4194       // Determine what the truncate's result bitsize and type would be.
4195       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4196
4197       if (VT.isVector())
4198         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4199
4200       // Determine the residual right-shift amount.
4201       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4202
4203       // If the shift is not a no-op (in which case this should be just a sign
4204       // extend already), the truncated to type is legal, sign_extend is legal
4205       // on that type, and the truncate to that type is both legal and free,
4206       // perform the transform.
4207       if ((ShiftAmt > 0) &&
4208           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4209           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4210           TLI.isTruncateFree(VT, TruncVT)) {
4211
4212           SDValue Amt = DAG.getConstant(ShiftAmt,
4213               getShiftAmountTy(N0.getOperand(0).getValueType()));
4214           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4215                                       N0.getOperand(0), Amt);
4216           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4217                                       Shift);
4218           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4219                              N->getValueType(0), Trunc);
4220       }
4221     }
4222   }
4223
4224   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4225   if (N1.getOpcode() == ISD::TRUNCATE &&
4226       N1.getOperand(0).getOpcode() == ISD::AND) {
4227     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4228     if (NewOp1.getNode())
4229       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4230   }
4231
4232   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4233   //      if c1 is equal to the number of bits the trunc removes
4234   if (N0.getOpcode() == ISD::TRUNCATE &&
4235       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4236        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4237       N0.getOperand(0).hasOneUse() &&
4238       N0.getOperand(0).getOperand(1).hasOneUse() &&
4239       N1C) {
4240     SDValue N0Op0 = N0.getOperand(0);
4241     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4242       unsigned LargeShiftVal = LargeShift->getZExtValue();
4243       EVT LargeVT = N0Op0.getValueType();
4244
4245       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4246         SDValue Amt =
4247           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4248                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4249         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4250                                   N0Op0.getOperand(0), Amt);
4251         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4252       }
4253     }
4254   }
4255
4256   // Simplify, based on bits shifted out of the LHS.
4257   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4258     return SDValue(N, 0);
4259
4260
4261   // If the sign bit is known to be zero, switch this to a SRL.
4262   if (DAG.SignBitIsZero(N0))
4263     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4264
4265   if (N1C) {
4266     SDValue NewSRA = visitShiftByConstant(N, N1C);
4267     if (NewSRA.getNode())
4268       return NewSRA;
4269   }
4270
4271   return SDValue();
4272 }
4273
4274 SDValue DAGCombiner::visitSRL(SDNode *N) {
4275   SDValue N0 = N->getOperand(0);
4276   SDValue N1 = N->getOperand(1);
4277   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4278   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4279   EVT VT = N0.getValueType();
4280   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4281
4282   // fold vector ops
4283   if (VT.isVector()) {
4284     SDValue FoldedVOp = SimplifyVBinOp(N);
4285     if (FoldedVOp.getNode()) return FoldedVOp;
4286
4287     N1C = isConstOrConstSplat(N1);
4288   }
4289
4290   // fold (srl c1, c2) -> c1 >>u c2
4291   if (N0C && N1C)
4292     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4293   // fold (srl 0, x) -> 0
4294   if (N0C && N0C->isNullValue())
4295     return N0;
4296   // fold (srl x, c >= size(x)) -> undef
4297   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4298     return DAG.getUNDEF(VT);
4299   // fold (srl x, 0) -> x
4300   if (N1C && N1C->isNullValue())
4301     return N0;
4302   // if (srl x, c) is known to be zero, return 0
4303   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4304                                    APInt::getAllOnesValue(OpSizeInBits)))
4305     return DAG.getConstant(0, VT);
4306
4307   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4308   if (N1C && N0.getOpcode() == ISD::SRL) {
4309     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4310       uint64_t c1 = N01C->getZExtValue();
4311       uint64_t c2 = N1C->getZExtValue();
4312       if (c1 + c2 >= OpSizeInBits)
4313         return DAG.getConstant(0, VT);
4314       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4315                          DAG.getConstant(c1 + c2, N1.getValueType()));
4316     }
4317   }
4318
4319   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4320   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4321       N0.getOperand(0).getOpcode() == ISD::SRL &&
4322       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4323     uint64_t c1 =
4324       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4325     uint64_t c2 = N1C->getZExtValue();
4326     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4327     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4328     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4329     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4330     if (c1 + OpSizeInBits == InnerShiftSize) {
4331       if (c1 + c2 >= InnerShiftSize)
4332         return DAG.getConstant(0, VT);
4333       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4334                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4335                                      N0.getOperand(0)->getOperand(0),
4336                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4337     }
4338   }
4339
4340   // fold (srl (shl x, c), c) -> (and x, cst2)
4341   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4342     unsigned BitSize = N0.getScalarValueSizeInBits();
4343     if (BitSize <= 64) {
4344       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4345       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4346                          DAG.getConstant(~0ULL >> ShAmt, VT));
4347     }
4348   }
4349
4350   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4351   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4352     // Shifting in all undef bits?
4353     EVT SmallVT = N0.getOperand(0).getValueType();
4354     unsigned BitSize = SmallVT.getScalarSizeInBits();
4355     if (N1C->getZExtValue() >= BitSize)
4356       return DAG.getUNDEF(VT);
4357
4358     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4359       uint64_t ShiftAmt = N1C->getZExtValue();
4360       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4361                                        N0.getOperand(0),
4362                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4363       AddToWorkList(SmallShift.getNode());
4364       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4365       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4366                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4367                          DAG.getConstant(Mask, VT));
4368     }
4369   }
4370
4371   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4372   // bit, which is unmodified by sra.
4373   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4374     if (N0.getOpcode() == ISD::SRA)
4375       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4376   }
4377
4378   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4379   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4380       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4381     APInt KnownZero, KnownOne;
4382     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4383
4384     // If any of the input bits are KnownOne, then the input couldn't be all
4385     // zeros, thus the result of the srl will always be zero.
4386     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4387
4388     // If all of the bits input the to ctlz node are known to be zero, then
4389     // the result of the ctlz is "32" and the result of the shift is one.
4390     APInt UnknownBits = ~KnownZero;
4391     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4392
4393     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4394     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4395       // Okay, we know that only that the single bit specified by UnknownBits
4396       // could be set on input to the CTLZ node. If this bit is set, the SRL
4397       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4398       // to an SRL/XOR pair, which is likely to simplify more.
4399       unsigned ShAmt = UnknownBits.countTrailingZeros();
4400       SDValue Op = N0.getOperand(0);
4401
4402       if (ShAmt) {
4403         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4404                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4405         AddToWorkList(Op.getNode());
4406       }
4407
4408       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4409                          Op, DAG.getConstant(1, VT));
4410     }
4411   }
4412
4413   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4414   if (N1.getOpcode() == ISD::TRUNCATE &&
4415       N1.getOperand(0).getOpcode() == ISD::AND) {
4416     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4417     if (NewOp1.getNode())
4418       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4419   }
4420
4421   // fold operands of srl based on knowledge that the low bits are not
4422   // demanded.
4423   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4424     return SDValue(N, 0);
4425
4426   if (N1C) {
4427     SDValue NewSRL = visitShiftByConstant(N, N1C);
4428     if (NewSRL.getNode())
4429       return NewSRL;
4430   }
4431
4432   // Attempt to convert a srl of a load into a narrower zero-extending load.
4433   SDValue NarrowLoad = ReduceLoadWidth(N);
4434   if (NarrowLoad.getNode())
4435     return NarrowLoad;
4436
4437   // Here is a common situation. We want to optimize:
4438   //
4439   //   %a = ...
4440   //   %b = and i32 %a, 2
4441   //   %c = srl i32 %b, 1
4442   //   brcond i32 %c ...
4443   //
4444   // into
4445   //
4446   //   %a = ...
4447   //   %b = and %a, 2
4448   //   %c = setcc eq %b, 0
4449   //   brcond %c ...
4450   //
4451   // However when after the source operand of SRL is optimized into AND, the SRL
4452   // itself may not be optimized further. Look for it and add the BRCOND into
4453   // the worklist.
4454   if (N->hasOneUse()) {
4455     SDNode *Use = *N->use_begin();
4456     if (Use->getOpcode() == ISD::BRCOND)
4457       AddToWorkList(Use);
4458     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4459       // Also look pass the truncate.
4460       Use = *Use->use_begin();
4461       if (Use->getOpcode() == ISD::BRCOND)
4462         AddToWorkList(Use);
4463     }
4464   }
4465
4466   return SDValue();
4467 }
4468
4469 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4470   SDValue N0 = N->getOperand(0);
4471   EVT VT = N->getValueType(0);
4472
4473   // fold (ctlz c1) -> c2
4474   if (isa<ConstantSDNode>(N0))
4475     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4476   return SDValue();
4477 }
4478
4479 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4480   SDValue N0 = N->getOperand(0);
4481   EVT VT = N->getValueType(0);
4482
4483   // fold (ctlz_zero_undef c1) -> c2
4484   if (isa<ConstantSDNode>(N0))
4485     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4486   return SDValue();
4487 }
4488
4489 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4490   SDValue N0 = N->getOperand(0);
4491   EVT VT = N->getValueType(0);
4492
4493   // fold (cttz c1) -> c2
4494   if (isa<ConstantSDNode>(N0))
4495     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4496   return SDValue();
4497 }
4498
4499 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4500   SDValue N0 = N->getOperand(0);
4501   EVT VT = N->getValueType(0);
4502
4503   // fold (cttz_zero_undef c1) -> c2
4504   if (isa<ConstantSDNode>(N0))
4505     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4506   return SDValue();
4507 }
4508
4509 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4510   SDValue N0 = N->getOperand(0);
4511   EVT VT = N->getValueType(0);
4512
4513   // fold (ctpop c1) -> c2
4514   if (isa<ConstantSDNode>(N0))
4515     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4516   return SDValue();
4517 }
4518
4519 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4520   SDValue N0 = N->getOperand(0);
4521   SDValue N1 = N->getOperand(1);
4522   SDValue N2 = N->getOperand(2);
4523   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4524   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4525   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4526   EVT VT = N->getValueType(0);
4527   EVT VT0 = N0.getValueType();
4528
4529   // fold (select C, X, X) -> X
4530   if (N1 == N2)
4531     return N1;
4532   // fold (select true, X, Y) -> X
4533   if (N0C && !N0C->isNullValue())
4534     return N1;
4535   // fold (select false, X, Y) -> Y
4536   if (N0C && N0C->isNullValue())
4537     return N2;
4538   // fold (select C, 1, X) -> (or C, X)
4539   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4540     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4541   // fold (select C, 0, 1) -> (xor C, 1)
4542   if (VT.isInteger() &&
4543       (VT0 == MVT::i1 ||
4544        (VT0.isInteger() &&
4545         TLI.getBooleanContents(false) ==
4546         TargetLowering::ZeroOrOneBooleanContent)) &&
4547       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4548     SDValue XORNode;
4549     if (VT == VT0)
4550       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4551                          N0, DAG.getConstant(1, VT0));
4552     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4553                           N0, DAG.getConstant(1, VT0));
4554     AddToWorkList(XORNode.getNode());
4555     if (VT.bitsGT(VT0))
4556       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4557     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4558   }
4559   // fold (select C, 0, X) -> (and (not C), X)
4560   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4561     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4562     AddToWorkList(NOTNode.getNode());
4563     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4564   }
4565   // fold (select C, X, 1) -> (or (not C), X)
4566   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4567     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4568     AddToWorkList(NOTNode.getNode());
4569     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4570   }
4571   // fold (select C, X, 0) -> (and C, X)
4572   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4573     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4574   // fold (select X, X, Y) -> (or X, Y)
4575   // fold (select X, 1, Y) -> (or X, Y)
4576   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4577     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4578   // fold (select X, Y, X) -> (and X, Y)
4579   // fold (select X, Y, 0) -> (and X, Y)
4580   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4581     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4582
4583   // If we can fold this based on the true/false value, do so.
4584   if (SimplifySelectOps(N, N1, N2))
4585     return SDValue(N, 0);  // Don't revisit N.
4586
4587   // fold selects based on a setcc into other things, such as min/max/abs
4588   if (N0.getOpcode() == ISD::SETCC) {
4589     // FIXME:
4590     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4591     // having to say they don't support SELECT_CC on every type the DAG knows
4592     // about, since there is no way to mark an opcode illegal at all value types
4593     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4594         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4595       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4596                          N0.getOperand(0), N0.getOperand(1),
4597                          N1, N2, N0.getOperand(2));
4598     return SimplifySelect(SDLoc(N), N0, N1, N2);
4599   }
4600
4601   return SDValue();
4602 }
4603
4604 static
4605 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4606   SDLoc DL(N);
4607   EVT LoVT, HiVT;
4608   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4609
4610   // Split the inputs.
4611   SDValue Lo, Hi, LL, LH, RL, RH;
4612   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4613   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4614
4615   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4616   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4617
4618   return std::make_pair(Lo, Hi);
4619 }
4620
4621 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4622   SDValue N0 = N->getOperand(0);
4623   SDValue N1 = N->getOperand(1);
4624   SDValue N2 = N->getOperand(2);
4625   SDLoc DL(N);
4626
4627   // Canonicalize integer abs.
4628   // vselect (setg[te] X,  0),  X, -X ->
4629   // vselect (setgt    X, -1),  X, -X ->
4630   // vselect (setl[te] X,  0), -X,  X ->
4631   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4632   if (N0.getOpcode() == ISD::SETCC) {
4633     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4634     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4635     bool isAbs = false;
4636     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4637
4638     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4639          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4640         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4641       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4642     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4643              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4644       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4645
4646     if (isAbs) {
4647       EVT VT = LHS.getValueType();
4648       SDValue Shift = DAG.getNode(
4649           ISD::SRA, DL, VT, LHS,
4650           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4651       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4652       AddToWorkList(Shift.getNode());
4653       AddToWorkList(Add.getNode());
4654       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4655     }
4656   }
4657
4658   // If the VSELECT result requires splitting and the mask is provided by a
4659   // SETCC, then split both nodes and its operands before legalization. This
4660   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4661   // and enables future optimizations (e.g. min/max pattern matching on X86).
4662   if (N0.getOpcode() == ISD::SETCC) {
4663     EVT VT = N->getValueType(0);
4664
4665     // Check if any splitting is required.
4666     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4667         TargetLowering::TypeSplitVector)
4668       return SDValue();
4669
4670     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4671     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4672     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4673     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4674
4675     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4676     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4677
4678     // Add the new VSELECT nodes to the work list in case they need to be split
4679     // again.
4680     AddToWorkList(Lo.getNode());
4681     AddToWorkList(Hi.getNode());
4682
4683     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4684   }
4685
4686   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4687   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4688     return N1;
4689   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4690   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4691     return N2;
4692
4693   return SDValue();
4694 }
4695
4696 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4697   SDValue N0 = N->getOperand(0);
4698   SDValue N1 = N->getOperand(1);
4699   SDValue N2 = N->getOperand(2);
4700   SDValue N3 = N->getOperand(3);
4701   SDValue N4 = N->getOperand(4);
4702   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4703
4704   // fold select_cc lhs, rhs, x, x, cc -> x
4705   if (N2 == N3)
4706     return N2;
4707
4708   // Determine if the condition we're dealing with is constant
4709   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4710                               N0, N1, CC, SDLoc(N), false);
4711   if (SCC.getNode()) {
4712     AddToWorkList(SCC.getNode());
4713
4714     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4715       if (!SCCC->isNullValue())
4716         return N2;    // cond always true -> true val
4717       else
4718         return N3;    // cond always false -> false val
4719     }
4720
4721     // Fold to a simpler select_cc
4722     if (SCC.getOpcode() == ISD::SETCC)
4723       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4724                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4725                          SCC.getOperand(2));
4726   }
4727
4728   // If we can fold this based on the true/false value, do so.
4729   if (SimplifySelectOps(N, N2, N3))
4730     return SDValue(N, 0);  // Don't revisit N.
4731
4732   // fold select_cc into other things, such as min/max/abs
4733   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4734 }
4735
4736 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4737   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4738                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4739                        SDLoc(N));
4740 }
4741
4742 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4743 // dag node into a ConstantSDNode or a build_vector of constants.
4744 // This function is called by the DAGCombiner when visiting sext/zext/aext
4745 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4746 // Vector extends are not folded if operations are legal; this is to
4747 // avoid introducing illegal build_vector dag nodes.
4748 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4749                                          SelectionDAG &DAG, bool LegalTypes,
4750                                          bool LegalOperations) {
4751   unsigned Opcode = N->getOpcode();
4752   SDValue N0 = N->getOperand(0);
4753   EVT VT = N->getValueType(0);
4754
4755   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4756          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4757
4758   // fold (sext c1) -> c1
4759   // fold (zext c1) -> c1
4760   // fold (aext c1) -> c1
4761   if (isa<ConstantSDNode>(N0))
4762     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4763
4764   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4765   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4766   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4767   EVT SVT = VT.getScalarType();
4768   if (!(VT.isVector() &&
4769       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4770       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4771     return 0;
4772   
4773   // We can fold this node into a build_vector.
4774   unsigned VTBits = SVT.getSizeInBits();
4775   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4776   unsigned ShAmt = VTBits - EVTBits;
4777   SmallVector<SDValue, 8> Elts;
4778   unsigned NumElts = N0->getNumOperands();
4779   SDLoc DL(N);
4780
4781   for (unsigned i=0; i != NumElts; ++i) {
4782     SDValue Op = N0->getOperand(i);
4783     if (Op->getOpcode() == ISD::UNDEF) {
4784       Elts.push_back(DAG.getUNDEF(SVT));
4785       continue;
4786     }
4787
4788     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4789     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4790     if (Opcode == ISD::SIGN_EXTEND)
4791       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4792                                      SVT));
4793     else
4794       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4795                                      SVT));
4796   }
4797
4798   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4799 }
4800
4801 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4802 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4803 // transformation. Returns true if extension are possible and the above
4804 // mentioned transformation is profitable.
4805 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4806                                     unsigned ExtOpc,
4807                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4808                                     const TargetLowering &TLI) {
4809   bool HasCopyToRegUses = false;
4810   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4811   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4812                             UE = N0.getNode()->use_end();
4813        UI != UE; ++UI) {
4814     SDNode *User = *UI;
4815     if (User == N)
4816       continue;
4817     if (UI.getUse().getResNo() != N0.getResNo())
4818       continue;
4819     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4820     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4821       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4822       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4823         // Sign bits will be lost after a zext.
4824         return false;
4825       bool Add = false;
4826       for (unsigned i = 0; i != 2; ++i) {
4827         SDValue UseOp = User->getOperand(i);
4828         if (UseOp == N0)
4829           continue;
4830         if (!isa<ConstantSDNode>(UseOp))
4831           return false;
4832         Add = true;
4833       }
4834       if (Add)
4835         ExtendNodes.push_back(User);
4836       continue;
4837     }
4838     // If truncates aren't free and there are users we can't
4839     // extend, it isn't worthwhile.
4840     if (!isTruncFree)
4841       return false;
4842     // Remember if this value is live-out.
4843     if (User->getOpcode() == ISD::CopyToReg)
4844       HasCopyToRegUses = true;
4845   }
4846
4847   if (HasCopyToRegUses) {
4848     bool BothLiveOut = false;
4849     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4850          UI != UE; ++UI) {
4851       SDUse &Use = UI.getUse();
4852       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4853         BothLiveOut = true;
4854         break;
4855       }
4856     }
4857     if (BothLiveOut)
4858       // Both unextended and extended values are live out. There had better be
4859       // a good reason for the transformation.
4860       return ExtendNodes.size();
4861   }
4862   return true;
4863 }
4864
4865 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4866                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4867                                   ISD::NodeType ExtType) {
4868   // Extend SetCC uses if necessary.
4869   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4870     SDNode *SetCC = SetCCs[i];
4871     SmallVector<SDValue, 4> Ops;
4872
4873     for (unsigned j = 0; j != 2; ++j) {
4874       SDValue SOp = SetCC->getOperand(j);
4875       if (SOp == Trunc)
4876         Ops.push_back(ExtLoad);
4877       else
4878         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4879     }
4880
4881     Ops.push_back(SetCC->getOperand(2));
4882     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4883                                  &Ops[0], Ops.size()));
4884   }
4885 }
4886
4887 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4888   SDValue N0 = N->getOperand(0);
4889   EVT VT = N->getValueType(0);
4890
4891   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4892                                               LegalOperations))
4893     return SDValue(Res, 0);
4894
4895   // fold (sext (sext x)) -> (sext x)
4896   // fold (sext (aext x)) -> (sext x)
4897   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4898     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4899                        N0.getOperand(0));
4900
4901   if (N0.getOpcode() == ISD::TRUNCATE) {
4902     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4903     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4904     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4905     if (NarrowLoad.getNode()) {
4906       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4907       if (NarrowLoad.getNode() != N0.getNode()) {
4908         CombineTo(N0.getNode(), NarrowLoad);
4909         // CombineTo deleted the truncate, if needed, but not what's under it.
4910         AddToWorkList(oye);
4911       }
4912       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4913     }
4914
4915     // See if the value being truncated is already sign extended.  If so, just
4916     // eliminate the trunc/sext pair.
4917     SDValue Op = N0.getOperand(0);
4918     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4919     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4920     unsigned DestBits = VT.getScalarType().getSizeInBits();
4921     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4922
4923     if (OpBits == DestBits) {
4924       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4925       // bits, it is already ready.
4926       if (NumSignBits > DestBits-MidBits)
4927         return Op;
4928     } else if (OpBits < DestBits) {
4929       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4930       // bits, just sext from i32.
4931       if (NumSignBits > OpBits-MidBits)
4932         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4933     } else {
4934       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4935       // bits, just truncate to i32.
4936       if (NumSignBits > OpBits-MidBits)
4937         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4938     }
4939
4940     // fold (sext (truncate x)) -> (sextinreg x).
4941     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4942                                                  N0.getValueType())) {
4943       if (OpBits < DestBits)
4944         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4945       else if (OpBits > DestBits)
4946         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4947       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4948                          DAG.getValueType(N0.getValueType()));
4949     }
4950   }
4951
4952   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4953   // None of the supported targets knows how to perform load and sign extend
4954   // on vectors in one instruction.  We only perform this transformation on
4955   // scalars.
4956   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4957       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4958        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4959     bool DoXform = true;
4960     SmallVector<SDNode*, 4> SetCCs;
4961     if (!N0.hasOneUse())
4962       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4963     if (DoXform) {
4964       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4965       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4966                                        LN0->getChain(),
4967                                        LN0->getBasePtr(), N0.getValueType(),
4968                                        LN0->getMemOperand());
4969       CombineTo(N, ExtLoad);
4970       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4971                                   N0.getValueType(), ExtLoad);
4972       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4973       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4974                       ISD::SIGN_EXTEND);
4975       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4976     }
4977   }
4978
4979   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4980   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4981   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4982       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4983     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4984     EVT MemVT = LN0->getMemoryVT();
4985     if ((!LegalOperations && !LN0->isVolatile()) ||
4986         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4987       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4988                                        LN0->getChain(),
4989                                        LN0->getBasePtr(), MemVT,
4990                                        LN0->getMemOperand());
4991       CombineTo(N, ExtLoad);
4992       CombineTo(N0.getNode(),
4993                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4994                             N0.getValueType(), ExtLoad),
4995                 ExtLoad.getValue(1));
4996       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4997     }
4998   }
4999
5000   // fold (sext (and/or/xor (load x), cst)) ->
5001   //      (and/or/xor (sextload x), (sext cst))
5002   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5003        N0.getOpcode() == ISD::XOR) &&
5004       isa<LoadSDNode>(N0.getOperand(0)) &&
5005       N0.getOperand(1).getOpcode() == ISD::Constant &&
5006       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5007       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5008     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5009     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
5010       bool DoXform = true;
5011       SmallVector<SDNode*, 4> SetCCs;
5012       if (!N0.hasOneUse())
5013         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5014                                           SetCCs, TLI);
5015       if (DoXform) {
5016         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5017                                          LN0->getChain(), LN0->getBasePtr(),
5018                                          LN0->getMemoryVT(),
5019                                          LN0->getMemOperand());
5020         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5021         Mask = Mask.sext(VT.getSizeInBits());
5022         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5023                                   ExtLoad, DAG.getConstant(Mask, VT));
5024         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5025                                     SDLoc(N0.getOperand(0)),
5026                                     N0.getOperand(0).getValueType(), ExtLoad);
5027         CombineTo(N, And);
5028         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5029         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5030                         ISD::SIGN_EXTEND);
5031         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5032       }
5033     }
5034   }
5035
5036   if (N0.getOpcode() == ISD::SETCC) {
5037     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5038     // Only do this before legalize for now.
5039     if (VT.isVector() && !LegalOperations &&
5040         TLI.getBooleanContents(true) ==
5041           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5042       EVT N0VT = N0.getOperand(0).getValueType();
5043       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5044       // of the same size as the compared operands. Only optimize sext(setcc())
5045       // if this is the case.
5046       EVT SVT = getSetCCResultType(N0VT);
5047
5048       // We know that the # elements of the results is the same as the
5049       // # elements of the compare (and the # elements of the compare result
5050       // for that matter).  Check to see that they are the same size.  If so,
5051       // we know that the element size of the sext'd result matches the
5052       // element size of the compare operands.
5053       if (VT.getSizeInBits() == SVT.getSizeInBits())
5054         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5055                              N0.getOperand(1),
5056                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5057
5058       // If the desired elements are smaller or larger than the source
5059       // elements we can use a matching integer vector type and then
5060       // truncate/sign extend
5061       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5062       if (SVT == MatchingVectorType) {
5063         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5064                                N0.getOperand(0), N0.getOperand(1),
5065                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5066         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5067       }
5068     }
5069
5070     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5071     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5072     SDValue NegOne =
5073       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5074     SDValue SCC =
5075       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5076                        NegOne, DAG.getConstant(0, VT),
5077                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5078     if (SCC.getNode()) return SCC;
5079
5080     if (!VT.isVector()) {
5081       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5082       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5083         SDLoc DL(N);
5084         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5085         SDValue SetCC = DAG.getSetCC(DL,
5086                                      SetCCVT,
5087                                      N0.getOperand(0), N0.getOperand(1), CC);
5088         EVT SelectVT = getSetCCResultType(VT);
5089         return DAG.getSelect(DL, VT,
5090                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5091                              NegOne, DAG.getConstant(0, VT));
5092
5093       }
5094     }
5095   }
5096
5097   // fold (sext x) -> (zext x) if the sign bit is known zero.
5098   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5099       DAG.SignBitIsZero(N0))
5100     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5101
5102   return SDValue();
5103 }
5104
5105 // isTruncateOf - If N is a truncate of some other value, return true, record
5106 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5107 // This function computes KnownZero to avoid a duplicated call to
5108 // ComputeMaskedBits in the caller.
5109 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5110                          APInt &KnownZero) {
5111   APInt KnownOne;
5112   if (N->getOpcode() == ISD::TRUNCATE) {
5113     Op = N->getOperand(0);
5114     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5115     return true;
5116   }
5117
5118   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5119       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5120     return false;
5121
5122   SDValue Op0 = N->getOperand(0);
5123   SDValue Op1 = N->getOperand(1);
5124   assert(Op0.getValueType() == Op1.getValueType());
5125
5126   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5127   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5128   if (COp0 && COp0->isNullValue())
5129     Op = Op1;
5130   else if (COp1 && COp1->isNullValue())
5131     Op = Op0;
5132   else
5133     return false;
5134
5135   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5136
5137   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5138     return false;
5139
5140   return true;
5141 }
5142
5143 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5144   SDValue N0 = N->getOperand(0);
5145   EVT VT = N->getValueType(0);
5146
5147   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5148                                               LegalOperations))
5149     return SDValue(Res, 0);
5150
5151   // fold (zext (zext x)) -> (zext x)
5152   // fold (zext (aext x)) -> (zext x)
5153   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5154     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5155                        N0.getOperand(0));
5156
5157   // fold (zext (truncate x)) -> (zext x) or
5158   //      (zext (truncate x)) -> (truncate x)
5159   // This is valid when the truncated bits of x are already zero.
5160   // FIXME: We should extend this to work for vectors too.
5161   SDValue Op;
5162   APInt KnownZero;
5163   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5164     APInt TruncatedBits =
5165       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5166       APInt(Op.getValueSizeInBits(), 0) :
5167       APInt::getBitsSet(Op.getValueSizeInBits(),
5168                         N0.getValueSizeInBits(),
5169                         std::min(Op.getValueSizeInBits(),
5170                                  VT.getSizeInBits()));
5171     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5172       if (VT.bitsGT(Op.getValueType()))
5173         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5174       if (VT.bitsLT(Op.getValueType()))
5175         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5176
5177       return Op;
5178     }
5179   }
5180
5181   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5182   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5183   if (N0.getOpcode() == ISD::TRUNCATE) {
5184     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5185     if (NarrowLoad.getNode()) {
5186       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5187       if (NarrowLoad.getNode() != N0.getNode()) {
5188         CombineTo(N0.getNode(), NarrowLoad);
5189         // CombineTo deleted the truncate, if needed, but not what's under it.
5190         AddToWorkList(oye);
5191       }
5192       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5193     }
5194   }
5195
5196   // fold (zext (truncate x)) -> (and x, mask)
5197   if (N0.getOpcode() == ISD::TRUNCATE &&
5198       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5199
5200     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5201     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5202     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5203     if (NarrowLoad.getNode()) {
5204       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5205       if (NarrowLoad.getNode() != N0.getNode()) {
5206         CombineTo(N0.getNode(), NarrowLoad);
5207         // CombineTo deleted the truncate, if needed, but not what's under it.
5208         AddToWorkList(oye);
5209       }
5210       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5211     }
5212
5213     SDValue Op = N0.getOperand(0);
5214     if (Op.getValueType().bitsLT(VT)) {
5215       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5216       AddToWorkList(Op.getNode());
5217     } else if (Op.getValueType().bitsGT(VT)) {
5218       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5219       AddToWorkList(Op.getNode());
5220     }
5221     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5222                                   N0.getValueType().getScalarType());
5223   }
5224
5225   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5226   // if either of the casts is not free.
5227   if (N0.getOpcode() == ISD::AND &&
5228       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5229       N0.getOperand(1).getOpcode() == ISD::Constant &&
5230       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5231                            N0.getValueType()) ||
5232        !TLI.isZExtFree(N0.getValueType(), VT))) {
5233     SDValue X = N0.getOperand(0).getOperand(0);
5234     if (X.getValueType().bitsLT(VT)) {
5235       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5236     } else if (X.getValueType().bitsGT(VT)) {
5237       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5238     }
5239     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5240     Mask = Mask.zext(VT.getSizeInBits());
5241     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5242                        X, DAG.getConstant(Mask, VT));
5243   }
5244
5245   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5246   // None of the supported targets knows how to perform load and vector_zext
5247   // on vectors in one instruction.  We only perform this transformation on
5248   // scalars.
5249   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5250       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5251        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5252     bool DoXform = true;
5253     SmallVector<SDNode*, 4> SetCCs;
5254     if (!N0.hasOneUse())
5255       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5256     if (DoXform) {
5257       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5258       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5259                                        LN0->getChain(),
5260                                        LN0->getBasePtr(), N0.getValueType(),
5261                                        LN0->getMemOperand());
5262       CombineTo(N, ExtLoad);
5263       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5264                                   N0.getValueType(), ExtLoad);
5265       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5266
5267       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5268                       ISD::ZERO_EXTEND);
5269       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5270     }
5271   }
5272
5273   // fold (zext (and/or/xor (load x), cst)) ->
5274   //      (and/or/xor (zextload x), (zext cst))
5275   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5276        N0.getOpcode() == ISD::XOR) &&
5277       isa<LoadSDNode>(N0.getOperand(0)) &&
5278       N0.getOperand(1).getOpcode() == ISD::Constant &&
5279       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5280       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5281     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5282     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5283       bool DoXform = true;
5284       SmallVector<SDNode*, 4> SetCCs;
5285       if (!N0.hasOneUse())
5286         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5287                                           SetCCs, TLI);
5288       if (DoXform) {
5289         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5290                                          LN0->getChain(), LN0->getBasePtr(),
5291                                          LN0->getMemoryVT(),
5292                                          LN0->getMemOperand());
5293         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5294         Mask = Mask.zext(VT.getSizeInBits());
5295         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5296                                   ExtLoad, DAG.getConstant(Mask, VT));
5297         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5298                                     SDLoc(N0.getOperand(0)),
5299                                     N0.getOperand(0).getValueType(), ExtLoad);
5300         CombineTo(N, And);
5301         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5302         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5303                         ISD::ZERO_EXTEND);
5304         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5305       }
5306     }
5307   }
5308
5309   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5310   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5311   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5312       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5313     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5314     EVT MemVT = LN0->getMemoryVT();
5315     if ((!LegalOperations && !LN0->isVolatile()) ||
5316         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5317       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5318                                        LN0->getChain(),
5319                                        LN0->getBasePtr(), MemVT,
5320                                        LN0->getMemOperand());
5321       CombineTo(N, ExtLoad);
5322       CombineTo(N0.getNode(),
5323                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5324                             ExtLoad),
5325                 ExtLoad.getValue(1));
5326       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5327     }
5328   }
5329
5330   if (N0.getOpcode() == ISD::SETCC) {
5331     if (!LegalOperations && VT.isVector() &&
5332         N0.getValueType().getVectorElementType() == MVT::i1) {
5333       EVT N0VT = N0.getOperand(0).getValueType();
5334       if (getSetCCResultType(N0VT) == N0.getValueType())
5335         return SDValue();
5336
5337       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5338       // Only do this before legalize for now.
5339       EVT EltVT = VT.getVectorElementType();
5340       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5341                                     DAG.getConstant(1, EltVT));
5342       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5343         // We know that the # elements of the results is the same as the
5344         // # elements of the compare (and the # elements of the compare result
5345         // for that matter).  Check to see that they are the same size.  If so,
5346         // we know that the element size of the sext'd result matches the
5347         // element size of the compare operands.
5348         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5349                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5350                                          N0.getOperand(1),
5351                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5352                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5353                                        &OneOps[0], OneOps.size()));
5354
5355       // If the desired elements are smaller or larger than the source
5356       // elements we can use a matching integer vector type and then
5357       // truncate/sign extend
5358       EVT MatchingElementType =
5359         EVT::getIntegerVT(*DAG.getContext(),
5360                           N0VT.getScalarType().getSizeInBits());
5361       EVT MatchingVectorType =
5362         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5363                          N0VT.getVectorNumElements());
5364       SDValue VsetCC =
5365         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5366                       N0.getOperand(1),
5367                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5368       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5369                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5370                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5371                                      &OneOps[0], OneOps.size()));
5372     }
5373
5374     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5375     SDValue SCC =
5376       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5377                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5378                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5379     if (SCC.getNode()) return SCC;
5380   }
5381
5382   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5383   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5384       isa<ConstantSDNode>(N0.getOperand(1)) &&
5385       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5386       N0.hasOneUse()) {
5387     SDValue ShAmt = N0.getOperand(1);
5388     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5389     if (N0.getOpcode() == ISD::SHL) {
5390       SDValue InnerZExt = N0.getOperand(0);
5391       // If the original shl may be shifting out bits, do not perform this
5392       // transformation.
5393       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5394         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5395       if (ShAmtVal > KnownZeroBits)
5396         return SDValue();
5397     }
5398
5399     SDLoc DL(N);
5400
5401     // Ensure that the shift amount is wide enough for the shifted value.
5402     if (VT.getSizeInBits() >= 256)
5403       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5404
5405     return DAG.getNode(N0.getOpcode(), DL, VT,
5406                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5407                        ShAmt);
5408   }
5409
5410   return SDValue();
5411 }
5412
5413 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5414   SDValue N0 = N->getOperand(0);
5415   EVT VT = N->getValueType(0);
5416
5417   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5418                                               LegalOperations))
5419     return SDValue(Res, 0);
5420
5421   // fold (aext (aext x)) -> (aext x)
5422   // fold (aext (zext x)) -> (zext x)
5423   // fold (aext (sext x)) -> (sext x)
5424   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5425       N0.getOpcode() == ISD::ZERO_EXTEND ||
5426       N0.getOpcode() == ISD::SIGN_EXTEND)
5427     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5428
5429   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5430   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5431   if (N0.getOpcode() == ISD::TRUNCATE) {
5432     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5433     if (NarrowLoad.getNode()) {
5434       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5435       if (NarrowLoad.getNode() != N0.getNode()) {
5436         CombineTo(N0.getNode(), NarrowLoad);
5437         // CombineTo deleted the truncate, if needed, but not what's under it.
5438         AddToWorkList(oye);
5439       }
5440       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5441     }
5442   }
5443
5444   // fold (aext (truncate x))
5445   if (N0.getOpcode() == ISD::TRUNCATE) {
5446     SDValue TruncOp = N0.getOperand(0);
5447     if (TruncOp.getValueType() == VT)
5448       return TruncOp; // x iff x size == zext size.
5449     if (TruncOp.getValueType().bitsGT(VT))
5450       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5451     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5452   }
5453
5454   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5455   // if the trunc is not free.
5456   if (N0.getOpcode() == ISD::AND &&
5457       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5458       N0.getOperand(1).getOpcode() == ISD::Constant &&
5459       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5460                           N0.getValueType())) {
5461     SDValue X = N0.getOperand(0).getOperand(0);
5462     if (X.getValueType().bitsLT(VT)) {
5463       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5464     } else if (X.getValueType().bitsGT(VT)) {
5465       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5466     }
5467     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5468     Mask = Mask.zext(VT.getSizeInBits());
5469     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5470                        X, DAG.getConstant(Mask, VT));
5471   }
5472
5473   // fold (aext (load x)) -> (aext (truncate (extload x)))
5474   // None of the supported targets knows how to perform load and any_ext
5475   // on vectors in one instruction.  We only perform this transformation on
5476   // scalars.
5477   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5478       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5479        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5480     bool DoXform = true;
5481     SmallVector<SDNode*, 4> SetCCs;
5482     if (!N0.hasOneUse())
5483       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5484     if (DoXform) {
5485       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5486       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5487                                        LN0->getChain(),
5488                                        LN0->getBasePtr(), N0.getValueType(),
5489                                        LN0->getMemOperand());
5490       CombineTo(N, ExtLoad);
5491       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5492                                   N0.getValueType(), ExtLoad);
5493       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5494       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5495                       ISD::ANY_EXTEND);
5496       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5497     }
5498   }
5499
5500   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5501   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5502   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5503   if (N0.getOpcode() == ISD::LOAD &&
5504       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5505       N0.hasOneUse()) {
5506     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5507     EVT MemVT = LN0->getMemoryVT();
5508     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5509                                      VT, LN0->getChain(), LN0->getBasePtr(),
5510                                      MemVT, LN0->getMemOperand());
5511     CombineTo(N, ExtLoad);
5512     CombineTo(N0.getNode(),
5513               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5514                           N0.getValueType(), ExtLoad),
5515               ExtLoad.getValue(1));
5516     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5517   }
5518
5519   if (N0.getOpcode() == ISD::SETCC) {
5520     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5521     // Only do this before legalize for now.
5522     if (VT.isVector() && !LegalOperations) {
5523       EVT N0VT = N0.getOperand(0).getValueType();
5524         // We know that the # elements of the results is the same as the
5525         // # elements of the compare (and the # elements of the compare result
5526         // for that matter).  Check to see that they are the same size.  If so,
5527         // we know that the element size of the sext'd result matches the
5528         // element size of the compare operands.
5529       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5530         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5531                              N0.getOperand(1),
5532                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5533       // If the desired elements are smaller or larger than the source
5534       // elements we can use a matching integer vector type and then
5535       // truncate/sign extend
5536       else {
5537         EVT MatchingElementType =
5538           EVT::getIntegerVT(*DAG.getContext(),
5539                             N0VT.getScalarType().getSizeInBits());
5540         EVT MatchingVectorType =
5541           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5542                            N0VT.getVectorNumElements());
5543         SDValue VsetCC =
5544           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5545                         N0.getOperand(1),
5546                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5547         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5548       }
5549     }
5550
5551     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5552     SDValue SCC =
5553       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5554                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5555                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5556     if (SCC.getNode())
5557       return SCC;
5558   }
5559
5560   return SDValue();
5561 }
5562
5563 /// GetDemandedBits - See if the specified operand can be simplified with the
5564 /// knowledge that only the bits specified by Mask are used.  If so, return the
5565 /// simpler operand, otherwise return a null SDValue.
5566 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5567   switch (V.getOpcode()) {
5568   default: break;
5569   case ISD::Constant: {
5570     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5571     assert(CV != 0 && "Const value should be ConstSDNode.");
5572     const APInt &CVal = CV->getAPIntValue();
5573     APInt NewVal = CVal & Mask;
5574     if (NewVal != CVal)
5575       return DAG.getConstant(NewVal, V.getValueType());
5576     break;
5577   }
5578   case ISD::OR:
5579   case ISD::XOR:
5580     // If the LHS or RHS don't contribute bits to the or, drop them.
5581     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5582       return V.getOperand(1);
5583     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5584       return V.getOperand(0);
5585     break;
5586   case ISD::SRL:
5587     // Only look at single-use SRLs.
5588     if (!V.getNode()->hasOneUse())
5589       break;
5590     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5591       // See if we can recursively simplify the LHS.
5592       unsigned Amt = RHSC->getZExtValue();
5593
5594       // Watch out for shift count overflow though.
5595       if (Amt >= Mask.getBitWidth()) break;
5596       APInt NewMask = Mask << Amt;
5597       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5598       if (SimplifyLHS.getNode())
5599         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5600                            SimplifyLHS, V.getOperand(1));
5601     }
5602   }
5603   return SDValue();
5604 }
5605
5606 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5607 /// bits and then truncated to a narrower type and where N is a multiple
5608 /// of number of bits of the narrower type, transform it to a narrower load
5609 /// from address + N / num of bits of new type. If the result is to be
5610 /// extended, also fold the extension to form a extending load.
5611 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5612   unsigned Opc = N->getOpcode();
5613
5614   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5615   SDValue N0 = N->getOperand(0);
5616   EVT VT = N->getValueType(0);
5617   EVT ExtVT = VT;
5618
5619   // This transformation isn't valid for vector loads.
5620   if (VT.isVector())
5621     return SDValue();
5622
5623   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5624   // extended to VT.
5625   if (Opc == ISD::SIGN_EXTEND_INREG) {
5626     ExtType = ISD::SEXTLOAD;
5627     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5628   } else if (Opc == ISD::SRL) {
5629     // Another special-case: SRL is basically zero-extending a narrower value.
5630     ExtType = ISD::ZEXTLOAD;
5631     N0 = SDValue(N, 0);
5632     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5633     if (!N01) return SDValue();
5634     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5635                               VT.getSizeInBits() - N01->getZExtValue());
5636   }
5637   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5638     return SDValue();
5639
5640   unsigned EVTBits = ExtVT.getSizeInBits();
5641
5642   // Do not generate loads of non-round integer types since these can
5643   // be expensive (and would be wrong if the type is not byte sized).
5644   if (!ExtVT.isRound())
5645     return SDValue();
5646
5647   unsigned ShAmt = 0;
5648   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5649     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5650       ShAmt = N01->getZExtValue();
5651       // Is the shift amount a multiple of size of VT?
5652       if ((ShAmt & (EVTBits-1)) == 0) {
5653         N0 = N0.getOperand(0);
5654         // Is the load width a multiple of size of VT?
5655         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5656           return SDValue();
5657       }
5658
5659       // At this point, we must have a load or else we can't do the transform.
5660       if (!isa<LoadSDNode>(N0)) return SDValue();
5661
5662       // Because a SRL must be assumed to *need* to zero-extend the high bits
5663       // (as opposed to anyext the high bits), we can't combine the zextload
5664       // lowering of SRL and an sextload.
5665       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5666         return SDValue();
5667
5668       // If the shift amount is larger than the input type then we're not
5669       // accessing any of the loaded bytes.  If the load was a zextload/extload
5670       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5671       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5672         return SDValue();
5673     }
5674   }
5675
5676   // If the load is shifted left (and the result isn't shifted back right),
5677   // we can fold the truncate through the shift.
5678   unsigned ShLeftAmt = 0;
5679   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5680       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5681     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5682       ShLeftAmt = N01->getZExtValue();
5683       N0 = N0.getOperand(0);
5684     }
5685   }
5686
5687   // If we haven't found a load, we can't narrow it.  Don't transform one with
5688   // multiple uses, this would require adding a new load.
5689   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5690     return SDValue();
5691
5692   // Don't change the width of a volatile load.
5693   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5694   if (LN0->isVolatile())
5695     return SDValue();
5696
5697   // Verify that we are actually reducing a load width here.
5698   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5699     return SDValue();
5700
5701   // For the transform to be legal, the load must produce only two values
5702   // (the value loaded and the chain).  Don't transform a pre-increment
5703   // load, for example, which produces an extra value.  Otherwise the
5704   // transformation is not equivalent, and the downstream logic to replace
5705   // uses gets things wrong.
5706   if (LN0->getNumValues() > 2)
5707     return SDValue();
5708
5709   // If the load that we're shrinking is an extload and we're not just
5710   // discarding the extension we can't simply shrink the load. Bail.
5711   // TODO: It would be possible to merge the extensions in some cases.
5712   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5713       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5714     return SDValue();
5715
5716   EVT PtrType = N0.getOperand(1).getValueType();
5717
5718   if (PtrType == MVT::Untyped || PtrType.isExtended())
5719     // It's not possible to generate a constant of extended or untyped type.
5720     return SDValue();
5721
5722   // For big endian targets, we need to adjust the offset to the pointer to
5723   // load the correct bytes.
5724   if (TLI.isBigEndian()) {
5725     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5726     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5727     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5728   }
5729
5730   uint64_t PtrOff = ShAmt / 8;
5731   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5732   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5733                                PtrType, LN0->getBasePtr(),
5734                                DAG.getConstant(PtrOff, PtrType));
5735   AddToWorkList(NewPtr.getNode());
5736
5737   SDValue Load;
5738   if (ExtType == ISD::NON_EXTLOAD)
5739     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5740                         LN0->getPointerInfo().getWithOffset(PtrOff),
5741                         LN0->isVolatile(), LN0->isNonTemporal(),
5742                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5743   else
5744     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5745                           LN0->getPointerInfo().getWithOffset(PtrOff),
5746                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5747                           NewAlign, LN0->getTBAAInfo());
5748
5749   // Replace the old load's chain with the new load's chain.
5750   WorkListRemover DeadNodes(*this);
5751   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5752
5753   // Shift the result left, if we've swallowed a left shift.
5754   SDValue Result = Load;
5755   if (ShLeftAmt != 0) {
5756     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5757     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5758       ShImmTy = VT;
5759     // If the shift amount is as large as the result size (but, presumably,
5760     // no larger than the source) then the useful bits of the result are
5761     // zero; we can't simply return the shortened shift, because the result
5762     // of that operation is undefined.
5763     if (ShLeftAmt >= VT.getSizeInBits())
5764       Result = DAG.getConstant(0, VT);
5765     else
5766       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5767                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5768   }
5769
5770   // Return the new loaded value.
5771   return Result;
5772 }
5773
5774 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5775   SDValue N0 = N->getOperand(0);
5776   SDValue N1 = N->getOperand(1);
5777   EVT VT = N->getValueType(0);
5778   EVT EVT = cast<VTSDNode>(N1)->getVT();
5779   unsigned VTBits = VT.getScalarType().getSizeInBits();
5780   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5781
5782   // fold (sext_in_reg c1) -> c1
5783   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5784     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5785
5786   // If the input is already sign extended, just drop the extension.
5787   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5788     return N0;
5789
5790   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5791   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5792       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5793     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5794                        N0.getOperand(0), N1);
5795
5796   // fold (sext_in_reg (sext x)) -> (sext x)
5797   // fold (sext_in_reg (aext x)) -> (sext x)
5798   // if x is small enough.
5799   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5800     SDValue N00 = N0.getOperand(0);
5801     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5802         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5803       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5804   }
5805
5806   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5807   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5808     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5809
5810   // fold operands of sext_in_reg based on knowledge that the top bits are not
5811   // demanded.
5812   if (SimplifyDemandedBits(SDValue(N, 0)))
5813     return SDValue(N, 0);
5814
5815   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5816   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5817   SDValue NarrowLoad = ReduceLoadWidth(N);
5818   if (NarrowLoad.getNode())
5819     return NarrowLoad;
5820
5821   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5822   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5823   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5824   if (N0.getOpcode() == ISD::SRL) {
5825     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5826       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5827         // We can turn this into an SRA iff the input to the SRL is already sign
5828         // extended enough.
5829         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5830         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5831           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5832                              N0.getOperand(0), N0.getOperand(1));
5833       }
5834   }
5835
5836   // fold (sext_inreg (extload x)) -> (sextload x)
5837   if (ISD::isEXTLoad(N0.getNode()) &&
5838       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5839       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5840       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5841        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5842     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5843     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5844                                      LN0->getChain(),
5845                                      LN0->getBasePtr(), EVT,
5846                                      LN0->getMemOperand());
5847     CombineTo(N, ExtLoad);
5848     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5849     AddToWorkList(ExtLoad.getNode());
5850     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5851   }
5852   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5853   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5854       N0.hasOneUse() &&
5855       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5856       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5857        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5858     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5859     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5860                                      LN0->getChain(),
5861                                      LN0->getBasePtr(), EVT,
5862                                      LN0->getMemOperand());
5863     CombineTo(N, ExtLoad);
5864     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5865     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5866   }
5867
5868   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5869   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5870     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5871                                        N0.getOperand(1), false);
5872     if (BSwap.getNode() != 0)
5873       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5874                          BSwap, N1);
5875   }
5876
5877   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5878   // into a build_vector.
5879   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5880     SmallVector<SDValue, 8> Elts;
5881     unsigned NumElts = N0->getNumOperands();
5882     unsigned ShAmt = VTBits - EVTBits;
5883
5884     for (unsigned i = 0; i != NumElts; ++i) {
5885       SDValue Op = N0->getOperand(i);
5886       if (Op->getOpcode() == ISD::UNDEF) {
5887         Elts.push_back(Op);
5888         continue;
5889       }
5890
5891       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5892       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5893       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5894                                      Op.getValueType()));
5895     }
5896
5897     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5898   }
5899
5900   return SDValue();
5901 }
5902
5903 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5904   SDValue N0 = N->getOperand(0);
5905   EVT VT = N->getValueType(0);
5906   bool isLE = TLI.isLittleEndian();
5907
5908   // noop truncate
5909   if (N0.getValueType() == N->getValueType(0))
5910     return N0;
5911   // fold (truncate c1) -> c1
5912   if (isa<ConstantSDNode>(N0))
5913     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5914   // fold (truncate (truncate x)) -> (truncate x)
5915   if (N0.getOpcode() == ISD::TRUNCATE)
5916     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5917   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5918   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5919       N0.getOpcode() == ISD::SIGN_EXTEND ||
5920       N0.getOpcode() == ISD::ANY_EXTEND) {
5921     if (N0.getOperand(0).getValueType().bitsLT(VT))
5922       // if the source is smaller than the dest, we still need an extend
5923       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5924                          N0.getOperand(0));
5925     if (N0.getOperand(0).getValueType().bitsGT(VT))
5926       // if the source is larger than the dest, than we just need the truncate
5927       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5928     // if the source and dest are the same type, we can drop both the extend
5929     // and the truncate.
5930     return N0.getOperand(0);
5931   }
5932
5933   // Fold extract-and-trunc into a narrow extract. For example:
5934   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5935   //   i32 y = TRUNCATE(i64 x)
5936   //        -- becomes --
5937   //   v16i8 b = BITCAST (v2i64 val)
5938   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5939   //
5940   // Note: We only run this optimization after type legalization (which often
5941   // creates this pattern) and before operation legalization after which
5942   // we need to be more careful about the vector instructions that we generate.
5943   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5944       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5945
5946     EVT VecTy = N0.getOperand(0).getValueType();
5947     EVT ExTy = N0.getValueType();
5948     EVT TrTy = N->getValueType(0);
5949
5950     unsigned NumElem = VecTy.getVectorNumElements();
5951     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5952
5953     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5954     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5955
5956     SDValue EltNo = N0->getOperand(1);
5957     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5958       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5959       EVT IndexTy = TLI.getVectorIdxTy();
5960       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5961
5962       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5963                               NVT, N0.getOperand(0));
5964
5965       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5966                          SDLoc(N), TrTy, V,
5967                          DAG.getConstant(Index, IndexTy));
5968     }
5969   }
5970
5971   // Fold a series of buildvector, bitcast, and truncate if possible.
5972   // For example fold
5973   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5974   //   (2xi32 (buildvector x, y)).
5975   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5976       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5977       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5978       N0.getOperand(0).hasOneUse()) {
5979
5980     SDValue BuildVect = N0.getOperand(0);
5981     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5982     EVT TruncVecEltTy = VT.getVectorElementType();
5983
5984     // Check that the element types match.
5985     if (BuildVectEltTy == TruncVecEltTy) {
5986       // Now we only need to compute the offset of the truncated elements.
5987       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5988       unsigned TruncVecNumElts = VT.getVectorNumElements();
5989       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5990
5991       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5992              "Invalid number of elements");
5993
5994       SmallVector<SDValue, 8> Opnds;
5995       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5996         Opnds.push_back(BuildVect.getOperand(i));
5997
5998       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5999                          Opnds.size());
6000     }
6001   }
6002
6003   // See if we can simplify the input to this truncate through knowledge that
6004   // only the low bits are being used.
6005   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6006   // Currently we only perform this optimization on scalars because vectors
6007   // may have different active low bits.
6008   if (!VT.isVector()) {
6009     SDValue Shorter =
6010       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6011                                                VT.getSizeInBits()));
6012     if (Shorter.getNode())
6013       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6014   }
6015   // fold (truncate (load x)) -> (smaller load x)
6016   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6017   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6018     SDValue Reduced = ReduceLoadWidth(N);
6019     if (Reduced.getNode())
6020       return Reduced;
6021     // Handle the case where the load remains an extending load even
6022     // after truncation.
6023     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6024       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6025       if (!LN0->isVolatile() &&
6026           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6027         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6028                                          VT, LN0->getChain(), LN0->getBasePtr(),
6029                                          LN0->getMemoryVT(),
6030                                          LN0->getMemOperand());
6031         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6032         return NewLoad;
6033       }
6034     }
6035   }
6036   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6037   // where ... are all 'undef'.
6038   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6039     SmallVector<EVT, 8> VTs;
6040     SDValue V;
6041     unsigned Idx = 0;
6042     unsigned NumDefs = 0;
6043
6044     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6045       SDValue X = N0.getOperand(i);
6046       if (X.getOpcode() != ISD::UNDEF) {
6047         V = X;
6048         Idx = i;
6049         NumDefs++;
6050       }
6051       // Stop if more than one members are non-undef.
6052       if (NumDefs > 1)
6053         break;
6054       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6055                                      VT.getVectorElementType(),
6056                                      X.getValueType().getVectorNumElements()));
6057     }
6058
6059     if (NumDefs == 0)
6060       return DAG.getUNDEF(VT);
6061
6062     if (NumDefs == 1) {
6063       assert(V.getNode() && "The single defined operand is empty!");
6064       SmallVector<SDValue, 8> Opnds;
6065       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6066         if (i != Idx) {
6067           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6068           continue;
6069         }
6070         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6071         AddToWorkList(NV.getNode());
6072         Opnds.push_back(NV);
6073       }
6074       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6075                          &Opnds[0], Opnds.size());
6076     }
6077   }
6078
6079   // Simplify the operands using demanded-bits information.
6080   if (!VT.isVector() &&
6081       SimplifyDemandedBits(SDValue(N, 0)))
6082     return SDValue(N, 0);
6083
6084   return SDValue();
6085 }
6086
6087 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6088   SDValue Elt = N->getOperand(i);
6089   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6090     return Elt.getNode();
6091   return Elt.getOperand(Elt.getResNo()).getNode();
6092 }
6093
6094 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6095 /// if load locations are consecutive.
6096 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6097   assert(N->getOpcode() == ISD::BUILD_PAIR);
6098
6099   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6100   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6101   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6102       LD1->getAddressSpace() != LD2->getAddressSpace())
6103     return SDValue();
6104   EVT LD1VT = LD1->getValueType(0);
6105
6106   if (ISD::isNON_EXTLoad(LD2) &&
6107       LD2->hasOneUse() &&
6108       // If both are volatile this would reduce the number of volatile loads.
6109       // If one is volatile it might be ok, but play conservative and bail out.
6110       !LD1->isVolatile() &&
6111       !LD2->isVolatile() &&
6112       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6113     unsigned Align = LD1->getAlignment();
6114     unsigned NewAlign = TLI.getDataLayout()->
6115       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6116
6117     if (NewAlign <= Align &&
6118         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6119       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6120                          LD1->getBasePtr(), LD1->getPointerInfo(),
6121                          false, false, false, Align);
6122   }
6123
6124   return SDValue();
6125 }
6126
6127 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6128   SDValue N0 = N->getOperand(0);
6129   EVT VT = N->getValueType(0);
6130
6131   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6132   // Only do this before legalize, since afterward the target may be depending
6133   // on the bitconvert.
6134   // First check to see if this is all constant.
6135   if (!LegalTypes &&
6136       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6137       VT.isVector()) {
6138     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6139
6140     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6141     assert(!DestEltVT.isVector() &&
6142            "Element type of vector ValueType must not be vector!");
6143     if (isSimple)
6144       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6145   }
6146
6147   // If the input is a constant, let getNode fold it.
6148   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6149     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6150     if (Res.getNode() != N) {
6151       if (!LegalOperations ||
6152           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6153         return Res;
6154
6155       // Folding it resulted in an illegal node, and it's too late to
6156       // do that. Clean up the old node and forego the transformation.
6157       // Ideally this won't happen very often, because instcombine
6158       // and the earlier dagcombine runs (where illegal nodes are
6159       // permitted) should have folded most of them already.
6160       DAG.DeleteNode(Res.getNode());
6161     }
6162   }
6163
6164   // (conv (conv x, t1), t2) -> (conv x, t2)
6165   if (N0.getOpcode() == ISD::BITCAST)
6166     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6167                        N0.getOperand(0));
6168
6169   // fold (conv (load x)) -> (load (conv*)x)
6170   // If the resultant load doesn't need a higher alignment than the original!
6171   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6172       // Do not change the width of a volatile load.
6173       !cast<LoadSDNode>(N0)->isVolatile() &&
6174       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6175       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6176     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6177     unsigned Align = TLI.getDataLayout()->
6178       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6179     unsigned OrigAlign = LN0->getAlignment();
6180
6181     if (Align <= OrigAlign) {
6182       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6183                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6184                                  LN0->isVolatile(), LN0->isNonTemporal(),
6185                                  LN0->isInvariant(), OrigAlign,
6186                                  LN0->getTBAAInfo());
6187       AddToWorkList(N);
6188       CombineTo(N0.getNode(),
6189                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6190                             N0.getValueType(), Load),
6191                 Load.getValue(1));
6192       return Load;
6193     }
6194   }
6195
6196   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6197   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6198   // This often reduces constant pool loads.
6199   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6200        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6201       N0.getNode()->hasOneUse() && VT.isInteger() &&
6202       !VT.isVector() && !N0.getValueType().isVector()) {
6203     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6204                                   N0.getOperand(0));
6205     AddToWorkList(NewConv.getNode());
6206
6207     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6208     if (N0.getOpcode() == ISD::FNEG)
6209       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6210                          NewConv, DAG.getConstant(SignBit, VT));
6211     assert(N0.getOpcode() == ISD::FABS);
6212     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6213                        NewConv, DAG.getConstant(~SignBit, VT));
6214   }
6215
6216   // fold (bitconvert (fcopysign cst, x)) ->
6217   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6218   // Note that we don't handle (copysign x, cst) because this can always be
6219   // folded to an fneg or fabs.
6220   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6221       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6222       VT.isInteger() && !VT.isVector()) {
6223     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6224     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6225     if (isTypeLegal(IntXVT)) {
6226       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6227                               IntXVT, N0.getOperand(1));
6228       AddToWorkList(X.getNode());
6229
6230       // If X has a different width than the result/lhs, sext it or truncate it.
6231       unsigned VTWidth = VT.getSizeInBits();
6232       if (OrigXWidth < VTWidth) {
6233         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6234         AddToWorkList(X.getNode());
6235       } else if (OrigXWidth > VTWidth) {
6236         // To get the sign bit in the right place, we have to shift it right
6237         // before truncating.
6238         X = DAG.getNode(ISD::SRL, SDLoc(X),
6239                         X.getValueType(), X,
6240                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6241         AddToWorkList(X.getNode());
6242         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6243         AddToWorkList(X.getNode());
6244       }
6245
6246       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6247       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6248                       X, DAG.getConstant(SignBit, VT));
6249       AddToWorkList(X.getNode());
6250
6251       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6252                                 VT, N0.getOperand(0));
6253       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6254                         Cst, DAG.getConstant(~SignBit, VT));
6255       AddToWorkList(Cst.getNode());
6256
6257       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6258     }
6259   }
6260
6261   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6262   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6263     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6264     if (CombineLD.getNode())
6265       return CombineLD;
6266   }
6267
6268   return SDValue();
6269 }
6270
6271 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6272   EVT VT = N->getValueType(0);
6273   return CombineConsecutiveLoads(N, VT);
6274 }
6275
6276 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6277 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6278 /// destination element value type.
6279 SDValue DAGCombiner::
6280 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6281   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6282
6283   // If this is already the right type, we're done.
6284   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6285
6286   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6287   unsigned DstBitSize = DstEltVT.getSizeInBits();
6288
6289   // If this is a conversion of N elements of one type to N elements of another
6290   // type, convert each element.  This handles FP<->INT cases.
6291   if (SrcBitSize == DstBitSize) {
6292     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6293                               BV->getValueType(0).getVectorNumElements());
6294
6295     // Due to the FP element handling below calling this routine recursively,
6296     // we can end up with a scalar-to-vector node here.
6297     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6298       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6299                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6300                                      DstEltVT, BV->getOperand(0)));
6301
6302     SmallVector<SDValue, 8> Ops;
6303     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6304       SDValue Op = BV->getOperand(i);
6305       // If the vector element type is not legal, the BUILD_VECTOR operands
6306       // are promoted and implicitly truncated.  Make that explicit here.
6307       if (Op.getValueType() != SrcEltVT)
6308         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6309       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6310                                 DstEltVT, Op));
6311       AddToWorkList(Ops.back().getNode());
6312     }
6313     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6314                        &Ops[0], Ops.size());
6315   }
6316
6317   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6318   // handle annoying details of growing/shrinking FP values, we convert them to
6319   // int first.
6320   if (SrcEltVT.isFloatingPoint()) {
6321     // Convert the input float vector to a int vector where the elements are the
6322     // same sizes.
6323     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6324     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6325     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6326     SrcEltVT = IntVT;
6327   }
6328
6329   // Now we know the input is an integer vector.  If the output is a FP type,
6330   // convert to integer first, then to FP of the right size.
6331   if (DstEltVT.isFloatingPoint()) {
6332     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6333     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6334     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6335
6336     // Next, convert to FP elements of the same size.
6337     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6338   }
6339
6340   // Okay, we know the src/dst types are both integers of differing types.
6341   // Handling growing first.
6342   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6343   if (SrcBitSize < DstBitSize) {
6344     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6345
6346     SmallVector<SDValue, 8> Ops;
6347     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6348          i += NumInputsPerOutput) {
6349       bool isLE = TLI.isLittleEndian();
6350       APInt NewBits = APInt(DstBitSize, 0);
6351       bool EltIsUndef = true;
6352       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6353         // Shift the previously computed bits over.
6354         NewBits <<= SrcBitSize;
6355         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6356         if (Op.getOpcode() == ISD::UNDEF) continue;
6357         EltIsUndef = false;
6358
6359         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6360                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6361       }
6362
6363       if (EltIsUndef)
6364         Ops.push_back(DAG.getUNDEF(DstEltVT));
6365       else
6366         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6367     }
6368
6369     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6370     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6371                        &Ops[0], Ops.size());
6372   }
6373
6374   // Finally, this must be the case where we are shrinking elements: each input
6375   // turns into multiple outputs.
6376   bool isS2V = ISD::isScalarToVector(BV);
6377   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6378   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6379                             NumOutputsPerInput*BV->getNumOperands());
6380   SmallVector<SDValue, 8> Ops;
6381
6382   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6383     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6384       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6385         Ops.push_back(DAG.getUNDEF(DstEltVT));
6386       continue;
6387     }
6388
6389     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6390                   getAPIntValue().zextOrTrunc(SrcBitSize);
6391
6392     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6393       APInt ThisVal = OpVal.trunc(DstBitSize);
6394       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6395       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6396         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6397         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6398                            Ops[0]);
6399       OpVal = OpVal.lshr(DstBitSize);
6400     }
6401
6402     // For big endian targets, swap the order of the pieces of each element.
6403     if (TLI.isBigEndian())
6404       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6405   }
6406
6407   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6408                      &Ops[0], Ops.size());
6409 }
6410
6411 SDValue DAGCombiner::visitFADD(SDNode *N) {
6412   SDValue N0 = N->getOperand(0);
6413   SDValue N1 = N->getOperand(1);
6414   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6415   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6416   EVT VT = N->getValueType(0);
6417
6418   // fold vector ops
6419   if (VT.isVector()) {
6420     SDValue FoldedVOp = SimplifyVBinOp(N);
6421     if (FoldedVOp.getNode()) return FoldedVOp;
6422   }
6423
6424   // fold (fadd c1, c2) -> c1 + c2
6425   if (N0CFP && N1CFP)
6426     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6427   // canonicalize constant to RHS
6428   if (N0CFP && !N1CFP)
6429     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6430   // fold (fadd A, 0) -> A
6431   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6432       N1CFP->getValueAPF().isZero())
6433     return N0;
6434   // fold (fadd A, (fneg B)) -> (fsub A, B)
6435   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6436     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6437     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6438                        GetNegatedExpression(N1, DAG, LegalOperations));
6439   // fold (fadd (fneg A), B) -> (fsub B, A)
6440   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6441     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6442     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6443                        GetNegatedExpression(N0, DAG, LegalOperations));
6444
6445   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6446   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6447       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6448       isa<ConstantFPSDNode>(N0.getOperand(1)))
6449     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6450                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6451                                    N0.getOperand(1), N1));
6452
6453   // No FP constant should be created after legalization as Instruction
6454   // Selection pass has hard time in dealing with FP constant.
6455   //
6456   // We don't need test this condition for transformation like following, as
6457   // the DAG being transformed implies it is legal to take FP constant as
6458   // operand.
6459   //
6460   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6461   //
6462   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6463
6464   // If allow, fold (fadd (fneg x), x) -> 0.0
6465   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6466       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6467     return DAG.getConstantFP(0.0, VT);
6468
6469     // If allow, fold (fadd x, (fneg x)) -> 0.0
6470   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6471       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6472     return DAG.getConstantFP(0.0, VT);
6473
6474   // In unsafe math mode, we can fold chains of FADD's of the same value
6475   // into multiplications.  This transform is not safe in general because
6476   // we are reducing the number of rounding steps.
6477   if (DAG.getTarget().Options.UnsafeFPMath &&
6478       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6479       !N0CFP && !N1CFP) {
6480     if (N0.getOpcode() == ISD::FMUL) {
6481       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6482       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6483
6484       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6485       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6486         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6487                                      SDValue(CFP00, 0),
6488                                      DAG.getConstantFP(1.0, VT));
6489         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6490                            N1, NewCFP);
6491       }
6492
6493       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6494       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6495         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6496                                      SDValue(CFP01, 0),
6497                                      DAG.getConstantFP(1.0, VT));
6498         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6499                            N1, NewCFP);
6500       }
6501
6502       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6503       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6504           N1.getOperand(0) == N1.getOperand(1) &&
6505           N0.getOperand(1) == N1.getOperand(0)) {
6506         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6507                                      SDValue(CFP00, 0),
6508                                      DAG.getConstantFP(2.0, VT));
6509         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6510                            N0.getOperand(1), NewCFP);
6511       }
6512
6513       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6514       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6515           N1.getOperand(0) == N1.getOperand(1) &&
6516           N0.getOperand(0) == N1.getOperand(0)) {
6517         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6518                                      SDValue(CFP01, 0),
6519                                      DAG.getConstantFP(2.0, VT));
6520         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6521                            N0.getOperand(0), NewCFP);
6522       }
6523     }
6524
6525     if (N1.getOpcode() == ISD::FMUL) {
6526       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6527       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6528
6529       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6530       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6531         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6532                                      SDValue(CFP10, 0),
6533                                      DAG.getConstantFP(1.0, VT));
6534         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6535                            N0, NewCFP);
6536       }
6537
6538       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6539       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6540         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6541                                      SDValue(CFP11, 0),
6542                                      DAG.getConstantFP(1.0, VT));
6543         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6544                            N0, NewCFP);
6545       }
6546
6547
6548       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6549       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6550           N0.getOperand(0) == N0.getOperand(1) &&
6551           N1.getOperand(1) == N0.getOperand(0)) {
6552         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6553                                      SDValue(CFP10, 0),
6554                                      DAG.getConstantFP(2.0, VT));
6555         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6556                            N1.getOperand(1), NewCFP);
6557       }
6558
6559       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6560       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6561           N0.getOperand(0) == N0.getOperand(1) &&
6562           N1.getOperand(0) == N0.getOperand(0)) {
6563         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6564                                      SDValue(CFP11, 0),
6565                                      DAG.getConstantFP(2.0, VT));
6566         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6567                            N1.getOperand(0), NewCFP);
6568       }
6569     }
6570
6571     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6572       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6573       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6574       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6575           (N0.getOperand(0) == N1))
6576         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6577                            N1, DAG.getConstantFP(3.0, VT));
6578     }
6579
6580     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6581       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6582       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6583       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6584           N1.getOperand(0) == N0)
6585         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6586                            N0, DAG.getConstantFP(3.0, VT));
6587     }
6588
6589     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6590     if (AllowNewFpConst &&
6591         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6592         N0.getOperand(0) == N0.getOperand(1) &&
6593         N1.getOperand(0) == N1.getOperand(1) &&
6594         N0.getOperand(0) == N1.getOperand(0))
6595       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6596                          N0.getOperand(0),
6597                          DAG.getConstantFP(4.0, VT));
6598   }
6599
6600   // FADD -> FMA combines:
6601   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6602        DAG.getTarget().Options.UnsafeFPMath) &&
6603       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6604       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6605
6606     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6607     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6608       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6609                          N0.getOperand(0), N0.getOperand(1), N1);
6610
6611     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6612     // Note: Commutes FADD operands.
6613     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6614       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6615                          N1.getOperand(0), N1.getOperand(1), N0);
6616   }
6617
6618   return SDValue();
6619 }
6620
6621 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6622   SDValue N0 = N->getOperand(0);
6623   SDValue N1 = N->getOperand(1);
6624   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6625   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6626   EVT VT = N->getValueType(0);
6627   SDLoc dl(N);
6628
6629   // fold vector ops
6630   if (VT.isVector()) {
6631     SDValue FoldedVOp = SimplifyVBinOp(N);
6632     if (FoldedVOp.getNode()) return FoldedVOp;
6633   }
6634
6635   // fold (fsub c1, c2) -> c1-c2
6636   if (N0CFP && N1CFP)
6637     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6638   // fold (fsub A, 0) -> A
6639   if (DAG.getTarget().Options.UnsafeFPMath &&
6640       N1CFP && N1CFP->getValueAPF().isZero())
6641     return N0;
6642   // fold (fsub 0, B) -> -B
6643   if (DAG.getTarget().Options.UnsafeFPMath &&
6644       N0CFP && N0CFP->getValueAPF().isZero()) {
6645     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6646       return GetNegatedExpression(N1, DAG, LegalOperations);
6647     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6648       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6649   }
6650   // fold (fsub A, (fneg B)) -> (fadd A, B)
6651   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6652     return DAG.getNode(ISD::FADD, dl, VT, N0,
6653                        GetNegatedExpression(N1, DAG, LegalOperations));
6654
6655   // If 'unsafe math' is enabled, fold
6656   //    (fsub x, x) -> 0.0 &
6657   //    (fsub x, (fadd x, y)) -> (fneg y) &
6658   //    (fsub x, (fadd y, x)) -> (fneg y)
6659   if (DAG.getTarget().Options.UnsafeFPMath) {
6660     if (N0 == N1)
6661       return DAG.getConstantFP(0.0f, VT);
6662
6663     if (N1.getOpcode() == ISD::FADD) {
6664       SDValue N10 = N1->getOperand(0);
6665       SDValue N11 = N1->getOperand(1);
6666
6667       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6668                                           &DAG.getTarget().Options))
6669         return GetNegatedExpression(N11, DAG, LegalOperations);
6670
6671       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6672                                           &DAG.getTarget().Options))
6673         return GetNegatedExpression(N10, DAG, LegalOperations);
6674     }
6675   }
6676
6677   // FSUB -> FMA combines:
6678   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6679        DAG.getTarget().Options.UnsafeFPMath) &&
6680       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6681       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6682
6683     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6684     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6685       return DAG.getNode(ISD::FMA, dl, VT,
6686                          N0.getOperand(0), N0.getOperand(1),
6687                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6688
6689     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6690     // Note: Commutes FSUB operands.
6691     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6692       return DAG.getNode(ISD::FMA, dl, VT,
6693                          DAG.getNode(ISD::FNEG, dl, VT,
6694                          N1.getOperand(0)),
6695                          N1.getOperand(1), N0);
6696
6697     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6698     if (N0.getOpcode() == ISD::FNEG &&
6699         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6700         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6701       SDValue N00 = N0.getOperand(0).getOperand(0);
6702       SDValue N01 = N0.getOperand(0).getOperand(1);
6703       return DAG.getNode(ISD::FMA, dl, VT,
6704                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6705                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6706     }
6707   }
6708
6709   return SDValue();
6710 }
6711
6712 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6713   SDValue N0 = N->getOperand(0);
6714   SDValue N1 = N->getOperand(1);
6715   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6716   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6717   EVT VT = N->getValueType(0);
6718   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6719
6720   // fold vector ops
6721   if (VT.isVector()) {
6722     SDValue FoldedVOp = SimplifyVBinOp(N);
6723     if (FoldedVOp.getNode()) return FoldedVOp;
6724   }
6725
6726   // fold (fmul c1, c2) -> c1*c2
6727   if (N0CFP && N1CFP)
6728     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6729   // canonicalize constant to RHS
6730   if (N0CFP && !N1CFP)
6731     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6732   // fold (fmul A, 0) -> 0
6733   if (DAG.getTarget().Options.UnsafeFPMath &&
6734       N1CFP && N1CFP->getValueAPF().isZero())
6735     return N1;
6736   // fold (fmul A, 0) -> 0, vector edition.
6737   if (DAG.getTarget().Options.UnsafeFPMath &&
6738       ISD::isBuildVectorAllZeros(N1.getNode()))
6739     return N1;
6740   // fold (fmul A, 1.0) -> A
6741   if (N1CFP && N1CFP->isExactlyValue(1.0))
6742     return N0;
6743   // fold (fmul X, 2.0) -> (fadd X, X)
6744   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6745     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6746   // fold (fmul X, -1.0) -> (fneg X)
6747   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6748     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6749       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6750
6751   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6752   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6753                                        &DAG.getTarget().Options)) {
6754     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6755                                          &DAG.getTarget().Options)) {
6756       // Both can be negated for free, check to see if at least one is cheaper
6757       // negated.
6758       if (LHSNeg == 2 || RHSNeg == 2)
6759         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6760                            GetNegatedExpression(N0, DAG, LegalOperations),
6761                            GetNegatedExpression(N1, DAG, LegalOperations));
6762     }
6763   }
6764
6765   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6766   if (DAG.getTarget().Options.UnsafeFPMath &&
6767       N1CFP && N0.getOpcode() == ISD::FMUL &&
6768       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6769     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6770                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6771                                    N0.getOperand(1), N1));
6772
6773   return SDValue();
6774 }
6775
6776 SDValue DAGCombiner::visitFMA(SDNode *N) {
6777   SDValue N0 = N->getOperand(0);
6778   SDValue N1 = N->getOperand(1);
6779   SDValue N2 = N->getOperand(2);
6780   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6781   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6782   EVT VT = N->getValueType(0);
6783   SDLoc dl(N);
6784
6785   if (DAG.getTarget().Options.UnsafeFPMath) {
6786     if (N0CFP && N0CFP->isZero())
6787       return N2;
6788     if (N1CFP && N1CFP->isZero())
6789       return N2;
6790   }
6791   if (N0CFP && N0CFP->isExactlyValue(1.0))
6792     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6793   if (N1CFP && N1CFP->isExactlyValue(1.0))
6794     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6795
6796   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6797   if (N0CFP && !N1CFP)
6798     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6799
6800   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6801   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6802       N2.getOpcode() == ISD::FMUL &&
6803       N0 == N2.getOperand(0) &&
6804       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6805     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6806                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6807   }
6808
6809
6810   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6811   if (DAG.getTarget().Options.UnsafeFPMath &&
6812       N0.getOpcode() == ISD::FMUL && N1CFP &&
6813       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6814     return DAG.getNode(ISD::FMA, dl, VT,
6815                        N0.getOperand(0),
6816                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6817                        N2);
6818   }
6819
6820   // (fma x, 1, y) -> (fadd x, y)
6821   // (fma x, -1, y) -> (fadd (fneg x), y)
6822   if (N1CFP) {
6823     if (N1CFP->isExactlyValue(1.0))
6824       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6825
6826     if (N1CFP->isExactlyValue(-1.0) &&
6827         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6828       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6829       AddToWorkList(RHSNeg.getNode());
6830       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6831     }
6832   }
6833
6834   // (fma x, c, x) -> (fmul x, (c+1))
6835   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6836     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6837                        DAG.getNode(ISD::FADD, dl, VT,
6838                                    N1, DAG.getConstantFP(1.0, VT)));
6839
6840   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6841   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6842       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6843     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6844                        DAG.getNode(ISD::FADD, dl, VT,
6845                                    N1, DAG.getConstantFP(-1.0, VT)));
6846
6847
6848   return SDValue();
6849 }
6850
6851 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6852   SDValue N0 = N->getOperand(0);
6853   SDValue N1 = N->getOperand(1);
6854   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6855   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6856   EVT VT = N->getValueType(0);
6857   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6858
6859   // fold vector ops
6860   if (VT.isVector()) {
6861     SDValue FoldedVOp = SimplifyVBinOp(N);
6862     if (FoldedVOp.getNode()) return FoldedVOp;
6863   }
6864
6865   // fold (fdiv c1, c2) -> c1/c2
6866   if (N0CFP && N1CFP)
6867     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6868
6869   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6870   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6871     // Compute the reciprocal 1.0 / c2.
6872     APFloat N1APF = N1CFP->getValueAPF();
6873     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6874     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6875     // Only do the transform if the reciprocal is a legal fp immediate that
6876     // isn't too nasty (eg NaN, denormal, ...).
6877     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6878         (!LegalOperations ||
6879          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6880          // backend)... we should handle this gracefully after Legalize.
6881          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6882          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6883          TLI.isFPImmLegal(Recip, VT)))
6884       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6885                          DAG.getConstantFP(Recip, VT));
6886   }
6887
6888   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6889   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6890                                        &DAG.getTarget().Options)) {
6891     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6892                                          &DAG.getTarget().Options)) {
6893       // Both can be negated for free, check to see if at least one is cheaper
6894       // negated.
6895       if (LHSNeg == 2 || RHSNeg == 2)
6896         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6897                            GetNegatedExpression(N0, DAG, LegalOperations),
6898                            GetNegatedExpression(N1, DAG, LegalOperations));
6899     }
6900   }
6901
6902   return SDValue();
6903 }
6904
6905 SDValue DAGCombiner::visitFREM(SDNode *N) {
6906   SDValue N0 = N->getOperand(0);
6907   SDValue N1 = N->getOperand(1);
6908   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6909   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6910   EVT VT = N->getValueType(0);
6911
6912   // fold (frem c1, c2) -> fmod(c1,c2)
6913   if (N0CFP && N1CFP)
6914     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6915
6916   return SDValue();
6917 }
6918
6919 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6920   SDValue N0 = N->getOperand(0);
6921   SDValue N1 = N->getOperand(1);
6922   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6923   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6924   EVT VT = N->getValueType(0);
6925
6926   if (N0CFP && N1CFP)  // Constant fold
6927     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6928
6929   if (N1CFP) {
6930     const APFloat& V = N1CFP->getValueAPF();
6931     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6932     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6933     if (!V.isNegative()) {
6934       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6935         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6936     } else {
6937       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6938         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6939                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6940     }
6941   }
6942
6943   // copysign(fabs(x), y) -> copysign(x, y)
6944   // copysign(fneg(x), y) -> copysign(x, y)
6945   // copysign(copysign(x,z), y) -> copysign(x, y)
6946   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6947       N0.getOpcode() == ISD::FCOPYSIGN)
6948     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6949                        N0.getOperand(0), N1);
6950
6951   // copysign(x, abs(y)) -> abs(x)
6952   if (N1.getOpcode() == ISD::FABS)
6953     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6954
6955   // copysign(x, copysign(y,z)) -> copysign(x, z)
6956   if (N1.getOpcode() == ISD::FCOPYSIGN)
6957     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6958                        N0, N1.getOperand(1));
6959
6960   // copysign(x, fp_extend(y)) -> copysign(x, y)
6961   // copysign(x, fp_round(y)) -> copysign(x, y)
6962   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6963     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6964                        N0, N1.getOperand(0));
6965
6966   return SDValue();
6967 }
6968
6969 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6970   SDValue N0 = N->getOperand(0);
6971   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6972   EVT VT = N->getValueType(0);
6973   EVT OpVT = N0.getValueType();
6974
6975   // fold (sint_to_fp c1) -> c1fp
6976   if (N0C &&
6977       // ...but only if the target supports immediate floating-point values
6978       (!LegalOperations ||
6979        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6980     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6981
6982   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6983   // but UINT_TO_FP is legal on this target, try to convert.
6984   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6985       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6986     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6987     if (DAG.SignBitIsZero(N0))
6988       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6989   }
6990
6991   // The next optimizations are desirable only if SELECT_CC can be lowered.
6992   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6993   // having to say they don't support SELECT_CC on every type the DAG knows
6994   // about, since there is no way to mark an opcode illegal at all value types
6995   // (See also visitSELECT)
6996   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6997     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6998     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6999         !VT.isVector() &&
7000         (!LegalOperations ||
7001          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7002       SDValue Ops[] =
7003         { N0.getOperand(0), N0.getOperand(1),
7004           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7005           N0.getOperand(2) };
7006       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7007     }
7008
7009     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7010     //      (select_cc x, y, 1.0, 0.0,, cc)
7011     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7012         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7013         (!LegalOperations ||
7014          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7015       SDValue Ops[] =
7016         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7017           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7018           N0.getOperand(0).getOperand(2) };
7019       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7020     }
7021   }
7022
7023   return SDValue();
7024 }
7025
7026 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7027   SDValue N0 = N->getOperand(0);
7028   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7029   EVT VT = N->getValueType(0);
7030   EVT OpVT = N0.getValueType();
7031
7032   // fold (uint_to_fp c1) -> c1fp
7033   if (N0C &&
7034       // ...but only if the target supports immediate floating-point values
7035       (!LegalOperations ||
7036        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7037     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7038
7039   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7040   // but SINT_TO_FP is legal on this target, try to convert.
7041   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7042       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7043     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7044     if (DAG.SignBitIsZero(N0))
7045       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7046   }
7047
7048   // The next optimizations are desirable only if SELECT_CC can be lowered.
7049   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7050   // having to say they don't support SELECT_CC on every type the DAG knows
7051   // about, since there is no way to mark an opcode illegal at all value types
7052   // (See also visitSELECT)
7053   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7054     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7055
7056     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7057         (!LegalOperations ||
7058          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7059       SDValue Ops[] =
7060         { N0.getOperand(0), N0.getOperand(1),
7061           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7062           N0.getOperand(2) };
7063       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7064     }
7065   }
7066
7067   return SDValue();
7068 }
7069
7070 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7071   SDValue N0 = N->getOperand(0);
7072   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7073   EVT VT = N->getValueType(0);
7074
7075   // fold (fp_to_sint c1fp) -> c1
7076   if (N0CFP)
7077     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7078
7079   return SDValue();
7080 }
7081
7082 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7083   SDValue N0 = N->getOperand(0);
7084   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7085   EVT VT = N->getValueType(0);
7086
7087   // fold (fp_to_uint c1fp) -> c1
7088   if (N0CFP)
7089     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7090
7091   return SDValue();
7092 }
7093
7094 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7095   SDValue N0 = N->getOperand(0);
7096   SDValue N1 = N->getOperand(1);
7097   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7098   EVT VT = N->getValueType(0);
7099
7100   // fold (fp_round c1fp) -> c1fp
7101   if (N0CFP)
7102     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7103
7104   // fold (fp_round (fp_extend x)) -> x
7105   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7106     return N0.getOperand(0);
7107
7108   // fold (fp_round (fp_round x)) -> (fp_round x)
7109   if (N0.getOpcode() == ISD::FP_ROUND) {
7110     // This is a value preserving truncation if both round's are.
7111     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7112                    N0.getNode()->getConstantOperandVal(1) == 1;
7113     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7114                        DAG.getIntPtrConstant(IsTrunc));
7115   }
7116
7117   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7118   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7119     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7120                               N0.getOperand(0), N1);
7121     AddToWorkList(Tmp.getNode());
7122     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7123                        Tmp, N0.getOperand(1));
7124   }
7125
7126   return SDValue();
7127 }
7128
7129 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7130   SDValue N0 = N->getOperand(0);
7131   EVT VT = N->getValueType(0);
7132   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7133   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7134
7135   // fold (fp_round_inreg c1fp) -> c1fp
7136   if (N0CFP && isTypeLegal(EVT)) {
7137     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7138     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7139   }
7140
7141   return SDValue();
7142 }
7143
7144 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7145   SDValue N0 = N->getOperand(0);
7146   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7147   EVT VT = N->getValueType(0);
7148
7149   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7150   if (N->hasOneUse() &&
7151       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7152     return SDValue();
7153
7154   // fold (fp_extend c1fp) -> c1fp
7155   if (N0CFP)
7156     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7157
7158   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7159   // value of X.
7160   if (N0.getOpcode() == ISD::FP_ROUND
7161       && N0.getNode()->getConstantOperandVal(1) == 1) {
7162     SDValue In = N0.getOperand(0);
7163     if (In.getValueType() == VT) return In;
7164     if (VT.bitsLT(In.getValueType()))
7165       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7166                          In, N0.getOperand(1));
7167     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7168   }
7169
7170   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7171   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7172       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7173        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7174     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7175     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7176                                      LN0->getChain(),
7177                                      LN0->getBasePtr(), N0.getValueType(),
7178                                      LN0->getMemOperand());
7179     CombineTo(N, ExtLoad);
7180     CombineTo(N0.getNode(),
7181               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7182                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7183               ExtLoad.getValue(1));
7184     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7185   }
7186
7187   return SDValue();
7188 }
7189
7190 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7191   SDValue N0 = N->getOperand(0);
7192   EVT VT = N->getValueType(0);
7193
7194   if (VT.isVector()) {
7195     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7196     if (FoldedVOp.getNode()) return FoldedVOp;
7197   }
7198
7199   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7200                          &DAG.getTarget().Options))
7201     return GetNegatedExpression(N0, DAG, LegalOperations);
7202
7203   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7204   // constant pool values.
7205   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7206       !VT.isVector() &&
7207       N0.getNode()->hasOneUse() &&
7208       N0.getOperand(0).getValueType().isInteger()) {
7209     SDValue Int = N0.getOperand(0);
7210     EVT IntVT = Int.getValueType();
7211     if (IntVT.isInteger() && !IntVT.isVector()) {
7212       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7213               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7214       AddToWorkList(Int.getNode());
7215       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7216                          VT, Int);
7217     }
7218   }
7219
7220   // (fneg (fmul c, x)) -> (fmul -c, x)
7221   if (N0.getOpcode() == ISD::FMUL) {
7222     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7223     if (CFP1)
7224       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7225                          N0.getOperand(0),
7226                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7227                                      N0.getOperand(1)));
7228   }
7229
7230   return SDValue();
7231 }
7232
7233 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7234   SDValue N0 = N->getOperand(0);
7235   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7236   EVT VT = N->getValueType(0);
7237
7238   // fold (fceil c1) -> fceil(c1)
7239   if (N0CFP)
7240     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7241
7242   return SDValue();
7243 }
7244
7245 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7246   SDValue N0 = N->getOperand(0);
7247   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7248   EVT VT = N->getValueType(0);
7249
7250   // fold (ftrunc c1) -> ftrunc(c1)
7251   if (N0CFP)
7252     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7253
7254   return SDValue();
7255 }
7256
7257 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7258   SDValue N0 = N->getOperand(0);
7259   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7260   EVT VT = N->getValueType(0);
7261
7262   // fold (ffloor c1) -> ffloor(c1)
7263   if (N0CFP)
7264     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7265
7266   return SDValue();
7267 }
7268
7269 SDValue DAGCombiner::visitFABS(SDNode *N) {
7270   SDValue N0 = N->getOperand(0);
7271   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7272   EVT VT = N->getValueType(0);
7273
7274   if (VT.isVector()) {
7275     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7276     if (FoldedVOp.getNode()) return FoldedVOp;
7277   }
7278
7279   // fold (fabs c1) -> fabs(c1)
7280   if (N0CFP)
7281     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7282   // fold (fabs (fabs x)) -> (fabs x)
7283   if (N0.getOpcode() == ISD::FABS)
7284     return N->getOperand(0);
7285   // fold (fabs (fneg x)) -> (fabs x)
7286   // fold (fabs (fcopysign x, y)) -> (fabs x)
7287   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7288     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7289
7290   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7291   // constant pool values.
7292   if (!TLI.isFAbsFree(VT) &&
7293       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7294       N0.getOperand(0).getValueType().isInteger() &&
7295       !N0.getOperand(0).getValueType().isVector()) {
7296     SDValue Int = N0.getOperand(0);
7297     EVT IntVT = Int.getValueType();
7298     if (IntVT.isInteger() && !IntVT.isVector()) {
7299       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7300              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7301       AddToWorkList(Int.getNode());
7302       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7303                          N->getValueType(0), Int);
7304     }
7305   }
7306
7307   return SDValue();
7308 }
7309
7310 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7311   SDValue Chain = N->getOperand(0);
7312   SDValue N1 = N->getOperand(1);
7313   SDValue N2 = N->getOperand(2);
7314
7315   // If N is a constant we could fold this into a fallthrough or unconditional
7316   // branch. However that doesn't happen very often in normal code, because
7317   // Instcombine/SimplifyCFG should have handled the available opportunities.
7318   // If we did this folding here, it would be necessary to update the
7319   // MachineBasicBlock CFG, which is awkward.
7320
7321   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7322   // on the target.
7323   if (N1.getOpcode() == ISD::SETCC &&
7324       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7325                                    N1.getOperand(0).getValueType())) {
7326     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7327                        Chain, N1.getOperand(2),
7328                        N1.getOperand(0), N1.getOperand(1), N2);
7329   }
7330
7331   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7332       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7333        (N1.getOperand(0).hasOneUse() &&
7334         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7335     SDNode *Trunc = 0;
7336     if (N1.getOpcode() == ISD::TRUNCATE) {
7337       // Look pass the truncate.
7338       Trunc = N1.getNode();
7339       N1 = N1.getOperand(0);
7340     }
7341
7342     // Match this pattern so that we can generate simpler code:
7343     //
7344     //   %a = ...
7345     //   %b = and i32 %a, 2
7346     //   %c = srl i32 %b, 1
7347     //   brcond i32 %c ...
7348     //
7349     // into
7350     //
7351     //   %a = ...
7352     //   %b = and i32 %a, 2
7353     //   %c = setcc eq %b, 0
7354     //   brcond %c ...
7355     //
7356     // This applies only when the AND constant value has one bit set and the
7357     // SRL constant is equal to the log2 of the AND constant. The back-end is
7358     // smart enough to convert the result into a TEST/JMP sequence.
7359     SDValue Op0 = N1.getOperand(0);
7360     SDValue Op1 = N1.getOperand(1);
7361
7362     if (Op0.getOpcode() == ISD::AND &&
7363         Op1.getOpcode() == ISD::Constant) {
7364       SDValue AndOp1 = Op0.getOperand(1);
7365
7366       if (AndOp1.getOpcode() == ISD::Constant) {
7367         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7368
7369         if (AndConst.isPowerOf2() &&
7370             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7371           SDValue SetCC =
7372             DAG.getSetCC(SDLoc(N),
7373                          getSetCCResultType(Op0.getValueType()),
7374                          Op0, DAG.getConstant(0, Op0.getValueType()),
7375                          ISD::SETNE);
7376
7377           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7378                                           MVT::Other, Chain, SetCC, N2);
7379           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7380           // will convert it back to (X & C1) >> C2.
7381           CombineTo(N, NewBRCond, false);
7382           // Truncate is dead.
7383           if (Trunc) {
7384             removeFromWorkList(Trunc);
7385             DAG.DeleteNode(Trunc);
7386           }
7387           // Replace the uses of SRL with SETCC
7388           WorkListRemover DeadNodes(*this);
7389           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7390           removeFromWorkList(N1.getNode());
7391           DAG.DeleteNode(N1.getNode());
7392           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7393         }
7394       }
7395     }
7396
7397     if (Trunc)
7398       // Restore N1 if the above transformation doesn't match.
7399       N1 = N->getOperand(1);
7400   }
7401
7402   // Transform br(xor(x, y)) -> br(x != y)
7403   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7404   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7405     SDNode *TheXor = N1.getNode();
7406     SDValue Op0 = TheXor->getOperand(0);
7407     SDValue Op1 = TheXor->getOperand(1);
7408     if (Op0.getOpcode() == Op1.getOpcode()) {
7409       // Avoid missing important xor optimizations.
7410       SDValue Tmp = visitXOR(TheXor);
7411       if (Tmp.getNode()) {
7412         if (Tmp.getNode() != TheXor) {
7413           DEBUG(dbgs() << "\nReplacing.8 ";
7414                 TheXor->dump(&DAG);
7415                 dbgs() << "\nWith: ";
7416                 Tmp.getNode()->dump(&DAG);
7417                 dbgs() << '\n');
7418           WorkListRemover DeadNodes(*this);
7419           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7420           removeFromWorkList(TheXor);
7421           DAG.DeleteNode(TheXor);
7422           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7423                              MVT::Other, Chain, Tmp, N2);
7424         }
7425
7426         // visitXOR has changed XOR's operands or replaced the XOR completely,
7427         // bail out.
7428         return SDValue(N, 0);
7429       }
7430     }
7431
7432     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7433       bool Equal = false;
7434       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7435         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7436             Op0.getOpcode() == ISD::XOR) {
7437           TheXor = Op0.getNode();
7438           Equal = true;
7439         }
7440
7441       EVT SetCCVT = N1.getValueType();
7442       if (LegalTypes)
7443         SetCCVT = getSetCCResultType(SetCCVT);
7444       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7445                                    SetCCVT,
7446                                    Op0, Op1,
7447                                    Equal ? ISD::SETEQ : ISD::SETNE);
7448       // Replace the uses of XOR with SETCC
7449       WorkListRemover DeadNodes(*this);
7450       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7451       removeFromWorkList(N1.getNode());
7452       DAG.DeleteNode(N1.getNode());
7453       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7454                          MVT::Other, Chain, SetCC, N2);
7455     }
7456   }
7457
7458   return SDValue();
7459 }
7460
7461 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7462 //
7463 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7464   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7465   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7466
7467   // If N is a constant we could fold this into a fallthrough or unconditional
7468   // branch. However that doesn't happen very often in normal code, because
7469   // Instcombine/SimplifyCFG should have handled the available opportunities.
7470   // If we did this folding here, it would be necessary to update the
7471   // MachineBasicBlock CFG, which is awkward.
7472
7473   // Use SimplifySetCC to simplify SETCC's.
7474   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7475                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7476                                false);
7477   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7478
7479   // fold to a simpler setcc
7480   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7481     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7482                        N->getOperand(0), Simp.getOperand(2),
7483                        Simp.getOperand(0), Simp.getOperand(1),
7484                        N->getOperand(4));
7485
7486   return SDValue();
7487 }
7488
7489 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7490 /// uses N as its base pointer and that N may be folded in the load / store
7491 /// addressing mode.
7492 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7493                                     SelectionDAG &DAG,
7494                                     const TargetLowering &TLI) {
7495   EVT VT;
7496   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7497     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7498       return false;
7499     VT = Use->getValueType(0);
7500   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7501     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7502       return false;
7503     VT = ST->getValue().getValueType();
7504   } else
7505     return false;
7506
7507   TargetLowering::AddrMode AM;
7508   if (N->getOpcode() == ISD::ADD) {
7509     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7510     if (Offset)
7511       // [reg +/- imm]
7512       AM.BaseOffs = Offset->getSExtValue();
7513     else
7514       // [reg +/- reg]
7515       AM.Scale = 1;
7516   } else if (N->getOpcode() == ISD::SUB) {
7517     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7518     if (Offset)
7519       // [reg +/- imm]
7520       AM.BaseOffs = -Offset->getSExtValue();
7521     else
7522       // [reg +/- reg]
7523       AM.Scale = 1;
7524   } else
7525     return false;
7526
7527   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7528 }
7529
7530 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7531 /// pre-indexed load / store when the base pointer is an add or subtract
7532 /// and it has other uses besides the load / store. After the
7533 /// transformation, the new indexed load / store has effectively folded
7534 /// the add / subtract in and all of its other uses are redirected to the
7535 /// new load / store.
7536 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7537   if (Level < AfterLegalizeDAG)
7538     return false;
7539
7540   bool isLoad = true;
7541   SDValue Ptr;
7542   EVT VT;
7543   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7544     if (LD->isIndexed())
7545       return false;
7546     VT = LD->getMemoryVT();
7547     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7548         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7549       return false;
7550     Ptr = LD->getBasePtr();
7551   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7552     if (ST->isIndexed())
7553       return false;
7554     VT = ST->getMemoryVT();
7555     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7556         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7557       return false;
7558     Ptr = ST->getBasePtr();
7559     isLoad = false;
7560   } else {
7561     return false;
7562   }
7563
7564   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7565   // out.  There is no reason to make this a preinc/predec.
7566   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7567       Ptr.getNode()->hasOneUse())
7568     return false;
7569
7570   // Ask the target to do addressing mode selection.
7571   SDValue BasePtr;
7572   SDValue Offset;
7573   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7574   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7575     return false;
7576
7577   // Backends without true r+i pre-indexed forms may need to pass a
7578   // constant base with a variable offset so that constant coercion
7579   // will work with the patterns in canonical form.
7580   bool Swapped = false;
7581   if (isa<ConstantSDNode>(BasePtr)) {
7582     std::swap(BasePtr, Offset);
7583     Swapped = true;
7584   }
7585
7586   // Don't create a indexed load / store with zero offset.
7587   if (isa<ConstantSDNode>(Offset) &&
7588       cast<ConstantSDNode>(Offset)->isNullValue())
7589     return false;
7590
7591   // Try turning it into a pre-indexed load / store except when:
7592   // 1) The new base ptr is a frame index.
7593   // 2) If N is a store and the new base ptr is either the same as or is a
7594   //    predecessor of the value being stored.
7595   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7596   //    that would create a cycle.
7597   // 4) All uses are load / store ops that use it as old base ptr.
7598
7599   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7600   // (plus the implicit offset) to a register to preinc anyway.
7601   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7602     return false;
7603
7604   // Check #2.
7605   if (!isLoad) {
7606     SDValue Val = cast<StoreSDNode>(N)->getValue();
7607     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7608       return false;
7609   }
7610
7611   // If the offset is a constant, there may be other adds of constants that
7612   // can be folded with this one. We should do this to avoid having to keep
7613   // a copy of the original base pointer.
7614   SmallVector<SDNode *, 16> OtherUses;
7615   if (isa<ConstantSDNode>(Offset))
7616     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7617          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7618       SDNode *Use = *I;
7619       if (Use == Ptr.getNode())
7620         continue;
7621
7622       if (Use->isPredecessorOf(N))
7623         continue;
7624
7625       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7626         OtherUses.clear();
7627         break;
7628       }
7629
7630       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7631       if (Op1.getNode() == BasePtr.getNode())
7632         std::swap(Op0, Op1);
7633       assert(Op0.getNode() == BasePtr.getNode() &&
7634              "Use of ADD/SUB but not an operand");
7635
7636       if (!isa<ConstantSDNode>(Op1)) {
7637         OtherUses.clear();
7638         break;
7639       }
7640
7641       // FIXME: In some cases, we can be smarter about this.
7642       if (Op1.getValueType() != Offset.getValueType()) {
7643         OtherUses.clear();
7644         break;
7645       }
7646
7647       OtherUses.push_back(Use);
7648     }
7649
7650   if (Swapped)
7651     std::swap(BasePtr, Offset);
7652
7653   // Now check for #3 and #4.
7654   bool RealUse = false;
7655
7656   // Caches for hasPredecessorHelper
7657   SmallPtrSet<const SDNode *, 32> Visited;
7658   SmallVector<const SDNode *, 16> Worklist;
7659
7660   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7661          E = Ptr.getNode()->use_end(); I != E; ++I) {
7662     SDNode *Use = *I;
7663     if (Use == N)
7664       continue;
7665     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7666       return false;
7667
7668     // If Ptr may be folded in addressing mode of other use, then it's
7669     // not profitable to do this transformation.
7670     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7671       RealUse = true;
7672   }
7673
7674   if (!RealUse)
7675     return false;
7676
7677   SDValue Result;
7678   if (isLoad)
7679     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7680                                 BasePtr, Offset, AM);
7681   else
7682     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7683                                  BasePtr, Offset, AM);
7684   ++PreIndexedNodes;
7685   ++NodesCombined;
7686   DEBUG(dbgs() << "\nReplacing.4 ";
7687         N->dump(&DAG);
7688         dbgs() << "\nWith: ";
7689         Result.getNode()->dump(&DAG);
7690         dbgs() << '\n');
7691   WorkListRemover DeadNodes(*this);
7692   if (isLoad) {
7693     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7694     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7695   } else {
7696     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7697   }
7698
7699   // Finally, since the node is now dead, remove it from the graph.
7700   DAG.DeleteNode(N);
7701
7702   if (Swapped)
7703     std::swap(BasePtr, Offset);
7704
7705   // Replace other uses of BasePtr that can be updated to use Ptr
7706   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7707     unsigned OffsetIdx = 1;
7708     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7709       OffsetIdx = 0;
7710     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7711            BasePtr.getNode() && "Expected BasePtr operand");
7712
7713     // We need to replace ptr0 in the following expression:
7714     //   x0 * offset0 + y0 * ptr0 = t0
7715     // knowing that
7716     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7717     //
7718     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7719     // indexed load/store and the expresion that needs to be re-written.
7720     //
7721     // Therefore, we have:
7722     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7723
7724     ConstantSDNode *CN =
7725       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7726     int X0, X1, Y0, Y1;
7727     APInt Offset0 = CN->getAPIntValue();
7728     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7729
7730     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7731     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7732     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7733     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7734
7735     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7736
7737     APInt CNV = Offset0;
7738     if (X0 < 0) CNV = -CNV;
7739     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7740     else CNV = CNV - Offset1;
7741
7742     // We can now generate the new expression.
7743     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7744     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7745
7746     SDValue NewUse = DAG.getNode(Opcode,
7747                                  SDLoc(OtherUses[i]),
7748                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7749     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7750     removeFromWorkList(OtherUses[i]);
7751     DAG.DeleteNode(OtherUses[i]);
7752   }
7753
7754   // Replace the uses of Ptr with uses of the updated base value.
7755   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7756   removeFromWorkList(Ptr.getNode());
7757   DAG.DeleteNode(Ptr.getNode());
7758
7759   return true;
7760 }
7761
7762 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7763 /// add / sub of the base pointer node into a post-indexed load / store.
7764 /// The transformation folded the add / subtract into the new indexed
7765 /// load / store effectively and all of its uses are redirected to the
7766 /// new load / store.
7767 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7768   if (Level < AfterLegalizeDAG)
7769     return false;
7770
7771   bool isLoad = true;
7772   SDValue Ptr;
7773   EVT VT;
7774   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7775     if (LD->isIndexed())
7776       return false;
7777     VT = LD->getMemoryVT();
7778     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7779         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7780       return false;
7781     Ptr = LD->getBasePtr();
7782   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7783     if (ST->isIndexed())
7784       return false;
7785     VT = ST->getMemoryVT();
7786     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7787         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7788       return false;
7789     Ptr = ST->getBasePtr();
7790     isLoad = false;
7791   } else {
7792     return false;
7793   }
7794
7795   if (Ptr.getNode()->hasOneUse())
7796     return false;
7797
7798   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7799          E = Ptr.getNode()->use_end(); I != E; ++I) {
7800     SDNode *Op = *I;
7801     if (Op == N ||
7802         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7803       continue;
7804
7805     SDValue BasePtr;
7806     SDValue Offset;
7807     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7808     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7809       // Don't create a indexed load / store with zero offset.
7810       if (isa<ConstantSDNode>(Offset) &&
7811           cast<ConstantSDNode>(Offset)->isNullValue())
7812         continue;
7813
7814       // Try turning it into a post-indexed load / store except when
7815       // 1) All uses are load / store ops that use it as base ptr (and
7816       //    it may be folded as addressing mmode).
7817       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7818       //    nor a successor of N. Otherwise, if Op is folded that would
7819       //    create a cycle.
7820
7821       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7822         continue;
7823
7824       // Check for #1.
7825       bool TryNext = false;
7826       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7827              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7828         SDNode *Use = *II;
7829         if (Use == Ptr.getNode())
7830           continue;
7831
7832         // If all the uses are load / store addresses, then don't do the
7833         // transformation.
7834         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7835           bool RealUse = false;
7836           for (SDNode::use_iterator III = Use->use_begin(),
7837                  EEE = Use->use_end(); III != EEE; ++III) {
7838             SDNode *UseUse = *III;
7839             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7840               RealUse = true;
7841           }
7842
7843           if (!RealUse) {
7844             TryNext = true;
7845             break;
7846           }
7847         }
7848       }
7849
7850       if (TryNext)
7851         continue;
7852
7853       // Check for #2
7854       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7855         SDValue Result = isLoad
7856           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7857                                BasePtr, Offset, AM)
7858           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7859                                 BasePtr, Offset, AM);
7860         ++PostIndexedNodes;
7861         ++NodesCombined;
7862         DEBUG(dbgs() << "\nReplacing.5 ";
7863               N->dump(&DAG);
7864               dbgs() << "\nWith: ";
7865               Result.getNode()->dump(&DAG);
7866               dbgs() << '\n');
7867         WorkListRemover DeadNodes(*this);
7868         if (isLoad) {
7869           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7870           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7871         } else {
7872           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7873         }
7874
7875         // Finally, since the node is now dead, remove it from the graph.
7876         DAG.DeleteNode(N);
7877
7878         // Replace the uses of Use with uses of the updated base value.
7879         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7880                                       Result.getValue(isLoad ? 1 : 0));
7881         removeFromWorkList(Op);
7882         DAG.DeleteNode(Op);
7883         return true;
7884       }
7885     }
7886   }
7887
7888   return false;
7889 }
7890
7891 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7892   LoadSDNode *LD  = cast<LoadSDNode>(N);
7893   SDValue Chain = LD->getChain();
7894   SDValue Ptr   = LD->getBasePtr();
7895
7896   // If load is not volatile and there are no uses of the loaded value (and
7897   // the updated indexed value in case of indexed loads), change uses of the
7898   // chain value into uses of the chain input (i.e. delete the dead load).
7899   if (!LD->isVolatile()) {
7900     if (N->getValueType(1) == MVT::Other) {
7901       // Unindexed loads.
7902       if (!N->hasAnyUseOfValue(0)) {
7903         // It's not safe to use the two value CombineTo variant here. e.g.
7904         // v1, chain2 = load chain1, loc
7905         // v2, chain3 = load chain2, loc
7906         // v3         = add v2, c
7907         // Now we replace use of chain2 with chain1.  This makes the second load
7908         // isomorphic to the one we are deleting, and thus makes this load live.
7909         DEBUG(dbgs() << "\nReplacing.6 ";
7910               N->dump(&DAG);
7911               dbgs() << "\nWith chain: ";
7912               Chain.getNode()->dump(&DAG);
7913               dbgs() << "\n");
7914         WorkListRemover DeadNodes(*this);
7915         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7916
7917         if (N->use_empty()) {
7918           removeFromWorkList(N);
7919           DAG.DeleteNode(N);
7920         }
7921
7922         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7923       }
7924     } else {
7925       // Indexed loads.
7926       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7927       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7928         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7929         DEBUG(dbgs() << "\nReplacing.7 ";
7930               N->dump(&DAG);
7931               dbgs() << "\nWith: ";
7932               Undef.getNode()->dump(&DAG);
7933               dbgs() << " and 2 other values\n");
7934         WorkListRemover DeadNodes(*this);
7935         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7936         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7937                                       DAG.getUNDEF(N->getValueType(1)));
7938         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7939         removeFromWorkList(N);
7940         DAG.DeleteNode(N);
7941         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7942       }
7943     }
7944   }
7945
7946   // If this load is directly stored, replace the load value with the stored
7947   // value.
7948   // TODO: Handle store large -> read small portion.
7949   // TODO: Handle TRUNCSTORE/LOADEXT
7950   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7951     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7952       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7953       if (PrevST->getBasePtr() == Ptr &&
7954           PrevST->getValue().getValueType() == N->getValueType(0))
7955       return CombineTo(N, Chain.getOperand(1), Chain);
7956     }
7957   }
7958
7959   // Try to infer better alignment information than the load already has.
7960   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7961     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7962       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7963         SDValue NewLoad =
7964                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7965                               LD->getValueType(0),
7966                               Chain, Ptr, LD->getPointerInfo(),
7967                               LD->getMemoryVT(),
7968                               LD->isVolatile(), LD->isNonTemporal(), Align,
7969                               LD->getTBAAInfo());
7970         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7971       }
7972     }
7973   }
7974
7975   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7976     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7977 #ifndef NDEBUG
7978   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7979       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7980     UseAA = false;
7981 #endif
7982   if (UseAA && LD->isUnindexed()) {
7983     // Walk up chain skipping non-aliasing memory nodes.
7984     SDValue BetterChain = FindBetterChain(N, Chain);
7985
7986     // If there is a better chain.
7987     if (Chain != BetterChain) {
7988       SDValue ReplLoad;
7989
7990       // Replace the chain to void dependency.
7991       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7992         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7993                                BetterChain, Ptr, LD->getMemOperand());
7994       } else {
7995         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7996                                   LD->getValueType(0),
7997                                   BetterChain, Ptr, LD->getMemoryVT(),
7998                                   LD->getMemOperand());
7999       }
8000
8001       // Create token factor to keep old chain connected.
8002       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8003                                   MVT::Other, Chain, ReplLoad.getValue(1));
8004
8005       // Make sure the new and old chains are cleaned up.
8006       AddToWorkList(Token.getNode());
8007
8008       // Replace uses with load result and token factor. Don't add users
8009       // to work list.
8010       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8011     }
8012   }
8013
8014   // Try transforming N to an indexed load.
8015   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8016     return SDValue(N, 0);
8017
8018   // Try to slice up N to more direct loads if the slices are mapped to
8019   // different register banks or pairing can take place.
8020   if (SliceUpLoad(N))
8021     return SDValue(N, 0);
8022
8023   return SDValue();
8024 }
8025
8026 namespace {
8027 /// \brief Helper structure used to slice a load in smaller loads.
8028 /// Basically a slice is obtained from the following sequence:
8029 /// Origin = load Ty1, Base
8030 /// Shift = srl Ty1 Origin, CstTy Amount
8031 /// Inst = trunc Shift to Ty2
8032 ///
8033 /// Then, it will be rewriten into:
8034 /// Slice = load SliceTy, Base + SliceOffset
8035 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8036 ///
8037 /// SliceTy is deduced from the number of bits that are actually used to
8038 /// build Inst.
8039 struct LoadedSlice {
8040   /// \brief Helper structure used to compute the cost of a slice.
8041   struct Cost {
8042     /// Are we optimizing for code size.
8043     bool ForCodeSize;
8044     /// Various cost.
8045     unsigned Loads;
8046     unsigned Truncates;
8047     unsigned CrossRegisterBanksCopies;
8048     unsigned ZExts;
8049     unsigned Shift;
8050
8051     Cost(bool ForCodeSize = false)
8052         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8053           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8054
8055     /// \brief Get the cost of one isolated slice.
8056     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8057         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8058           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8059       EVT TruncType = LS.Inst->getValueType(0);
8060       EVT LoadedType = LS.getLoadedType();
8061       if (TruncType != LoadedType &&
8062           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8063         ZExts = 1;
8064     }
8065
8066     /// \brief Account for slicing gain in the current cost.
8067     /// Slicing provide a few gains like removing a shift or a
8068     /// truncate. This method allows to grow the cost of the original
8069     /// load with the gain from this slice.
8070     void addSliceGain(const LoadedSlice &LS) {
8071       // Each slice saves a truncate.
8072       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8073       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8074                               LS.Inst->getOperand(0).getValueType()))
8075         ++Truncates;
8076       // If there is a shift amount, this slice gets rid of it.
8077       if (LS.Shift)
8078         ++Shift;
8079       // If this slice can merge a cross register bank copy, account for it.
8080       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8081         ++CrossRegisterBanksCopies;
8082     }
8083
8084     Cost &operator+=(const Cost &RHS) {
8085       Loads += RHS.Loads;
8086       Truncates += RHS.Truncates;
8087       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8088       ZExts += RHS.ZExts;
8089       Shift += RHS.Shift;
8090       return *this;
8091     }
8092
8093     bool operator==(const Cost &RHS) const {
8094       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8095              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8096              ZExts == RHS.ZExts && Shift == RHS.Shift;
8097     }
8098
8099     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8100
8101     bool operator<(const Cost &RHS) const {
8102       // Assume cross register banks copies are as expensive as loads.
8103       // FIXME: Do we want some more target hooks?
8104       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8105       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8106       // Unless we are optimizing for code size, consider the
8107       // expensive operation first.
8108       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8109         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8110       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8111              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8112     }
8113
8114     bool operator>(const Cost &RHS) const { return RHS < *this; }
8115
8116     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8117
8118     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8119   };
8120   // The last instruction that represent the slice. This should be a
8121   // truncate instruction.
8122   SDNode *Inst;
8123   // The original load instruction.
8124   LoadSDNode *Origin;
8125   // The right shift amount in bits from the original load.
8126   unsigned Shift;
8127   // The DAG from which Origin came from.
8128   // This is used to get some contextual information about legal types, etc.
8129   SelectionDAG *DAG;
8130
8131   LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8132               unsigned Shift = 0, SelectionDAG *DAG = NULL)
8133       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8134
8135   LoadedSlice(const LoadedSlice &LS)
8136       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8137
8138   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8139   /// \return Result is \p BitWidth and has used bits set to 1 and
8140   ///         not used bits set to 0.
8141   APInt getUsedBits() const {
8142     // Reproduce the trunc(lshr) sequence:
8143     // - Start from the truncated value.
8144     // - Zero extend to the desired bit width.
8145     // - Shift left.
8146     assert(Origin && "No original load to compare against.");
8147     unsigned BitWidth = Origin->getValueSizeInBits(0);
8148     assert(Inst && "This slice is not bound to an instruction");
8149     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8150            "Extracted slice is bigger than the whole type!");
8151     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8152     UsedBits.setAllBits();
8153     UsedBits = UsedBits.zext(BitWidth);
8154     UsedBits <<= Shift;
8155     return UsedBits;
8156   }
8157
8158   /// \brief Get the size of the slice to be loaded in bytes.
8159   unsigned getLoadedSize() const {
8160     unsigned SliceSize = getUsedBits().countPopulation();
8161     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8162     return SliceSize / 8;
8163   }
8164
8165   /// \brief Get the type that will be loaded for this slice.
8166   /// Note: This may not be the final type for the slice.
8167   EVT getLoadedType() const {
8168     assert(DAG && "Missing context");
8169     LLVMContext &Ctxt = *DAG->getContext();
8170     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8171   }
8172
8173   /// \brief Get the alignment of the load used for this slice.
8174   unsigned getAlignment() const {
8175     unsigned Alignment = Origin->getAlignment();
8176     unsigned Offset = getOffsetFromBase();
8177     if (Offset != 0)
8178       Alignment = MinAlign(Alignment, Alignment + Offset);
8179     return Alignment;
8180   }
8181
8182   /// \brief Check if this slice can be rewritten with legal operations.
8183   bool isLegal() const {
8184     // An invalid slice is not legal.
8185     if (!Origin || !Inst || !DAG)
8186       return false;
8187
8188     // Offsets are for indexed load only, we do not handle that.
8189     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8190       return false;
8191
8192     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8193
8194     // Check that the type is legal.
8195     EVT SliceType = getLoadedType();
8196     if (!TLI.isTypeLegal(SliceType))
8197       return false;
8198
8199     // Check that the load is legal for this type.
8200     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8201       return false;
8202
8203     // Check that the offset can be computed.
8204     // 1. Check its type.
8205     EVT PtrType = Origin->getBasePtr().getValueType();
8206     if (PtrType == MVT::Untyped || PtrType.isExtended())
8207       return false;
8208
8209     // 2. Check that it fits in the immediate.
8210     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8211       return false;
8212
8213     // 3. Check that the computation is legal.
8214     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8215       return false;
8216
8217     // Check that the zext is legal if it needs one.
8218     EVT TruncateType = Inst->getValueType(0);
8219     if (TruncateType != SliceType &&
8220         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8221       return false;
8222
8223     return true;
8224   }
8225
8226   /// \brief Get the offset in bytes of this slice in the original chunk of
8227   /// bits.
8228   /// \pre DAG != NULL.
8229   uint64_t getOffsetFromBase() const {
8230     assert(DAG && "Missing context.");
8231     bool IsBigEndian =
8232         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8233     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8234     uint64_t Offset = Shift / 8;
8235     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8236     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8237            "The size of the original loaded type is not a multiple of a"
8238            " byte.");
8239     // If Offset is bigger than TySizeInBytes, it means we are loading all
8240     // zeros. This should have been optimized before in the process.
8241     assert(TySizeInBytes > Offset &&
8242            "Invalid shift amount for given loaded size");
8243     if (IsBigEndian)
8244       Offset = TySizeInBytes - Offset - getLoadedSize();
8245     return Offset;
8246   }
8247
8248   /// \brief Generate the sequence of instructions to load the slice
8249   /// represented by this object and redirect the uses of this slice to
8250   /// this new sequence of instructions.
8251   /// \pre this->Inst && this->Origin are valid Instructions and this
8252   /// object passed the legal check: LoadedSlice::isLegal returned true.
8253   /// \return The last instruction of the sequence used to load the slice.
8254   SDValue loadSlice() const {
8255     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8256     const SDValue &OldBaseAddr = Origin->getBasePtr();
8257     SDValue BaseAddr = OldBaseAddr;
8258     // Get the offset in that chunk of bytes w.r.t. the endianess.
8259     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8260     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8261     if (Offset) {
8262       // BaseAddr = BaseAddr + Offset.
8263       EVT ArithType = BaseAddr.getValueType();
8264       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8265                               DAG->getConstant(Offset, ArithType));
8266     }
8267
8268     // Create the type of the loaded slice according to its size.
8269     EVT SliceType = getLoadedType();
8270
8271     // Create the load for the slice.
8272     SDValue LastInst = DAG->getLoad(
8273         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8274         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8275         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8276     // If the final type is not the same as the loaded type, this means that
8277     // we have to pad with zero. Create a zero extend for that.
8278     EVT FinalType = Inst->getValueType(0);
8279     if (SliceType != FinalType)
8280       LastInst =
8281           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8282     return LastInst;
8283   }
8284
8285   /// \brief Check if this slice can be merged with an expensive cross register
8286   /// bank copy. E.g.,
8287   /// i = load i32
8288   /// f = bitcast i32 i to float
8289   bool canMergeExpensiveCrossRegisterBankCopy() const {
8290     if (!Inst || !Inst->hasOneUse())
8291       return false;
8292     SDNode *Use = *Inst->use_begin();
8293     if (Use->getOpcode() != ISD::BITCAST)
8294       return false;
8295     assert(DAG && "Missing context");
8296     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8297     EVT ResVT = Use->getValueType(0);
8298     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8299     const TargetRegisterClass *ArgRC =
8300         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8301     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8302       return false;
8303
8304     // At this point, we know that we perform a cross-register-bank copy.
8305     // Check if it is expensive.
8306     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8307     // Assume bitcasts are cheap, unless both register classes do not
8308     // explicitly share a common sub class.
8309     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8310       return false;
8311
8312     // Check if it will be merged with the load.
8313     // 1. Check the alignment constraint.
8314     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8315         ResVT.getTypeForEVT(*DAG->getContext()));
8316
8317     if (RequiredAlignment > getAlignment())
8318       return false;
8319
8320     // 2. Check that the load is a legal operation for that type.
8321     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8322       return false;
8323
8324     // 3. Check that we do not have a zext in the way.
8325     if (Inst->getValueType(0) != getLoadedType())
8326       return false;
8327
8328     return true;
8329   }
8330 };
8331 }
8332
8333 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8334 /// \p UsedBits looks like 0..0 1..1 0..0.
8335 static bool areUsedBitsDense(const APInt &UsedBits) {
8336   // If all the bits are one, this is dense!
8337   if (UsedBits.isAllOnesValue())
8338     return true;
8339
8340   // Get rid of the unused bits on the right.
8341   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8342   // Get rid of the unused bits on the left.
8343   if (NarrowedUsedBits.countLeadingZeros())
8344     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8345   // Check that the chunk of bits is completely used.
8346   return NarrowedUsedBits.isAllOnesValue();
8347 }
8348
8349 /// \brief Check whether or not \p First and \p Second are next to each other
8350 /// in memory. This means that there is no hole between the bits loaded
8351 /// by \p First and the bits loaded by \p Second.
8352 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8353                                      const LoadedSlice &Second) {
8354   assert(First.Origin == Second.Origin && First.Origin &&
8355          "Unable to match different memory origins.");
8356   APInt UsedBits = First.getUsedBits();
8357   assert((UsedBits & Second.getUsedBits()) == 0 &&
8358          "Slices are not supposed to overlap.");
8359   UsedBits |= Second.getUsedBits();
8360   return areUsedBitsDense(UsedBits);
8361 }
8362
8363 /// \brief Adjust the \p GlobalLSCost according to the target
8364 /// paring capabilities and the layout of the slices.
8365 /// \pre \p GlobalLSCost should account for at least as many loads as
8366 /// there is in the slices in \p LoadedSlices.
8367 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8368                                  LoadedSlice::Cost &GlobalLSCost) {
8369   unsigned NumberOfSlices = LoadedSlices.size();
8370   // If there is less than 2 elements, no pairing is possible.
8371   if (NumberOfSlices < 2)
8372     return;
8373
8374   // Sort the slices so that elements that are likely to be next to each
8375   // other in memory are next to each other in the list.
8376   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8377             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8378     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8379     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8380   });
8381   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8382   // First (resp. Second) is the first (resp. Second) potentially candidate
8383   // to be placed in a paired load.
8384   const LoadedSlice *First = NULL;
8385   const LoadedSlice *Second = NULL;
8386   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8387                 // Set the beginning of the pair.
8388                                                            First = Second) {
8389
8390     Second = &LoadedSlices[CurrSlice];
8391
8392     // If First is NULL, it means we start a new pair.
8393     // Get to the next slice.
8394     if (!First)
8395       continue;
8396
8397     EVT LoadedType = First->getLoadedType();
8398
8399     // If the types of the slices are different, we cannot pair them.
8400     if (LoadedType != Second->getLoadedType())
8401       continue;
8402
8403     // Check if the target supplies paired loads for this type.
8404     unsigned RequiredAlignment = 0;
8405     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8406       // move to the next pair, this type is hopeless.
8407       Second = NULL;
8408       continue;
8409     }
8410     // Check if we meet the alignment requirement.
8411     if (RequiredAlignment > First->getAlignment())
8412       continue;
8413
8414     // Check that both loads are next to each other in memory.
8415     if (!areSlicesNextToEachOther(*First, *Second))
8416       continue;
8417
8418     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8419     --GlobalLSCost.Loads;
8420     // Move to the next pair.
8421     Second = NULL;
8422   }
8423 }
8424
8425 /// \brief Check the profitability of all involved LoadedSlice.
8426 /// Currently, it is considered profitable if there is exactly two
8427 /// involved slices (1) which are (2) next to each other in memory, and
8428 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8429 ///
8430 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8431 /// the elements themselves.
8432 ///
8433 /// FIXME: When the cost model will be mature enough, we can relax
8434 /// constraints (1) and (2).
8435 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8436                                 const APInt &UsedBits, bool ForCodeSize) {
8437   unsigned NumberOfSlices = LoadedSlices.size();
8438   if (StressLoadSlicing)
8439     return NumberOfSlices > 1;
8440
8441   // Check (1).
8442   if (NumberOfSlices != 2)
8443     return false;
8444
8445   // Check (2).
8446   if (!areUsedBitsDense(UsedBits))
8447     return false;
8448
8449   // Check (3).
8450   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8451   // The original code has one big load.
8452   OrigCost.Loads = 1;
8453   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8454     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8455     // Accumulate the cost of all the slices.
8456     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8457     GlobalSlicingCost += SliceCost;
8458
8459     // Account as cost in the original configuration the gain obtained
8460     // with the current slices.
8461     OrigCost.addSliceGain(LS);
8462   }
8463
8464   // If the target supports paired load, adjust the cost accordingly.
8465   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8466   return OrigCost > GlobalSlicingCost;
8467 }
8468
8469 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8470 /// operations, split it in the various pieces being extracted.
8471 ///
8472 /// This sort of thing is introduced by SROA.
8473 /// This slicing takes care not to insert overlapping loads.
8474 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8475 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8476   if (Level < AfterLegalizeDAG)
8477     return false;
8478
8479   LoadSDNode *LD = cast<LoadSDNode>(N);
8480   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8481       !LD->getValueType(0).isInteger())
8482     return false;
8483
8484   // Keep track of already used bits to detect overlapping values.
8485   // In that case, we will just abort the transformation.
8486   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8487
8488   SmallVector<LoadedSlice, 4> LoadedSlices;
8489
8490   // Check if this load is used as several smaller chunks of bits.
8491   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8492   // of computation for each trunc.
8493   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8494        UI != UIEnd; ++UI) {
8495     // Skip the uses of the chain.
8496     if (UI.getUse().getResNo() != 0)
8497       continue;
8498
8499     SDNode *User = *UI;
8500     unsigned Shift = 0;
8501
8502     // Check if this is a trunc(lshr).
8503     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8504         isa<ConstantSDNode>(User->getOperand(1))) {
8505       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8506       User = *User->use_begin();
8507     }
8508
8509     // At this point, User is a Truncate, iff we encountered, trunc or
8510     // trunc(lshr).
8511     if (User->getOpcode() != ISD::TRUNCATE)
8512       return false;
8513
8514     // The width of the type must be a power of 2 and greater than 8-bits.
8515     // Otherwise the load cannot be represented in LLVM IR.
8516     // Moreover, if we shifted with a non-8-bits multiple, the slice
8517     // will be across several bytes. We do not support that.
8518     unsigned Width = User->getValueSizeInBits(0);
8519     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8520       return 0;
8521
8522     // Build the slice for this chain of computations.
8523     LoadedSlice LS(User, LD, Shift, &DAG);
8524     APInt CurrentUsedBits = LS.getUsedBits();
8525
8526     // Check if this slice overlaps with another.
8527     if ((CurrentUsedBits & UsedBits) != 0)
8528       return false;
8529     // Update the bits used globally.
8530     UsedBits |= CurrentUsedBits;
8531
8532     // Check if the new slice would be legal.
8533     if (!LS.isLegal())
8534       return false;
8535
8536     // Record the slice.
8537     LoadedSlices.push_back(LS);
8538   }
8539
8540   // Abort slicing if it does not seem to be profitable.
8541   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8542     return false;
8543
8544   ++SlicedLoads;
8545
8546   // Rewrite each chain to use an independent load.
8547   // By construction, each chain can be represented by a unique load.
8548
8549   // Prepare the argument for the new token factor for all the slices.
8550   SmallVector<SDValue, 8> ArgChains;
8551   for (SmallVectorImpl<LoadedSlice>::const_iterator
8552            LSIt = LoadedSlices.begin(),
8553            LSItEnd = LoadedSlices.end();
8554        LSIt != LSItEnd; ++LSIt) {
8555     SDValue SliceInst = LSIt->loadSlice();
8556     CombineTo(LSIt->Inst, SliceInst, true);
8557     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8558       SliceInst = SliceInst.getOperand(0);
8559     assert(SliceInst->getOpcode() == ISD::LOAD &&
8560            "It takes more than a zext to get to the loaded slice!!");
8561     ArgChains.push_back(SliceInst.getValue(1));
8562   }
8563
8564   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8565                               &ArgChains[0], ArgChains.size());
8566   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8567   return true;
8568 }
8569
8570 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8571 /// load is having specific bytes cleared out.  If so, return the byte size
8572 /// being masked out and the shift amount.
8573 static std::pair<unsigned, unsigned>
8574 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8575   std::pair<unsigned, unsigned> Result(0, 0);
8576
8577   // Check for the structure we're looking for.
8578   if (V->getOpcode() != ISD::AND ||
8579       !isa<ConstantSDNode>(V->getOperand(1)) ||
8580       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8581     return Result;
8582
8583   // Check the chain and pointer.
8584   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8585   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8586
8587   // The store should be chained directly to the load or be an operand of a
8588   // tokenfactor.
8589   if (LD == Chain.getNode())
8590     ; // ok.
8591   else if (Chain->getOpcode() != ISD::TokenFactor)
8592     return Result; // Fail.
8593   else {
8594     bool isOk = false;
8595     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8596       if (Chain->getOperand(i).getNode() == LD) {
8597         isOk = true;
8598         break;
8599       }
8600     if (!isOk) return Result;
8601   }
8602
8603   // This only handles simple types.
8604   if (V.getValueType() != MVT::i16 &&
8605       V.getValueType() != MVT::i32 &&
8606       V.getValueType() != MVT::i64)
8607     return Result;
8608
8609   // Check the constant mask.  Invert it so that the bits being masked out are
8610   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8611   // follow the sign bit for uniformity.
8612   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8613   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8614   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8615   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8616   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8617   if (NotMaskLZ == 64) return Result;  // All zero mask.
8618
8619   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8620   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8621     return Result;
8622
8623   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8624   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8625     NotMaskLZ -= 64-V.getValueSizeInBits();
8626
8627   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8628   switch (MaskedBytes) {
8629   case 1:
8630   case 2:
8631   case 4: break;
8632   default: return Result; // All one mask, or 5-byte mask.
8633   }
8634
8635   // Verify that the first bit starts at a multiple of mask so that the access
8636   // is aligned the same as the access width.
8637   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8638
8639   Result.first = MaskedBytes;
8640   Result.second = NotMaskTZ/8;
8641   return Result;
8642 }
8643
8644
8645 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8646 /// provides a value as specified by MaskInfo.  If so, replace the specified
8647 /// store with a narrower store of truncated IVal.
8648 static SDNode *
8649 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8650                                 SDValue IVal, StoreSDNode *St,
8651                                 DAGCombiner *DC) {
8652   unsigned NumBytes = MaskInfo.first;
8653   unsigned ByteShift = MaskInfo.second;
8654   SelectionDAG &DAG = DC->getDAG();
8655
8656   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8657   // that uses this.  If not, this is not a replacement.
8658   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8659                                   ByteShift*8, (ByteShift+NumBytes)*8);
8660   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8661
8662   // Check that it is legal on the target to do this.  It is legal if the new
8663   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8664   // legalization.
8665   MVT VT = MVT::getIntegerVT(NumBytes*8);
8666   if (!DC->isTypeLegal(VT))
8667     return 0;
8668
8669   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8670   // shifted by ByteShift and truncated down to NumBytes.
8671   if (ByteShift)
8672     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8673                        DAG.getConstant(ByteShift*8,
8674                                     DC->getShiftAmountTy(IVal.getValueType())));
8675
8676   // Figure out the offset for the store and the alignment of the access.
8677   unsigned StOffset;
8678   unsigned NewAlign = St->getAlignment();
8679
8680   if (DAG.getTargetLoweringInfo().isLittleEndian())
8681     StOffset = ByteShift;
8682   else
8683     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8684
8685   SDValue Ptr = St->getBasePtr();
8686   if (StOffset) {
8687     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8688                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8689     NewAlign = MinAlign(NewAlign, StOffset);
8690   }
8691
8692   // Truncate down to the new size.
8693   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8694
8695   ++OpsNarrowed;
8696   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8697                       St->getPointerInfo().getWithOffset(StOffset),
8698                       false, false, NewAlign).getNode();
8699 }
8700
8701
8702 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8703 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8704 /// of the loaded bits, try narrowing the load and store if it would end up
8705 /// being a win for performance or code size.
8706 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8707   StoreSDNode *ST  = cast<StoreSDNode>(N);
8708   if (ST->isVolatile())
8709     return SDValue();
8710
8711   SDValue Chain = ST->getChain();
8712   SDValue Value = ST->getValue();
8713   SDValue Ptr   = ST->getBasePtr();
8714   EVT VT = Value.getValueType();
8715
8716   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8717     return SDValue();
8718
8719   unsigned Opc = Value.getOpcode();
8720
8721   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8722   // is a byte mask indicating a consecutive number of bytes, check to see if
8723   // Y is known to provide just those bytes.  If so, we try to replace the
8724   // load + replace + store sequence with a single (narrower) store, which makes
8725   // the load dead.
8726   if (Opc == ISD::OR) {
8727     std::pair<unsigned, unsigned> MaskedLoad;
8728     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8729     if (MaskedLoad.first)
8730       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8731                                                   Value.getOperand(1), ST,this))
8732         return SDValue(NewST, 0);
8733
8734     // Or is commutative, so try swapping X and Y.
8735     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8736     if (MaskedLoad.first)
8737       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8738                                                   Value.getOperand(0), ST,this))
8739         return SDValue(NewST, 0);
8740   }
8741
8742   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8743       Value.getOperand(1).getOpcode() != ISD::Constant)
8744     return SDValue();
8745
8746   SDValue N0 = Value.getOperand(0);
8747   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8748       Chain == SDValue(N0.getNode(), 1)) {
8749     LoadSDNode *LD = cast<LoadSDNode>(N0);
8750     if (LD->getBasePtr() != Ptr ||
8751         LD->getPointerInfo().getAddrSpace() !=
8752         ST->getPointerInfo().getAddrSpace())
8753       return SDValue();
8754
8755     // Find the type to narrow it the load / op / store to.
8756     SDValue N1 = Value.getOperand(1);
8757     unsigned BitWidth = N1.getValueSizeInBits();
8758     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8759     if (Opc == ISD::AND)
8760       Imm ^= APInt::getAllOnesValue(BitWidth);
8761     if (Imm == 0 || Imm.isAllOnesValue())
8762       return SDValue();
8763     unsigned ShAmt = Imm.countTrailingZeros();
8764     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8765     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8766     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8767     while (NewBW < BitWidth &&
8768            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8769              TLI.isNarrowingProfitable(VT, NewVT))) {
8770       NewBW = NextPowerOf2(NewBW);
8771       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8772     }
8773     if (NewBW >= BitWidth)
8774       return SDValue();
8775
8776     // If the lsb changed does not start at the type bitwidth boundary,
8777     // start at the previous one.
8778     if (ShAmt % NewBW)
8779       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8780     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8781                                    std::min(BitWidth, ShAmt + NewBW));
8782     if ((Imm & Mask) == Imm) {
8783       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8784       if (Opc == ISD::AND)
8785         NewImm ^= APInt::getAllOnesValue(NewBW);
8786       uint64_t PtrOff = ShAmt / 8;
8787       // For big endian targets, we need to adjust the offset to the pointer to
8788       // load the correct bytes.
8789       if (TLI.isBigEndian())
8790         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8791
8792       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8793       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8794       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8795         return SDValue();
8796
8797       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8798                                    Ptr.getValueType(), Ptr,
8799                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8800       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8801                                   LD->getChain(), NewPtr,
8802                                   LD->getPointerInfo().getWithOffset(PtrOff),
8803                                   LD->isVolatile(), LD->isNonTemporal(),
8804                                   LD->isInvariant(), NewAlign,
8805                                   LD->getTBAAInfo());
8806       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8807                                    DAG.getConstant(NewImm, NewVT));
8808       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8809                                    NewVal, NewPtr,
8810                                    ST->getPointerInfo().getWithOffset(PtrOff),
8811                                    false, false, NewAlign);
8812
8813       AddToWorkList(NewPtr.getNode());
8814       AddToWorkList(NewLD.getNode());
8815       AddToWorkList(NewVal.getNode());
8816       WorkListRemover DeadNodes(*this);
8817       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8818       ++OpsNarrowed;
8819       return NewST;
8820     }
8821   }
8822
8823   return SDValue();
8824 }
8825
8826 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8827 /// if the load value isn't used by any other operations, then consider
8828 /// transforming the pair to integer load / store operations if the target
8829 /// deems the transformation profitable.
8830 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8831   StoreSDNode *ST  = cast<StoreSDNode>(N);
8832   SDValue Chain = ST->getChain();
8833   SDValue Value = ST->getValue();
8834   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8835       Value.hasOneUse() &&
8836       Chain == SDValue(Value.getNode(), 1)) {
8837     LoadSDNode *LD = cast<LoadSDNode>(Value);
8838     EVT VT = LD->getMemoryVT();
8839     if (!VT.isFloatingPoint() ||
8840         VT != ST->getMemoryVT() ||
8841         LD->isNonTemporal() ||
8842         ST->isNonTemporal() ||
8843         LD->getPointerInfo().getAddrSpace() != 0 ||
8844         ST->getPointerInfo().getAddrSpace() != 0)
8845       return SDValue();
8846
8847     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8848     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8849         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8850         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8851         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8852       return SDValue();
8853
8854     unsigned LDAlign = LD->getAlignment();
8855     unsigned STAlign = ST->getAlignment();
8856     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8857     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8858     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8859       return SDValue();
8860
8861     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8862                                 LD->getChain(), LD->getBasePtr(),
8863                                 LD->getPointerInfo(),
8864                                 false, false, false, LDAlign);
8865
8866     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8867                                  NewLD, ST->getBasePtr(),
8868                                  ST->getPointerInfo(),
8869                                  false, false, STAlign);
8870
8871     AddToWorkList(NewLD.getNode());
8872     AddToWorkList(NewST.getNode());
8873     WorkListRemover DeadNodes(*this);
8874     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8875     ++LdStFP2Int;
8876     return NewST;
8877   }
8878
8879   return SDValue();
8880 }
8881
8882 /// Helper struct to parse and store a memory address as base + index + offset.
8883 /// We ignore sign extensions when it is safe to do so.
8884 /// The following two expressions are not equivalent. To differentiate we need
8885 /// to store whether there was a sign extension involved in the index
8886 /// computation.
8887 ///  (load (i64 add (i64 copyfromreg %c)
8888 ///                 (i64 signextend (add (i8 load %index)
8889 ///                                      (i8 1))))
8890 /// vs
8891 ///
8892 /// (load (i64 add (i64 copyfromreg %c)
8893 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8894 ///                                         (i32 1)))))
8895 struct BaseIndexOffset {
8896   SDValue Base;
8897   SDValue Index;
8898   int64_t Offset;
8899   bool IsIndexSignExt;
8900
8901   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8902
8903   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8904                   bool IsIndexSignExt) :
8905     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8906
8907   bool equalBaseIndex(const BaseIndexOffset &Other) {
8908     return Other.Base == Base && Other.Index == Index &&
8909       Other.IsIndexSignExt == IsIndexSignExt;
8910   }
8911
8912   /// Parses tree in Ptr for base, index, offset addresses.
8913   static BaseIndexOffset match(SDValue Ptr) {
8914     bool IsIndexSignExt = false;
8915
8916     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8917     // instruction, then it could be just the BASE or everything else we don't
8918     // know how to handle. Just use Ptr as BASE and give up.
8919     if (Ptr->getOpcode() != ISD::ADD)
8920       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8921
8922     // We know that we have at least an ADD instruction. Try to pattern match
8923     // the simple case of BASE + OFFSET.
8924     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8925       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8926       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8927                               IsIndexSignExt);
8928     }
8929
8930     // Inside a loop the current BASE pointer is calculated using an ADD and a
8931     // MUL instruction. In this case Ptr is the actual BASE pointer.
8932     // (i64 add (i64 %array_ptr)
8933     //          (i64 mul (i64 %induction_var)
8934     //                   (i64 %element_size)))
8935     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8936       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8937
8938     // Look at Base + Index + Offset cases.
8939     SDValue Base = Ptr->getOperand(0);
8940     SDValue IndexOffset = Ptr->getOperand(1);
8941
8942     // Skip signextends.
8943     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8944       IndexOffset = IndexOffset->getOperand(0);
8945       IsIndexSignExt = true;
8946     }
8947
8948     // Either the case of Base + Index (no offset) or something else.
8949     if (IndexOffset->getOpcode() != ISD::ADD)
8950       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8951
8952     // Now we have the case of Base + Index + offset.
8953     SDValue Index = IndexOffset->getOperand(0);
8954     SDValue Offset = IndexOffset->getOperand(1);
8955
8956     if (!isa<ConstantSDNode>(Offset))
8957       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8958
8959     // Ignore signextends.
8960     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8961       Index = Index->getOperand(0);
8962       IsIndexSignExt = true;
8963     } else IsIndexSignExt = false;
8964
8965     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8966     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8967   }
8968 };
8969
8970 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8971 /// is located in a sequence of memory operations connected by a chain.
8972 struct MemOpLink {
8973   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8974     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8975   // Ptr to the mem node.
8976   LSBaseSDNode *MemNode;
8977   // Offset from the base ptr.
8978   int64_t OffsetFromBase;
8979   // What is the sequence number of this mem node.
8980   // Lowest mem operand in the DAG starts at zero.
8981   unsigned SequenceNum;
8982 };
8983
8984 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8985   EVT MemVT = St->getMemoryVT();
8986   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8987   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8988     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8989
8990   // Don't merge vectors into wider inputs.
8991   if (MemVT.isVector() || !MemVT.isSimple())
8992     return false;
8993
8994   // Perform an early exit check. Do not bother looking at stored values that
8995   // are not constants or loads.
8996   SDValue StoredVal = St->getValue();
8997   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8998   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8999       !IsLoadSrc)
9000     return false;
9001
9002   // Only look at ends of store sequences.
9003   SDValue Chain = SDValue(St, 1);
9004   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9005     return false;
9006
9007   // This holds the base pointer, index, and the offset in bytes from the base
9008   // pointer.
9009   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9010
9011   // We must have a base and an offset.
9012   if (!BasePtr.Base.getNode())
9013     return false;
9014
9015   // Do not handle stores to undef base pointers.
9016   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9017     return false;
9018
9019   // Save the LoadSDNodes that we find in the chain.
9020   // We need to make sure that these nodes do not interfere with
9021   // any of the store nodes.
9022   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9023
9024   // Save the StoreSDNodes that we find in the chain.
9025   SmallVector<MemOpLink, 8> StoreNodes;
9026
9027   // Walk up the chain and look for nodes with offsets from the same
9028   // base pointer. Stop when reaching an instruction with a different kind
9029   // or instruction which has a different base pointer.
9030   unsigned Seq = 0;
9031   StoreSDNode *Index = St;
9032   while (Index) {
9033     // If the chain has more than one use, then we can't reorder the mem ops.
9034     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9035       break;
9036
9037     // Find the base pointer and offset for this memory node.
9038     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9039
9040     // Check that the base pointer is the same as the original one.
9041     if (!Ptr.equalBaseIndex(BasePtr))
9042       break;
9043
9044     // Check that the alignment is the same.
9045     if (Index->getAlignment() != St->getAlignment())
9046       break;
9047
9048     // The memory operands must not be volatile.
9049     if (Index->isVolatile() || Index->isIndexed())
9050       break;
9051
9052     // No truncation.
9053     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9054       if (St->isTruncatingStore())
9055         break;
9056
9057     // The stored memory type must be the same.
9058     if (Index->getMemoryVT() != MemVT)
9059       break;
9060
9061     // We do not allow unaligned stores because we want to prevent overriding
9062     // stores.
9063     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9064       break;
9065
9066     // We found a potential memory operand to merge.
9067     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9068
9069     // Find the next memory operand in the chain. If the next operand in the
9070     // chain is a store then move up and continue the scan with the next
9071     // memory operand. If the next operand is a load save it and use alias
9072     // information to check if it interferes with anything.
9073     SDNode *NextInChain = Index->getChain().getNode();
9074     while (1) {
9075       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9076         // We found a store node. Use it for the next iteration.
9077         Index = STn;
9078         break;
9079       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9080         if (Ldn->isVolatile()) {
9081           Index = NULL;
9082           break;
9083         }
9084
9085         // Save the load node for later. Continue the scan.
9086         AliasLoadNodes.push_back(Ldn);
9087         NextInChain = Ldn->getChain().getNode();
9088         continue;
9089       } else {
9090         Index = NULL;
9091         break;
9092       }
9093     }
9094   }
9095
9096   // Check if there is anything to merge.
9097   if (StoreNodes.size() < 2)
9098     return false;
9099
9100   // Sort the memory operands according to their distance from the base pointer.
9101   std::sort(StoreNodes.begin(), StoreNodes.end(),
9102             [](MemOpLink LHS, MemOpLink RHS) {
9103     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9104            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9105             LHS.SequenceNum > RHS.SequenceNum);
9106   });
9107
9108   // Scan the memory operations on the chain and find the first non-consecutive
9109   // store memory address.
9110   unsigned LastConsecutiveStore = 0;
9111   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9112   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9113
9114     // Check that the addresses are consecutive starting from the second
9115     // element in the list of stores.
9116     if (i > 0) {
9117       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9118       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9119         break;
9120     }
9121
9122     bool Alias = false;
9123     // Check if this store interferes with any of the loads that we found.
9124     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9125       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9126         Alias = true;
9127         break;
9128       }
9129     // We found a load that alias with this store. Stop the sequence.
9130     if (Alias)
9131       break;
9132
9133     // Mark this node as useful.
9134     LastConsecutiveStore = i;
9135   }
9136
9137   // The node with the lowest store address.
9138   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9139
9140   // Store the constants into memory as one consecutive store.
9141   if (!IsLoadSrc) {
9142     unsigned LastLegalType = 0;
9143     unsigned LastLegalVectorType = 0;
9144     bool NonZero = false;
9145     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9146       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9147       SDValue StoredVal = St->getValue();
9148
9149       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9150         NonZero |= !C->isNullValue();
9151       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9152         NonZero |= !C->getConstantFPValue()->isNullValue();
9153       } else {
9154         // Non-constant.
9155         break;
9156       }
9157
9158       // Find a legal type for the constant store.
9159       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9160       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9161       if (TLI.isTypeLegal(StoreTy))
9162         LastLegalType = i+1;
9163       // Or check whether a truncstore is legal.
9164       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9165                TargetLowering::TypePromoteInteger) {
9166         EVT LegalizedStoredValueTy =
9167           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9168         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9169           LastLegalType = i+1;
9170       }
9171
9172       // Find a legal type for the vector store.
9173       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9174       if (TLI.isTypeLegal(Ty))
9175         LastLegalVectorType = i + 1;
9176     }
9177
9178     // We only use vectors if the constant is known to be zero and the
9179     // function is not marked with the noimplicitfloat attribute.
9180     if (NonZero || NoVectors)
9181       LastLegalVectorType = 0;
9182
9183     // Check if we found a legal integer type to store.
9184     if (LastLegalType == 0 && LastLegalVectorType == 0)
9185       return false;
9186
9187     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9188     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9189
9190     // Make sure we have something to merge.
9191     if (NumElem < 2)
9192       return false;
9193
9194     unsigned EarliestNodeUsed = 0;
9195     for (unsigned i=0; i < NumElem; ++i) {
9196       // Find a chain for the new wide-store operand. Notice that some
9197       // of the store nodes that we found may not be selected for inclusion
9198       // in the wide store. The chain we use needs to be the chain of the
9199       // earliest store node which is *used* and replaced by the wide store.
9200       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9201         EarliestNodeUsed = i;
9202     }
9203
9204     // The earliest Node in the DAG.
9205     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9206     SDLoc DL(StoreNodes[0].MemNode);
9207
9208     SDValue StoredVal;
9209     if (UseVector) {
9210       // Find a legal type for the vector store.
9211       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9212       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9213       StoredVal = DAG.getConstant(0, Ty);
9214     } else {
9215       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9216       APInt StoreInt(StoreBW, 0);
9217
9218       // Construct a single integer constant which is made of the smaller
9219       // constant inputs.
9220       bool IsLE = TLI.isLittleEndian();
9221       for (unsigned i = 0; i < NumElem ; ++i) {
9222         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9223         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9224         SDValue Val = St->getValue();
9225         StoreInt<<=ElementSizeBytes*8;
9226         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9227           StoreInt|=C->getAPIntValue().zext(StoreBW);
9228         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9229           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9230         } else {
9231           assert(false && "Invalid constant element type");
9232         }
9233       }
9234
9235       // Create the new Load and Store operations.
9236       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9237       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9238     }
9239
9240     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9241                                     FirstInChain->getBasePtr(),
9242                                     FirstInChain->getPointerInfo(),
9243                                     false, false,
9244                                     FirstInChain->getAlignment());
9245
9246     // Replace the first store with the new store
9247     CombineTo(EarliestOp, NewStore);
9248     // Erase all other stores.
9249     for (unsigned i = 0; i < NumElem ; ++i) {
9250       if (StoreNodes[i].MemNode == EarliestOp)
9251         continue;
9252       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9253       // ReplaceAllUsesWith will replace all uses that existed when it was
9254       // called, but graph optimizations may cause new ones to appear. For
9255       // example, the case in pr14333 looks like
9256       //
9257       //  St's chain -> St -> another store -> X
9258       //
9259       // And the only difference from St to the other store is the chain.
9260       // When we change it's chain to be St's chain they become identical,
9261       // get CSEed and the net result is that X is now a use of St.
9262       // Since we know that St is redundant, just iterate.
9263       while (!St->use_empty())
9264         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9265       removeFromWorkList(St);
9266       DAG.DeleteNode(St);
9267     }
9268
9269     return true;
9270   }
9271
9272   // Below we handle the case of multiple consecutive stores that
9273   // come from multiple consecutive loads. We merge them into a single
9274   // wide load and a single wide store.
9275
9276   // Look for load nodes which are used by the stored values.
9277   SmallVector<MemOpLink, 8> LoadNodes;
9278
9279   // Find acceptable loads. Loads need to have the same chain (token factor),
9280   // must not be zext, volatile, indexed, and they must be consecutive.
9281   BaseIndexOffset LdBasePtr;
9282   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9283     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9284     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9285     if (!Ld) break;
9286
9287     // Loads must only have one use.
9288     if (!Ld->hasNUsesOfValue(1, 0))
9289       break;
9290
9291     // Check that the alignment is the same as the stores.
9292     if (Ld->getAlignment() != St->getAlignment())
9293       break;
9294
9295     // The memory operands must not be volatile.
9296     if (Ld->isVolatile() || Ld->isIndexed())
9297       break;
9298
9299     // We do not accept ext loads.
9300     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9301       break;
9302
9303     // The stored memory type must be the same.
9304     if (Ld->getMemoryVT() != MemVT)
9305       break;
9306
9307     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9308     // If this is not the first ptr that we check.
9309     if (LdBasePtr.Base.getNode()) {
9310       // The base ptr must be the same.
9311       if (!LdPtr.equalBaseIndex(LdBasePtr))
9312         break;
9313     } else {
9314       // Check that all other base pointers are the same as this one.
9315       LdBasePtr = LdPtr;
9316     }
9317
9318     // We found a potential memory operand to merge.
9319     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9320   }
9321
9322   if (LoadNodes.size() < 2)
9323     return false;
9324
9325   // Scan the memory operations on the chain and find the first non-consecutive
9326   // load memory address. These variables hold the index in the store node
9327   // array.
9328   unsigned LastConsecutiveLoad = 0;
9329   // This variable refers to the size and not index in the array.
9330   unsigned LastLegalVectorType = 0;
9331   unsigned LastLegalIntegerType = 0;
9332   StartAddress = LoadNodes[0].OffsetFromBase;
9333   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9334   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9335     // All loads much share the same chain.
9336     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9337       break;
9338
9339     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9340     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9341       break;
9342     LastConsecutiveLoad = i;
9343
9344     // Find a legal type for the vector store.
9345     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9346     if (TLI.isTypeLegal(StoreTy))
9347       LastLegalVectorType = i + 1;
9348
9349     // Find a legal type for the integer store.
9350     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9351     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9352     if (TLI.isTypeLegal(StoreTy))
9353       LastLegalIntegerType = i + 1;
9354     // Or check whether a truncstore and extload is legal.
9355     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9356              TargetLowering::TypePromoteInteger) {
9357       EVT LegalizedStoredValueTy =
9358         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9359       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9360           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9361           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9362           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9363         LastLegalIntegerType = i+1;
9364     }
9365   }
9366
9367   // Only use vector types if the vector type is larger than the integer type.
9368   // If they are the same, use integers.
9369   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9370   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9371
9372   // We add +1 here because the LastXXX variables refer to location while
9373   // the NumElem refers to array/index size.
9374   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9375   NumElem = std::min(LastLegalType, NumElem);
9376
9377   if (NumElem < 2)
9378     return false;
9379
9380   // The earliest Node in the DAG.
9381   unsigned EarliestNodeUsed = 0;
9382   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9383   for (unsigned i=1; i<NumElem; ++i) {
9384     // Find a chain for the new wide-store operand. Notice that some
9385     // of the store nodes that we found may not be selected for inclusion
9386     // in the wide store. The chain we use needs to be the chain of the
9387     // earliest store node which is *used* and replaced by the wide store.
9388     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9389       EarliestNodeUsed = i;
9390   }
9391
9392   // Find if it is better to use vectors or integers to load and store
9393   // to memory.
9394   EVT JointMemOpVT;
9395   if (UseVectorTy) {
9396     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9397   } else {
9398     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9399     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9400   }
9401
9402   SDLoc LoadDL(LoadNodes[0].MemNode);
9403   SDLoc StoreDL(StoreNodes[0].MemNode);
9404
9405   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9406   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9407                                 FirstLoad->getChain(),
9408                                 FirstLoad->getBasePtr(),
9409                                 FirstLoad->getPointerInfo(),
9410                                 false, false, false,
9411                                 FirstLoad->getAlignment());
9412
9413   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9414                                   FirstInChain->getBasePtr(),
9415                                   FirstInChain->getPointerInfo(), false, false,
9416                                   FirstInChain->getAlignment());
9417
9418   // Replace one of the loads with the new load.
9419   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9420   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9421                                 SDValue(NewLoad.getNode(), 1));
9422
9423   // Remove the rest of the load chains.
9424   for (unsigned i = 1; i < NumElem ; ++i) {
9425     // Replace all chain users of the old load nodes with the chain of the new
9426     // load node.
9427     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9428     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9429   }
9430
9431   // Replace the first store with the new store.
9432   CombineTo(EarliestOp, NewStore);
9433   // Erase all other stores.
9434   for (unsigned i = 0; i < NumElem ; ++i) {
9435     // Remove all Store nodes.
9436     if (StoreNodes[i].MemNode == EarliestOp)
9437       continue;
9438     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9439     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9440     removeFromWorkList(St);
9441     DAG.DeleteNode(St);
9442   }
9443
9444   return true;
9445 }
9446
9447 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9448   StoreSDNode *ST  = cast<StoreSDNode>(N);
9449   SDValue Chain = ST->getChain();
9450   SDValue Value = ST->getValue();
9451   SDValue Ptr   = ST->getBasePtr();
9452
9453   // If this is a store of a bit convert, store the input value if the
9454   // resultant store does not need a higher alignment than the original.
9455   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9456       ST->isUnindexed()) {
9457     unsigned OrigAlign = ST->getAlignment();
9458     EVT SVT = Value.getOperand(0).getValueType();
9459     unsigned Align = TLI.getDataLayout()->
9460       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9461     if (Align <= OrigAlign &&
9462         ((!LegalOperations && !ST->isVolatile()) ||
9463          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9464       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9465                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9466                           ST->isNonTemporal(), OrigAlign,
9467                           ST->getTBAAInfo());
9468   }
9469
9470   // Turn 'store undef, Ptr' -> nothing.
9471   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9472     return Chain;
9473
9474   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9475   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9476     // NOTE: If the original store is volatile, this transform must not increase
9477     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9478     // processor operation but an i64 (which is not legal) requires two.  So the
9479     // transform should not be done in this case.
9480     if (Value.getOpcode() != ISD::TargetConstantFP) {
9481       SDValue Tmp;
9482       switch (CFP->getSimpleValueType(0).SimpleTy) {
9483       default: llvm_unreachable("Unknown FP type");
9484       case MVT::f16:    // We don't do this for these yet.
9485       case MVT::f80:
9486       case MVT::f128:
9487       case MVT::ppcf128:
9488         break;
9489       case MVT::f32:
9490         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9491             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9492           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9493                               bitcastToAPInt().getZExtValue(), MVT::i32);
9494           return DAG.getStore(Chain, SDLoc(N), Tmp,
9495                               Ptr, ST->getMemOperand());
9496         }
9497         break;
9498       case MVT::f64:
9499         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9500              !ST->isVolatile()) ||
9501             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9502           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9503                                 getZExtValue(), MVT::i64);
9504           return DAG.getStore(Chain, SDLoc(N), Tmp,
9505                               Ptr, ST->getMemOperand());
9506         }
9507
9508         if (!ST->isVolatile() &&
9509             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9510           // Many FP stores are not made apparent until after legalize, e.g. for
9511           // argument passing.  Since this is so common, custom legalize the
9512           // 64-bit integer store into two 32-bit stores.
9513           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9514           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9515           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9516           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9517
9518           unsigned Alignment = ST->getAlignment();
9519           bool isVolatile = ST->isVolatile();
9520           bool isNonTemporal = ST->isNonTemporal();
9521           const MDNode *TBAAInfo = ST->getTBAAInfo();
9522
9523           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9524                                      Ptr, ST->getPointerInfo(),
9525                                      isVolatile, isNonTemporal,
9526                                      ST->getAlignment(), TBAAInfo);
9527           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9528                             DAG.getConstant(4, Ptr.getValueType()));
9529           Alignment = MinAlign(Alignment, 4U);
9530           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9531                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9532                                      isVolatile, isNonTemporal,
9533                                      Alignment, TBAAInfo);
9534           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9535                              St0, St1);
9536         }
9537
9538         break;
9539       }
9540     }
9541   }
9542
9543   // Try to infer better alignment information than the store already has.
9544   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9545     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9546       if (Align > ST->getAlignment())
9547         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9548                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9549                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9550                                  ST->getTBAAInfo());
9551     }
9552   }
9553
9554   // Try transforming a pair floating point load / store ops to integer
9555   // load / store ops.
9556   SDValue NewST = TransformFPLoadStorePair(N);
9557   if (NewST.getNode())
9558     return NewST;
9559
9560   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9561     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9562 #ifndef NDEBUG
9563   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9564       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9565     UseAA = false;
9566 #endif
9567   if (UseAA && ST->isUnindexed()) {
9568     // Walk up chain skipping non-aliasing memory nodes.
9569     SDValue BetterChain = FindBetterChain(N, Chain);
9570
9571     // If there is a better chain.
9572     if (Chain != BetterChain) {
9573       SDValue ReplStore;
9574
9575       // Replace the chain to avoid dependency.
9576       if (ST->isTruncatingStore()) {
9577         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9578                                       ST->getMemoryVT(), ST->getMemOperand());
9579       } else {
9580         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9581                                  ST->getMemOperand());
9582       }
9583
9584       // Create token to keep both nodes around.
9585       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9586                                   MVT::Other, Chain, ReplStore);
9587
9588       // Make sure the new and old chains are cleaned up.
9589       AddToWorkList(Token.getNode());
9590
9591       // Don't add users to work list.
9592       return CombineTo(N, Token, false);
9593     }
9594   }
9595
9596   // Try transforming N to an indexed store.
9597   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9598     return SDValue(N, 0);
9599
9600   // FIXME: is there such a thing as a truncating indexed store?
9601   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9602       Value.getValueType().isInteger()) {
9603     // See if we can simplify the input to this truncstore with knowledge that
9604     // only the low bits are being used.  For example:
9605     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9606     SDValue Shorter =
9607       GetDemandedBits(Value,
9608                       APInt::getLowBitsSet(
9609                         Value.getValueType().getScalarType().getSizeInBits(),
9610                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9611     AddToWorkList(Value.getNode());
9612     if (Shorter.getNode())
9613       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9614                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9615
9616     // Otherwise, see if we can simplify the operation with
9617     // SimplifyDemandedBits, which only works if the value has a single use.
9618     if (SimplifyDemandedBits(Value,
9619                         APInt::getLowBitsSet(
9620                           Value.getValueType().getScalarType().getSizeInBits(),
9621                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9622       return SDValue(N, 0);
9623   }
9624
9625   // If this is a load followed by a store to the same location, then the store
9626   // is dead/noop.
9627   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9628     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9629         ST->isUnindexed() && !ST->isVolatile() &&
9630         // There can't be any side effects between the load and store, such as
9631         // a call or store.
9632         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9633       // The store is dead, remove it.
9634       return Chain;
9635     }
9636   }
9637
9638   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9639   // truncating store.  We can do this even if this is already a truncstore.
9640   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9641       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9642       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9643                             ST->getMemoryVT())) {
9644     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9645                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9646   }
9647
9648   // Only perform this optimization before the types are legal, because we
9649   // don't want to perform this optimization on every DAGCombine invocation.
9650   if (!LegalTypes) {
9651     bool EverChanged = false;
9652
9653     do {
9654       // There can be multiple store sequences on the same chain.
9655       // Keep trying to merge store sequences until we are unable to do so
9656       // or until we merge the last store on the chain.
9657       bool Changed = MergeConsecutiveStores(ST);
9658       EverChanged |= Changed;
9659       if (!Changed) break;
9660     } while (ST->getOpcode() != ISD::DELETED_NODE);
9661
9662     if (EverChanged)
9663       return SDValue(N, 0);
9664   }
9665
9666   return ReduceLoadOpStoreWidth(N);
9667 }
9668
9669 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9670   SDValue InVec = N->getOperand(0);
9671   SDValue InVal = N->getOperand(1);
9672   SDValue EltNo = N->getOperand(2);
9673   SDLoc dl(N);
9674
9675   // If the inserted element is an UNDEF, just use the input vector.
9676   if (InVal.getOpcode() == ISD::UNDEF)
9677     return InVec;
9678
9679   EVT VT = InVec.getValueType();
9680
9681   // If we can't generate a legal BUILD_VECTOR, exit
9682   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9683     return SDValue();
9684
9685   // Check that we know which element is being inserted
9686   if (!isa<ConstantSDNode>(EltNo))
9687     return SDValue();
9688   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9689
9690   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9691   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9692   // vector elements.
9693   SmallVector<SDValue, 8> Ops;
9694   // Do not combine these two vectors if the output vector will not replace
9695   // the input vector.
9696   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9697     Ops.append(InVec.getNode()->op_begin(),
9698                InVec.getNode()->op_end());
9699   } else if (InVec.getOpcode() == ISD::UNDEF) {
9700     unsigned NElts = VT.getVectorNumElements();
9701     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9702   } else {
9703     return SDValue();
9704   }
9705
9706   // Insert the element
9707   if (Elt < Ops.size()) {
9708     // All the operands of BUILD_VECTOR must have the same type;
9709     // we enforce that here.
9710     EVT OpVT = Ops[0].getValueType();
9711     if (InVal.getValueType() != OpVT)
9712       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9713                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9714                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9715     Ops[Elt] = InVal;
9716   }
9717
9718   // Return the new vector
9719   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9720                      VT, &Ops[0], Ops.size());
9721 }
9722
9723 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9724   // (vextract (scalar_to_vector val, 0) -> val
9725   SDValue InVec = N->getOperand(0);
9726   EVT VT = InVec.getValueType();
9727   EVT NVT = N->getValueType(0);
9728
9729   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9730     // Check if the result type doesn't match the inserted element type. A
9731     // SCALAR_TO_VECTOR may truncate the inserted element and the
9732     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9733     SDValue InOp = InVec.getOperand(0);
9734     if (InOp.getValueType() != NVT) {
9735       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9736       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9737     }
9738     return InOp;
9739   }
9740
9741   SDValue EltNo = N->getOperand(1);
9742   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9743
9744   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9745   // We only perform this optimization before the op legalization phase because
9746   // we may introduce new vector instructions which are not backed by TD
9747   // patterns. For example on AVX, extracting elements from a wide vector
9748   // without using extract_subvector.
9749   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9750       && ConstEltNo && !LegalOperations) {
9751     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9752     int NumElem = VT.getVectorNumElements();
9753     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9754     // Find the new index to extract from.
9755     int OrigElt = SVOp->getMaskElt(Elt);
9756
9757     // Extracting an undef index is undef.
9758     if (OrigElt == -1)
9759       return DAG.getUNDEF(NVT);
9760
9761     // Select the right vector half to extract from.
9762     if (OrigElt < NumElem) {
9763       InVec = InVec->getOperand(0);
9764     } else {
9765       InVec = InVec->getOperand(1);
9766       OrigElt -= NumElem;
9767     }
9768
9769     EVT IndexTy = TLI.getVectorIdxTy();
9770     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9771                        InVec, DAG.getConstant(OrigElt, IndexTy));
9772   }
9773
9774   // Perform only after legalization to ensure build_vector / vector_shuffle
9775   // optimizations have already been done.
9776   if (!LegalOperations) return SDValue();
9777
9778   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9779   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9780   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9781
9782   if (ConstEltNo) {
9783     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9784     bool NewLoad = false;
9785     bool BCNumEltsChanged = false;
9786     EVT ExtVT = VT.getVectorElementType();
9787     EVT LVT = ExtVT;
9788
9789     // If the result of load has to be truncated, then it's not necessarily
9790     // profitable.
9791     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9792       return SDValue();
9793
9794     if (InVec.getOpcode() == ISD::BITCAST) {
9795       // Don't duplicate a load with other uses.
9796       if (!InVec.hasOneUse())
9797         return SDValue();
9798
9799       EVT BCVT = InVec.getOperand(0).getValueType();
9800       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9801         return SDValue();
9802       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9803         BCNumEltsChanged = true;
9804       InVec = InVec.getOperand(0);
9805       ExtVT = BCVT.getVectorElementType();
9806       NewLoad = true;
9807     }
9808
9809     LoadSDNode *LN0 = NULL;
9810     const ShuffleVectorSDNode *SVN = NULL;
9811     if (ISD::isNormalLoad(InVec.getNode())) {
9812       LN0 = cast<LoadSDNode>(InVec);
9813     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9814                InVec.getOperand(0).getValueType() == ExtVT &&
9815                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9816       // Don't duplicate a load with other uses.
9817       if (!InVec.hasOneUse())
9818         return SDValue();
9819
9820       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9821     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9822       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9823       // =>
9824       // (load $addr+1*size)
9825
9826       // Don't duplicate a load with other uses.
9827       if (!InVec.hasOneUse())
9828         return SDValue();
9829
9830       // If the bit convert changed the number of elements, it is unsafe
9831       // to examine the mask.
9832       if (BCNumEltsChanged)
9833         return SDValue();
9834
9835       // Select the input vector, guarding against out of range extract vector.
9836       unsigned NumElems = VT.getVectorNumElements();
9837       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9838       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9839
9840       if (InVec.getOpcode() == ISD::BITCAST) {
9841         // Don't duplicate a load with other uses.
9842         if (!InVec.hasOneUse())
9843           return SDValue();
9844
9845         InVec = InVec.getOperand(0);
9846       }
9847       if (ISD::isNormalLoad(InVec.getNode())) {
9848         LN0 = cast<LoadSDNode>(InVec);
9849         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9850       }
9851     }
9852
9853     // Make sure we found a non-volatile load and the extractelement is
9854     // the only use.
9855     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9856       return SDValue();
9857
9858     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9859     if (Elt == -1)
9860       return DAG.getUNDEF(LVT);
9861
9862     unsigned Align = LN0->getAlignment();
9863     if (NewLoad) {
9864       // Check the resultant load doesn't need a higher alignment than the
9865       // original load.
9866       unsigned NewAlign =
9867         TLI.getDataLayout()
9868             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9869
9870       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9871         return SDValue();
9872
9873       Align = NewAlign;
9874     }
9875
9876     SDValue NewPtr = LN0->getBasePtr();
9877     unsigned PtrOff = 0;
9878
9879     if (Elt) {
9880       PtrOff = LVT.getSizeInBits() * Elt / 8;
9881       EVT PtrType = NewPtr.getValueType();
9882       if (TLI.isBigEndian())
9883         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9884       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9885                            DAG.getConstant(PtrOff, PtrType));
9886     }
9887
9888     // The replacement we need to do here is a little tricky: we need to
9889     // replace an extractelement of a load with a load.
9890     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9891     // Note that this replacement assumes that the extractvalue is the only
9892     // use of the load; that's okay because we don't want to perform this
9893     // transformation in other cases anyway.
9894     SDValue Load;
9895     SDValue Chain;
9896     if (NVT.bitsGT(LVT)) {
9897       // If the result type of vextract is wider than the load, then issue an
9898       // extending load instead.
9899       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9900         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9901       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9902                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9903                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9904                             Align, LN0->getTBAAInfo());
9905       Chain = Load.getValue(1);
9906     } else {
9907       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9908                          LN0->getPointerInfo().getWithOffset(PtrOff),
9909                          LN0->isVolatile(), LN0->isNonTemporal(),
9910                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9911       Chain = Load.getValue(1);
9912       if (NVT.bitsLT(LVT))
9913         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9914       else
9915         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9916     }
9917     WorkListRemover DeadNodes(*this);
9918     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9919     SDValue To[] = { Load, Chain };
9920     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9921     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9922     // worklist explicitly as well.
9923     AddToWorkList(Load.getNode());
9924     AddUsersToWorkList(Load.getNode()); // Add users too
9925     // Make sure to revisit this node to clean it up; it will usually be dead.
9926     AddToWorkList(N);
9927     return SDValue(N, 0);
9928   }
9929
9930   return SDValue();
9931 }
9932
9933 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9934 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9935   // We perform this optimization post type-legalization because
9936   // the type-legalizer often scalarizes integer-promoted vectors.
9937   // Performing this optimization before may create bit-casts which
9938   // will be type-legalized to complex code sequences.
9939   // We perform this optimization only before the operation legalizer because we
9940   // may introduce illegal operations.
9941   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9942     return SDValue();
9943
9944   unsigned NumInScalars = N->getNumOperands();
9945   SDLoc dl(N);
9946   EVT VT = N->getValueType(0);
9947
9948   // Check to see if this is a BUILD_VECTOR of a bunch of values
9949   // which come from any_extend or zero_extend nodes. If so, we can create
9950   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9951   // optimizations. We do not handle sign-extend because we can't fill the sign
9952   // using shuffles.
9953   EVT SourceType = MVT::Other;
9954   bool AllAnyExt = true;
9955
9956   for (unsigned i = 0; i != NumInScalars; ++i) {
9957     SDValue In = N->getOperand(i);
9958     // Ignore undef inputs.
9959     if (In.getOpcode() == ISD::UNDEF) continue;
9960
9961     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9962     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9963
9964     // Abort if the element is not an extension.
9965     if (!ZeroExt && !AnyExt) {
9966       SourceType = MVT::Other;
9967       break;
9968     }
9969
9970     // The input is a ZeroExt or AnyExt. Check the original type.
9971     EVT InTy = In.getOperand(0).getValueType();
9972
9973     // Check that all of the widened source types are the same.
9974     if (SourceType == MVT::Other)
9975       // First time.
9976       SourceType = InTy;
9977     else if (InTy != SourceType) {
9978       // Multiple income types. Abort.
9979       SourceType = MVT::Other;
9980       break;
9981     }
9982
9983     // Check if all of the extends are ANY_EXTENDs.
9984     AllAnyExt &= AnyExt;
9985   }
9986
9987   // In order to have valid types, all of the inputs must be extended from the
9988   // same source type and all of the inputs must be any or zero extend.
9989   // Scalar sizes must be a power of two.
9990   EVT OutScalarTy = VT.getScalarType();
9991   bool ValidTypes = SourceType != MVT::Other &&
9992                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9993                  isPowerOf2_32(SourceType.getSizeInBits());
9994
9995   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9996   // turn into a single shuffle instruction.
9997   if (!ValidTypes)
9998     return SDValue();
9999
10000   bool isLE = TLI.isLittleEndian();
10001   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10002   assert(ElemRatio > 1 && "Invalid element size ratio");
10003   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10004                                DAG.getConstant(0, SourceType);
10005
10006   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10007   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10008
10009   // Populate the new build_vector
10010   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10011     SDValue Cast = N->getOperand(i);
10012     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10013             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10014             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10015     SDValue In;
10016     if (Cast.getOpcode() == ISD::UNDEF)
10017       In = DAG.getUNDEF(SourceType);
10018     else
10019       In = Cast->getOperand(0);
10020     unsigned Index = isLE ? (i * ElemRatio) :
10021                             (i * ElemRatio + (ElemRatio - 1));
10022
10023     assert(Index < Ops.size() && "Invalid index");
10024     Ops[Index] = In;
10025   }
10026
10027   // The type of the new BUILD_VECTOR node.
10028   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10029   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10030          "Invalid vector size");
10031   // Check if the new vector type is legal.
10032   if (!isTypeLegal(VecVT)) return SDValue();
10033
10034   // Make the new BUILD_VECTOR.
10035   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10036
10037   // The new BUILD_VECTOR node has the potential to be further optimized.
10038   AddToWorkList(BV.getNode());
10039   // Bitcast to the desired type.
10040   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10041 }
10042
10043 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10044   EVT VT = N->getValueType(0);
10045
10046   unsigned NumInScalars = N->getNumOperands();
10047   SDLoc dl(N);
10048
10049   EVT SrcVT = MVT::Other;
10050   unsigned Opcode = ISD::DELETED_NODE;
10051   unsigned NumDefs = 0;
10052
10053   for (unsigned i = 0; i != NumInScalars; ++i) {
10054     SDValue In = N->getOperand(i);
10055     unsigned Opc = In.getOpcode();
10056
10057     if (Opc == ISD::UNDEF)
10058       continue;
10059
10060     // If all scalar values are floats and converted from integers.
10061     if (Opcode == ISD::DELETED_NODE &&
10062         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10063       Opcode = Opc;
10064     }
10065
10066     if (Opc != Opcode)
10067       return SDValue();
10068
10069     EVT InVT = In.getOperand(0).getValueType();
10070
10071     // If all scalar values are typed differently, bail out. It's chosen to
10072     // simplify BUILD_VECTOR of integer types.
10073     if (SrcVT == MVT::Other)
10074       SrcVT = InVT;
10075     if (SrcVT != InVT)
10076       return SDValue();
10077     NumDefs++;
10078   }
10079
10080   // If the vector has just one element defined, it's not worth to fold it into
10081   // a vectorized one.
10082   if (NumDefs < 2)
10083     return SDValue();
10084
10085   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10086          && "Should only handle conversion from integer to float.");
10087   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10088
10089   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10090
10091   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10092     return SDValue();
10093
10094   SmallVector<SDValue, 8> Opnds;
10095   for (unsigned i = 0; i != NumInScalars; ++i) {
10096     SDValue In = N->getOperand(i);
10097
10098     if (In.getOpcode() == ISD::UNDEF)
10099       Opnds.push_back(DAG.getUNDEF(SrcVT));
10100     else
10101       Opnds.push_back(In.getOperand(0));
10102   }
10103   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10104                            &Opnds[0], Opnds.size());
10105   AddToWorkList(BV.getNode());
10106
10107   return DAG.getNode(Opcode, dl, VT, BV);
10108 }
10109
10110 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10111   unsigned NumInScalars = N->getNumOperands();
10112   SDLoc dl(N);
10113   EVT VT = N->getValueType(0);
10114
10115   // A vector built entirely of undefs is undef.
10116   if (ISD::allOperandsUndef(N))
10117     return DAG.getUNDEF(VT);
10118
10119   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10120   if (V.getNode())
10121     return V;
10122
10123   V = reduceBuildVecConvertToConvertBuildVec(N);
10124   if (V.getNode())
10125     return V;
10126
10127   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10128   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10129   // at most two distinct vectors, turn this into a shuffle node.
10130
10131   // May only combine to shuffle after legalize if shuffle is legal.
10132   if (LegalOperations &&
10133       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10134     return SDValue();
10135
10136   SDValue VecIn1, VecIn2;
10137   for (unsigned i = 0; i != NumInScalars; ++i) {
10138     // Ignore undef inputs.
10139     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10140
10141     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10142     // constant index, bail out.
10143     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10144         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10145       VecIn1 = VecIn2 = SDValue(0, 0);
10146       break;
10147     }
10148
10149     // We allow up to two distinct input vectors.
10150     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10151     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10152       continue;
10153
10154     if (VecIn1.getNode() == 0) {
10155       VecIn1 = ExtractedFromVec;
10156     } else if (VecIn2.getNode() == 0) {
10157       VecIn2 = ExtractedFromVec;
10158     } else {
10159       // Too many inputs.
10160       VecIn1 = VecIn2 = SDValue(0, 0);
10161       break;
10162     }
10163   }
10164
10165     // If everything is good, we can make a shuffle operation.
10166   if (VecIn1.getNode()) {
10167     SmallVector<int, 8> Mask;
10168     for (unsigned i = 0; i != NumInScalars; ++i) {
10169       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10170         Mask.push_back(-1);
10171         continue;
10172       }
10173
10174       // If extracting from the first vector, just use the index directly.
10175       SDValue Extract = N->getOperand(i);
10176       SDValue ExtVal = Extract.getOperand(1);
10177       if (Extract.getOperand(0) == VecIn1) {
10178         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10179         if (ExtIndex > VT.getVectorNumElements())
10180           return SDValue();
10181
10182         Mask.push_back(ExtIndex);
10183         continue;
10184       }
10185
10186       // Otherwise, use InIdx + VecSize
10187       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10188       Mask.push_back(Idx+NumInScalars);
10189     }
10190
10191     // We can't generate a shuffle node with mismatched input and output types.
10192     // Attempt to transform a single input vector to the correct type.
10193     if ((VT != VecIn1.getValueType())) {
10194       // We don't support shuffeling between TWO values of different types.
10195       if (VecIn2.getNode() != 0)
10196         return SDValue();
10197
10198       // We only support widening of vectors which are half the size of the
10199       // output registers. For example XMM->YMM widening on X86 with AVX.
10200       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10201         return SDValue();
10202
10203       // If the input vector type has a different base type to the output
10204       // vector type, bail out.
10205       if (VecIn1.getValueType().getVectorElementType() !=
10206           VT.getVectorElementType())
10207         return SDValue();
10208
10209       // Widen the input vector by adding undef values.
10210       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10211                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10212     }
10213
10214     // If VecIn2 is unused then change it to undef.
10215     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10216
10217     // Check that we were able to transform all incoming values to the same
10218     // type.
10219     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10220         VecIn1.getValueType() != VT)
10221           return SDValue();
10222
10223     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10224     if (!isTypeLegal(VT))
10225       return SDValue();
10226
10227     // Return the new VECTOR_SHUFFLE node.
10228     SDValue Ops[2];
10229     Ops[0] = VecIn1;
10230     Ops[1] = VecIn2;
10231     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10232   }
10233
10234   return SDValue();
10235 }
10236
10237 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10238   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10239   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10240   // inputs come from at most two distinct vectors, turn this into a shuffle
10241   // node.
10242
10243   // If we only have one input vector, we don't need to do any concatenation.
10244   if (N->getNumOperands() == 1)
10245     return N->getOperand(0);
10246
10247   // Check if all of the operands are undefs.
10248   EVT VT = N->getValueType(0);
10249   if (ISD::allOperandsUndef(N))
10250     return DAG.getUNDEF(VT);
10251
10252   // Optimize concat_vectors where one of the vectors is undef.
10253   if (N->getNumOperands() == 2 &&
10254       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10255     SDValue In = N->getOperand(0);
10256     assert(In.getValueType().isVector() && "Must concat vectors");
10257
10258     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10259     if (In->getOpcode() == ISD::BITCAST &&
10260         !In->getOperand(0)->getValueType(0).isVector()) {
10261       SDValue Scalar = In->getOperand(0);
10262       EVT SclTy = Scalar->getValueType(0);
10263
10264       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10265         return SDValue();
10266
10267       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10268                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10269       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10270         return SDValue();
10271
10272       SDLoc dl = SDLoc(N);
10273       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10274       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10275     }
10276   }
10277
10278   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10279   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10280   if (N->getNumOperands() == 2 &&
10281       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10282       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10283     EVT VT = N->getValueType(0);
10284     SDValue N0 = N->getOperand(0);
10285     SDValue N1 = N->getOperand(1);
10286     SmallVector<SDValue, 8> Opnds;
10287     unsigned BuildVecNumElts =  N0.getNumOperands();
10288
10289     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10290       Opnds.push_back(N0.getOperand(i));
10291     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10292       Opnds.push_back(N1.getOperand(i));
10293
10294     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10295                        Opnds.size());
10296   }
10297
10298   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10299   // nodes often generate nop CONCAT_VECTOR nodes.
10300   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10301   // place the incoming vectors at the exact same location.
10302   SDValue SingleSource = SDValue();
10303   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10304
10305   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10306     SDValue Op = N->getOperand(i);
10307
10308     if (Op.getOpcode() == ISD::UNDEF)
10309       continue;
10310
10311     // Check if this is the identity extract:
10312     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10313       return SDValue();
10314
10315     // Find the single incoming vector for the extract_subvector.
10316     if (SingleSource.getNode()) {
10317       if (Op.getOperand(0) != SingleSource)
10318         return SDValue();
10319     } else {
10320       SingleSource = Op.getOperand(0);
10321
10322       // Check the source type is the same as the type of the result.
10323       // If not, this concat may extend the vector, so we can not
10324       // optimize it away.
10325       if (SingleSource.getValueType() != N->getValueType(0))
10326         return SDValue();
10327     }
10328
10329     unsigned IdentityIndex = i * PartNumElem;
10330     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10331     // The extract index must be constant.
10332     if (!CS)
10333       return SDValue();
10334
10335     // Check that we are reading from the identity index.
10336     if (CS->getZExtValue() != IdentityIndex)
10337       return SDValue();
10338   }
10339
10340   if (SingleSource.getNode())
10341     return SingleSource;
10342
10343   return SDValue();
10344 }
10345
10346 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10347   EVT NVT = N->getValueType(0);
10348   SDValue V = N->getOperand(0);
10349
10350   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10351     // Combine:
10352     //    (extract_subvec (concat V1, V2, ...), i)
10353     // Into:
10354     //    Vi if possible
10355     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10356     // type.
10357     if (V->getOperand(0).getValueType() != NVT)
10358       return SDValue();
10359     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10360     unsigned NumElems = NVT.getVectorNumElements();
10361     assert((Idx % NumElems) == 0 &&
10362            "IDX in concat is not a multiple of the result vector length.");
10363     return V->getOperand(Idx / NumElems);
10364   }
10365
10366   // Skip bitcasting
10367   if (V->getOpcode() == ISD::BITCAST)
10368     V = V.getOperand(0);
10369
10370   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10371     SDLoc dl(N);
10372     // Handle only simple case where vector being inserted and vector
10373     // being extracted are of same type, and are half size of larger vectors.
10374     EVT BigVT = V->getOperand(0).getValueType();
10375     EVT SmallVT = V->getOperand(1).getValueType();
10376     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10377       return SDValue();
10378
10379     // Only handle cases where both indexes are constants with the same type.
10380     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10381     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10382
10383     if (InsIdx && ExtIdx &&
10384         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10385         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10386       // Combine:
10387       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10388       // Into:
10389       //    indices are equal or bit offsets are equal => V1
10390       //    otherwise => (extract_subvec V1, ExtIdx)
10391       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10392           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10393         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10394       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10395                          DAG.getNode(ISD::BITCAST, dl,
10396                                      N->getOperand(0).getValueType(),
10397                                      V->getOperand(0)), N->getOperand(1));
10398     }
10399   }
10400
10401   return SDValue();
10402 }
10403
10404 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10405 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10406   EVT VT = N->getValueType(0);
10407   unsigned NumElts = VT.getVectorNumElements();
10408
10409   SDValue N0 = N->getOperand(0);
10410   SDValue N1 = N->getOperand(1);
10411   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10412
10413   SmallVector<SDValue, 4> Ops;
10414   EVT ConcatVT = N0.getOperand(0).getValueType();
10415   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10416   unsigned NumConcats = NumElts / NumElemsPerConcat;
10417
10418   // Look at every vector that's inserted. We're looking for exact
10419   // subvector-sized copies from a concatenated vector
10420   for (unsigned I = 0; I != NumConcats; ++I) {
10421     // Make sure we're dealing with a copy.
10422     unsigned Begin = I * NumElemsPerConcat;
10423     bool AllUndef = true, NoUndef = true;
10424     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10425       if (SVN->getMaskElt(J) >= 0)
10426         AllUndef = false;
10427       else
10428         NoUndef = false;
10429     }
10430
10431     if (NoUndef) {
10432       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10433         return SDValue();
10434
10435       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10436         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10437           return SDValue();
10438
10439       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10440       if (FirstElt < N0.getNumOperands())
10441         Ops.push_back(N0.getOperand(FirstElt));
10442       else
10443         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10444
10445     } else if (AllUndef) {
10446       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10447     } else { // Mixed with general masks and undefs, can't do optimization.
10448       return SDValue();
10449     }
10450   }
10451
10452   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10453                      Ops.size());
10454 }
10455
10456 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10457   EVT VT = N->getValueType(0);
10458   unsigned NumElts = VT.getVectorNumElements();
10459
10460   SDValue N0 = N->getOperand(0);
10461   SDValue N1 = N->getOperand(1);
10462
10463   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10464
10465   // Canonicalize shuffle undef, undef -> undef
10466   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10467     return DAG.getUNDEF(VT);
10468
10469   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10470
10471   // Canonicalize shuffle v, v -> v, undef
10472   if (N0 == N1) {
10473     SmallVector<int, 8> NewMask;
10474     for (unsigned i = 0; i != NumElts; ++i) {
10475       int Idx = SVN->getMaskElt(i);
10476       if (Idx >= (int)NumElts) Idx -= NumElts;
10477       NewMask.push_back(Idx);
10478     }
10479     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10480                                 &NewMask[0]);
10481   }
10482
10483   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10484   if (N0.getOpcode() == ISD::UNDEF) {
10485     SmallVector<int, 8> NewMask;
10486     for (unsigned i = 0; i != NumElts; ++i) {
10487       int Idx = SVN->getMaskElt(i);
10488       if (Idx >= 0) {
10489         if (Idx >= (int)NumElts)
10490           Idx -= NumElts;
10491         else
10492           Idx = -1; // remove reference to lhs
10493       }
10494       NewMask.push_back(Idx);
10495     }
10496     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10497                                 &NewMask[0]);
10498   }
10499
10500   // Remove references to rhs if it is undef
10501   if (N1.getOpcode() == ISD::UNDEF) {
10502     bool Changed = false;
10503     SmallVector<int, 8> NewMask;
10504     for (unsigned i = 0; i != NumElts; ++i) {
10505       int Idx = SVN->getMaskElt(i);
10506       if (Idx >= (int)NumElts) {
10507         Idx = -1;
10508         Changed = true;
10509       }
10510       NewMask.push_back(Idx);
10511     }
10512     if (Changed)
10513       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10514   }
10515
10516   // If it is a splat, check if the argument vector is another splat or a
10517   // build_vector with all scalar elements the same.
10518   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10519     SDNode *V = N0.getNode();
10520
10521     // If this is a bit convert that changes the element type of the vector but
10522     // not the number of vector elements, look through it.  Be careful not to
10523     // look though conversions that change things like v4f32 to v2f64.
10524     if (V->getOpcode() == ISD::BITCAST) {
10525       SDValue ConvInput = V->getOperand(0);
10526       if (ConvInput.getValueType().isVector() &&
10527           ConvInput.getValueType().getVectorNumElements() == NumElts)
10528         V = ConvInput.getNode();
10529     }
10530
10531     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10532       assert(V->getNumOperands() == NumElts &&
10533              "BUILD_VECTOR has wrong number of operands");
10534       SDValue Base;
10535       bool AllSame = true;
10536       for (unsigned i = 0; i != NumElts; ++i) {
10537         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10538           Base = V->getOperand(i);
10539           break;
10540         }
10541       }
10542       // Splat of <u, u, u, u>, return <u, u, u, u>
10543       if (!Base.getNode())
10544         return N0;
10545       for (unsigned i = 0; i != NumElts; ++i) {
10546         if (V->getOperand(i) != Base) {
10547           AllSame = false;
10548           break;
10549         }
10550       }
10551       // Splat of <x, x, x, x>, return <x, x, x, x>
10552       if (AllSame)
10553         return N0;
10554     }
10555   }
10556
10557   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10558       Level < AfterLegalizeVectorOps &&
10559       (N1.getOpcode() == ISD::UNDEF ||
10560       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10561        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10562     SDValue V = partitionShuffleOfConcats(N, DAG);
10563
10564     if (V.getNode())
10565       return V;
10566   }
10567
10568   // If this shuffle node is simply a swizzle of another shuffle node,
10569   // and it reverses the swizzle of the previous shuffle then we can
10570   // optimize shuffle(shuffle(x, undef), undef) -> x.
10571   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10572       N1.getOpcode() == ISD::UNDEF) {
10573
10574     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10575
10576     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10577     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10578       return SDValue();
10579
10580     // The incoming shuffle must be of the same type as the result of the
10581     // current shuffle.
10582     assert(OtherSV->getOperand(0).getValueType() == VT &&
10583            "Shuffle types don't match");
10584
10585     for (unsigned i = 0; i != NumElts; ++i) {
10586       int Idx = SVN->getMaskElt(i);
10587       assert(Idx < (int)NumElts && "Index references undef operand");
10588       // Next, this index comes from the first value, which is the incoming
10589       // shuffle. Adopt the incoming index.
10590       if (Idx >= 0)
10591         Idx = OtherSV->getMaskElt(Idx);
10592
10593       // The combined shuffle must map each index to itself.
10594       if (Idx >= 0 && (unsigned)Idx != i)
10595         return SDValue();
10596     }
10597
10598     return OtherSV->getOperand(0);
10599   }
10600
10601   return SDValue();
10602 }
10603
10604 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10605   SDValue N0 = N->getOperand(0);
10606   SDValue N2 = N->getOperand(2);
10607
10608   // If the input vector is a concatenation, and the insert replaces
10609   // one of the halves, we can optimize into a single concat_vectors.
10610   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10611       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10612     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10613     EVT VT = N->getValueType(0);
10614
10615     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10616     // (concat_vectors Z, Y)
10617     if (InsIdx == 0)
10618       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10619                          N->getOperand(1), N0.getOperand(1));
10620
10621     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10622     // (concat_vectors X, Z)
10623     if (InsIdx == VT.getVectorNumElements()/2)
10624       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10625                          N0.getOperand(0), N->getOperand(1));
10626   }
10627
10628   return SDValue();
10629 }
10630
10631 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10632 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10633 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10634 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10635 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10636   EVT VT = N->getValueType(0);
10637   SDLoc dl(N);
10638   SDValue LHS = N->getOperand(0);
10639   SDValue RHS = N->getOperand(1);
10640   if (N->getOpcode() == ISD::AND) {
10641     if (RHS.getOpcode() == ISD::BITCAST)
10642       RHS = RHS.getOperand(0);
10643     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10644       SmallVector<int, 8> Indices;
10645       unsigned NumElts = RHS.getNumOperands();
10646       for (unsigned i = 0; i != NumElts; ++i) {
10647         SDValue Elt = RHS.getOperand(i);
10648         if (!isa<ConstantSDNode>(Elt))
10649           return SDValue();
10650
10651         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10652           Indices.push_back(i);
10653         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10654           Indices.push_back(NumElts);
10655         else
10656           return SDValue();
10657       }
10658
10659       // Let's see if the target supports this vector_shuffle.
10660       EVT RVT = RHS.getValueType();
10661       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10662         return SDValue();
10663
10664       // Return the new VECTOR_SHUFFLE node.
10665       EVT EltVT = RVT.getVectorElementType();
10666       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10667                                      DAG.getConstant(0, EltVT));
10668       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10669                                  RVT, &ZeroOps[0], ZeroOps.size());
10670       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10671       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10672       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10673     }
10674   }
10675
10676   return SDValue();
10677 }
10678
10679 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10680 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10681   assert(N->getValueType(0).isVector() &&
10682          "SimplifyVBinOp only works on vectors!");
10683
10684   SDValue LHS = N->getOperand(0);
10685   SDValue RHS = N->getOperand(1);
10686   SDValue Shuffle = XformToShuffleWithZero(N);
10687   if (Shuffle.getNode()) return Shuffle;
10688
10689   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10690   // this operation.
10691   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10692       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10693     // Check if both vectors are constants. If not bail out.
10694     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10695           cast<BuildVectorSDNode>(RHS)->isConstant()))
10696       return SDValue();
10697
10698     SmallVector<SDValue, 8> Ops;
10699     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10700       SDValue LHSOp = LHS.getOperand(i);
10701       SDValue RHSOp = RHS.getOperand(i);
10702
10703       // Can't fold divide by zero.
10704       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10705           N->getOpcode() == ISD::FDIV) {
10706         if ((RHSOp.getOpcode() == ISD::Constant &&
10707              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10708             (RHSOp.getOpcode() == ISD::ConstantFP &&
10709              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10710           break;
10711       }
10712
10713       EVT VT = LHSOp.getValueType();
10714       EVT RVT = RHSOp.getValueType();
10715       if (RVT != VT) {
10716         // Integer BUILD_VECTOR operands may have types larger than the element
10717         // size (e.g., when the element type is not legal).  Prior to type
10718         // legalization, the types may not match between the two BUILD_VECTORS.
10719         // Truncate one of the operands to make them match.
10720         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10721           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10722         } else {
10723           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10724           VT = RVT;
10725         }
10726       }
10727       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10728                                    LHSOp, RHSOp);
10729       if (FoldOp.getOpcode() != ISD::UNDEF &&
10730           FoldOp.getOpcode() != ISD::Constant &&
10731           FoldOp.getOpcode() != ISD::ConstantFP)
10732         break;
10733       Ops.push_back(FoldOp);
10734       AddToWorkList(FoldOp.getNode());
10735     }
10736
10737     if (Ops.size() == LHS.getNumOperands())
10738       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10739                          LHS.getValueType(), &Ops[0], Ops.size());
10740   }
10741
10742   return SDValue();
10743 }
10744
10745 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10746 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10747   assert(N->getValueType(0).isVector() &&
10748          "SimplifyVUnaryOp only works on vectors!");
10749
10750   SDValue N0 = N->getOperand(0);
10751
10752   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10753     return SDValue();
10754
10755   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10756   SmallVector<SDValue, 8> Ops;
10757   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10758     SDValue Op = N0.getOperand(i);
10759     if (Op.getOpcode() != ISD::UNDEF &&
10760         Op.getOpcode() != ISD::ConstantFP)
10761       break;
10762     EVT EltVT = Op.getValueType();
10763     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10764     if (FoldOp.getOpcode() != ISD::UNDEF &&
10765         FoldOp.getOpcode() != ISD::ConstantFP)
10766       break;
10767     Ops.push_back(FoldOp);
10768     AddToWorkList(FoldOp.getNode());
10769   }
10770
10771   if (Ops.size() != N0.getNumOperands())
10772     return SDValue();
10773
10774   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10775                      N0.getValueType(), &Ops[0], Ops.size());
10776 }
10777
10778 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10779                                     SDValue N1, SDValue N2){
10780   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10781
10782   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10783                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10784
10785   // If we got a simplified select_cc node back from SimplifySelectCC, then
10786   // break it down into a new SETCC node, and a new SELECT node, and then return
10787   // the SELECT node, since we were called with a SELECT node.
10788   if (SCC.getNode()) {
10789     // Check to see if we got a select_cc back (to turn into setcc/select).
10790     // Otherwise, just return whatever node we got back, like fabs.
10791     if (SCC.getOpcode() == ISD::SELECT_CC) {
10792       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10793                                   N0.getValueType(),
10794                                   SCC.getOperand(0), SCC.getOperand(1),
10795                                   SCC.getOperand(4));
10796       AddToWorkList(SETCC.getNode());
10797       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10798                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10799     }
10800
10801     return SCC;
10802   }
10803   return SDValue();
10804 }
10805
10806 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10807 /// are the two values being selected between, see if we can simplify the
10808 /// select.  Callers of this should assume that TheSelect is deleted if this
10809 /// returns true.  As such, they should return the appropriate thing (e.g. the
10810 /// node) back to the top-level of the DAG combiner loop to avoid it being
10811 /// looked at.
10812 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10813                                     SDValue RHS) {
10814
10815   // Cannot simplify select with vector condition
10816   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10817
10818   // If this is a select from two identical things, try to pull the operation
10819   // through the select.
10820   if (LHS.getOpcode() != RHS.getOpcode() ||
10821       !LHS.hasOneUse() || !RHS.hasOneUse())
10822     return false;
10823
10824   // If this is a load and the token chain is identical, replace the select
10825   // of two loads with a load through a select of the address to load from.
10826   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10827   // constants have been dropped into the constant pool.
10828   if (LHS.getOpcode() == ISD::LOAD) {
10829     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10830     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10831
10832     // Token chains must be identical.
10833     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10834         // Do not let this transformation reduce the number of volatile loads.
10835         LLD->isVolatile() || RLD->isVolatile() ||
10836         // If this is an EXTLOAD, the VT's must match.
10837         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10838         // If this is an EXTLOAD, the kind of extension must match.
10839         (LLD->getExtensionType() != RLD->getExtensionType() &&
10840          // The only exception is if one of the extensions is anyext.
10841          LLD->getExtensionType() != ISD::EXTLOAD &&
10842          RLD->getExtensionType() != ISD::EXTLOAD) ||
10843         // FIXME: this discards src value information.  This is
10844         // over-conservative. It would be beneficial to be able to remember
10845         // both potential memory locations.  Since we are discarding
10846         // src value info, don't do the transformation if the memory
10847         // locations are not in the default address space.
10848         LLD->getPointerInfo().getAddrSpace() != 0 ||
10849         RLD->getPointerInfo().getAddrSpace() != 0 ||
10850         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10851                                       LLD->getBasePtr().getValueType()))
10852       return false;
10853
10854     // Check that the select condition doesn't reach either load.  If so,
10855     // folding this will induce a cycle into the DAG.  If not, this is safe to
10856     // xform, so create a select of the addresses.
10857     SDValue Addr;
10858     if (TheSelect->getOpcode() == ISD::SELECT) {
10859       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10860       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10861           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10862         return false;
10863       // The loads must not depend on one another.
10864       if (LLD->isPredecessorOf(RLD) ||
10865           RLD->isPredecessorOf(LLD))
10866         return false;
10867       Addr = DAG.getSelect(SDLoc(TheSelect),
10868                            LLD->getBasePtr().getValueType(),
10869                            TheSelect->getOperand(0), LLD->getBasePtr(),
10870                            RLD->getBasePtr());
10871     } else {  // Otherwise SELECT_CC
10872       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10873       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10874
10875       if ((LLD->hasAnyUseOfValue(1) &&
10876            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10877           (RLD->hasAnyUseOfValue(1) &&
10878            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10879         return false;
10880
10881       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10882                          LLD->getBasePtr().getValueType(),
10883                          TheSelect->getOperand(0),
10884                          TheSelect->getOperand(1),
10885                          LLD->getBasePtr(), RLD->getBasePtr(),
10886                          TheSelect->getOperand(4));
10887     }
10888
10889     SDValue Load;
10890     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10891       Load = DAG.getLoad(TheSelect->getValueType(0),
10892                          SDLoc(TheSelect),
10893                          // FIXME: Discards pointer and TBAA info.
10894                          LLD->getChain(), Addr, MachinePointerInfo(),
10895                          LLD->isVolatile(), LLD->isNonTemporal(),
10896                          LLD->isInvariant(), LLD->getAlignment());
10897     } else {
10898       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10899                             RLD->getExtensionType() : LLD->getExtensionType(),
10900                             SDLoc(TheSelect),
10901                             TheSelect->getValueType(0),
10902                             // FIXME: Discards pointer and TBAA info.
10903                             LLD->getChain(), Addr, MachinePointerInfo(),
10904                             LLD->getMemoryVT(), LLD->isVolatile(),
10905                             LLD->isNonTemporal(), LLD->getAlignment());
10906     }
10907
10908     // Users of the select now use the result of the load.
10909     CombineTo(TheSelect, Load);
10910
10911     // Users of the old loads now use the new load's chain.  We know the
10912     // old-load value is dead now.
10913     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10914     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10915     return true;
10916   }
10917
10918   return false;
10919 }
10920
10921 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10922 /// where 'cond' is the comparison specified by CC.
10923 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10924                                       SDValue N2, SDValue N3,
10925                                       ISD::CondCode CC, bool NotExtCompare) {
10926   // (x ? y : y) -> y.
10927   if (N2 == N3) return N2;
10928
10929   EVT VT = N2.getValueType();
10930   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10931   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10932   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10933
10934   // Determine if the condition we're dealing with is constant
10935   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10936                               N0, N1, CC, DL, false);
10937   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10938   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10939
10940   // fold select_cc true, x, y -> x
10941   if (SCCC && !SCCC->isNullValue())
10942     return N2;
10943   // fold select_cc false, x, y -> y
10944   if (SCCC && SCCC->isNullValue())
10945     return N3;
10946
10947   // Check to see if we can simplify the select into an fabs node
10948   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10949     // Allow either -0.0 or 0.0
10950     if (CFP->getValueAPF().isZero()) {
10951       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10952       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10953           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10954           N2 == N3.getOperand(0))
10955         return DAG.getNode(ISD::FABS, DL, VT, N0);
10956
10957       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10958       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10959           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10960           N2.getOperand(0) == N3)
10961         return DAG.getNode(ISD::FABS, DL, VT, N3);
10962     }
10963   }
10964
10965   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10966   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10967   // in it.  This is a win when the constant is not otherwise available because
10968   // it replaces two constant pool loads with one.  We only do this if the FP
10969   // type is known to be legal, because if it isn't, then we are before legalize
10970   // types an we want the other legalization to happen first (e.g. to avoid
10971   // messing with soft float) and if the ConstantFP is not legal, because if
10972   // it is legal, we may not need to store the FP constant in a constant pool.
10973   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10974     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10975       if (TLI.isTypeLegal(N2.getValueType()) &&
10976           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10977            TargetLowering::Legal) &&
10978           // If both constants have multiple uses, then we won't need to do an
10979           // extra load, they are likely around in registers for other users.
10980           (TV->hasOneUse() || FV->hasOneUse())) {
10981         Constant *Elts[] = {
10982           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10983           const_cast<ConstantFP*>(TV->getConstantFPValue())
10984         };
10985         Type *FPTy = Elts[0]->getType();
10986         const DataLayout &TD = *TLI.getDataLayout();
10987
10988         // Create a ConstantArray of the two constants.
10989         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10990         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10991                                             TD.getPrefTypeAlignment(FPTy));
10992         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10993
10994         // Get the offsets to the 0 and 1 element of the array so that we can
10995         // select between them.
10996         SDValue Zero = DAG.getIntPtrConstant(0);
10997         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10998         SDValue One = DAG.getIntPtrConstant(EltSize);
10999
11000         SDValue Cond = DAG.getSetCC(DL,
11001                                     getSetCCResultType(N0.getValueType()),
11002                                     N0, N1, CC);
11003         AddToWorkList(Cond.getNode());
11004         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11005                                           Cond, One, Zero);
11006         AddToWorkList(CstOffset.getNode());
11007         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11008                             CstOffset);
11009         AddToWorkList(CPIdx.getNode());
11010         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11011                            MachinePointerInfo::getConstantPool(), false,
11012                            false, false, Alignment);
11013
11014       }
11015     }
11016
11017   // Check to see if we can perform the "gzip trick", transforming
11018   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11019   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11020       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11021        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11022     EVT XType = N0.getValueType();
11023     EVT AType = N2.getValueType();
11024     if (XType.bitsGE(AType)) {
11025       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11026       // single-bit constant.
11027       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11028         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11029         ShCtV = XType.getSizeInBits()-ShCtV-1;
11030         SDValue ShCt = DAG.getConstant(ShCtV,
11031                                        getShiftAmountTy(N0.getValueType()));
11032         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11033                                     XType, N0, ShCt);
11034         AddToWorkList(Shift.getNode());
11035
11036         if (XType.bitsGT(AType)) {
11037           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11038           AddToWorkList(Shift.getNode());
11039         }
11040
11041         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11042       }
11043
11044       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11045                                   XType, N0,
11046                                   DAG.getConstant(XType.getSizeInBits()-1,
11047                                          getShiftAmountTy(N0.getValueType())));
11048       AddToWorkList(Shift.getNode());
11049
11050       if (XType.bitsGT(AType)) {
11051         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11052         AddToWorkList(Shift.getNode());
11053       }
11054
11055       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11056     }
11057   }
11058
11059   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11060   // where y is has a single bit set.
11061   // A plaintext description would be, we can turn the SELECT_CC into an AND
11062   // when the condition can be materialized as an all-ones register.  Any
11063   // single bit-test can be materialized as an all-ones register with
11064   // shift-left and shift-right-arith.
11065   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11066       N0->getValueType(0) == VT &&
11067       N1C && N1C->isNullValue() &&
11068       N2C && N2C->isNullValue()) {
11069     SDValue AndLHS = N0->getOperand(0);
11070     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11071     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11072       // Shift the tested bit over the sign bit.
11073       APInt AndMask = ConstAndRHS->getAPIntValue();
11074       SDValue ShlAmt =
11075         DAG.getConstant(AndMask.countLeadingZeros(),
11076                         getShiftAmountTy(AndLHS.getValueType()));
11077       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11078
11079       // Now arithmetic right shift it all the way over, so the result is either
11080       // all-ones, or zero.
11081       SDValue ShrAmt =
11082         DAG.getConstant(AndMask.getBitWidth()-1,
11083                         getShiftAmountTy(Shl.getValueType()));
11084       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11085
11086       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11087     }
11088   }
11089
11090   // fold select C, 16, 0 -> shl C, 4
11091   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11092     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11093       TargetLowering::ZeroOrOneBooleanContent) {
11094
11095     // If the caller doesn't want us to simplify this into a zext of a compare,
11096     // don't do it.
11097     if (NotExtCompare && N2C->getAPIntValue() == 1)
11098       return SDValue();
11099
11100     // Get a SetCC of the condition
11101     // NOTE: Don't create a SETCC if it's not legal on this target.
11102     if (!LegalOperations ||
11103         TLI.isOperationLegal(ISD::SETCC,
11104           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11105       SDValue Temp, SCC;
11106       // cast from setcc result type to select result type
11107       if (LegalTypes) {
11108         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11109                             N0, N1, CC);
11110         if (N2.getValueType().bitsLT(SCC.getValueType()))
11111           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11112                                         N2.getValueType());
11113         else
11114           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11115                              N2.getValueType(), SCC);
11116       } else {
11117         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11118         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11119                            N2.getValueType(), SCC);
11120       }
11121
11122       AddToWorkList(SCC.getNode());
11123       AddToWorkList(Temp.getNode());
11124
11125       if (N2C->getAPIntValue() == 1)
11126         return Temp;
11127
11128       // shl setcc result by log2 n2c
11129       return DAG.getNode(
11130           ISD::SHL, DL, N2.getValueType(), Temp,
11131           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11132                           getShiftAmountTy(Temp.getValueType())));
11133     }
11134   }
11135
11136   // Check to see if this is the equivalent of setcc
11137   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11138   // otherwise, go ahead with the folds.
11139   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11140     EVT XType = N0.getValueType();
11141     if (!LegalOperations ||
11142         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11143       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11144       if (Res.getValueType() != VT)
11145         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11146       return Res;
11147     }
11148
11149     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11150     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11151         (!LegalOperations ||
11152          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11153       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11154       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11155                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11156                                        getShiftAmountTy(Ctlz.getValueType())));
11157     }
11158     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11159     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11160       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11161                                   XType, DAG.getConstant(0, XType), N0);
11162       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11163       return DAG.getNode(ISD::SRL, DL, XType,
11164                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11165                          DAG.getConstant(XType.getSizeInBits()-1,
11166                                          getShiftAmountTy(XType)));
11167     }
11168     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11169     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11170       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11171                                  DAG.getConstant(XType.getSizeInBits()-1,
11172                                          getShiftAmountTy(N0.getValueType())));
11173       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11174     }
11175   }
11176
11177   // Check to see if this is an integer abs.
11178   // select_cc setg[te] X,  0,  X, -X ->
11179   // select_cc setgt    X, -1,  X, -X ->
11180   // select_cc setl[te] X,  0, -X,  X ->
11181   // select_cc setlt    X,  1, -X,  X ->
11182   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11183   if (N1C) {
11184     ConstantSDNode *SubC = NULL;
11185     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11186          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11187         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11188       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11189     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11190               (N1C->isOne() && CC == ISD::SETLT)) &&
11191              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11192       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11193
11194     EVT XType = N0.getValueType();
11195     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11196       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11197                                   N0,
11198                                   DAG.getConstant(XType.getSizeInBits()-1,
11199                                          getShiftAmountTy(N0.getValueType())));
11200       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11201                                 XType, N0, Shift);
11202       AddToWorkList(Shift.getNode());
11203       AddToWorkList(Add.getNode());
11204       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11205     }
11206   }
11207
11208   return SDValue();
11209 }
11210
11211 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11212 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11213                                    SDValue N1, ISD::CondCode Cond,
11214                                    SDLoc DL, bool foldBooleans) {
11215   TargetLowering::DAGCombinerInfo
11216     DagCombineInfo(DAG, Level, false, this);
11217   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11218 }
11219
11220 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11221 /// return a DAG expression to select that will generate the same value by
11222 /// multiplying by a magic number.  See:
11223 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11224 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11225   std::vector<SDNode*> Built;
11226   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11227
11228   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11229        ii != ee; ++ii)
11230     AddToWorkList(*ii);
11231   return S;
11232 }
11233
11234 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11235 /// return a DAG expression to select that will generate the same value by
11236 /// multiplying by a magic number.  See:
11237 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11238 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11239   std::vector<SDNode*> Built;
11240   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11241
11242   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11243        ii != ee; ++ii)
11244     AddToWorkList(*ii);
11245   return S;
11246 }
11247
11248 /// FindBaseOffset - Return true if base is a frame index, which is known not
11249 // to alias with anything but itself.  Provides base object and offset as
11250 // results.
11251 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11252                            const GlobalValue *&GV, const void *&CV) {
11253   // Assume it is a primitive operation.
11254   Base = Ptr; Offset = 0; GV = 0; CV = 0;
11255
11256   // If it's an adding a simple constant then integrate the offset.
11257   if (Base.getOpcode() == ISD::ADD) {
11258     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11259       Base = Base.getOperand(0);
11260       Offset += C->getZExtValue();
11261     }
11262   }
11263
11264   // Return the underlying GlobalValue, and update the Offset.  Return false
11265   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11266   // by multiple nodes with different offsets.
11267   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11268     GV = G->getGlobal();
11269     Offset += G->getOffset();
11270     return false;
11271   }
11272
11273   // Return the underlying Constant value, and update the Offset.  Return false
11274   // for ConstantSDNodes since the same constant pool entry may be represented
11275   // by multiple nodes with different offsets.
11276   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11277     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11278                                          : (const void *)C->getConstVal();
11279     Offset += C->getOffset();
11280     return false;
11281   }
11282   // If it's any of the following then it can't alias with anything but itself.
11283   return isa<FrameIndexSDNode>(Base);
11284 }
11285
11286 /// isAlias - Return true if there is any possibility that the two addresses
11287 /// overlap.
11288 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11289                           const Value *SrcValue1, int SrcValueOffset1,
11290                           unsigned SrcValueAlign1,
11291                           const MDNode *TBAAInfo1,
11292                           SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11293                           const Value *SrcValue2, int SrcValueOffset2,
11294                           unsigned SrcValueAlign2,
11295                           const MDNode *TBAAInfo2) const {
11296   // If they are the same then they must be aliases.
11297   if (Ptr1 == Ptr2) return true;
11298
11299   // If they are both volatile then they cannot be reordered.
11300   if (IsVolatile1 && IsVolatile2) return true;
11301
11302   // Gather base node and offset information.
11303   SDValue Base1, Base2;
11304   int64_t Offset1, Offset2;
11305   const GlobalValue *GV1, *GV2;
11306   const void *CV1, *CV2;
11307   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11308   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11309
11310   // If they have a same base address then check to see if they overlap.
11311   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11312     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11313
11314   // It is possible for different frame indices to alias each other, mostly
11315   // when tail call optimization reuses return address slots for arguments.
11316   // To catch this case, look up the actual index of frame indices to compute
11317   // the real alias relationship.
11318   if (isFrameIndex1 && isFrameIndex2) {
11319     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11320     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11321     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11322     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11323   }
11324
11325   // Otherwise, if we know what the bases are, and they aren't identical, then
11326   // we know they cannot alias.
11327   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11328     return false;
11329
11330   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11331   // compared to the size and offset of the access, we may be able to prove they
11332   // do not alias.  This check is conservative for now to catch cases created by
11333   // splitting vector types.
11334   if ((SrcValueAlign1 == SrcValueAlign2) &&
11335       (SrcValueOffset1 != SrcValueOffset2) &&
11336       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11337     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11338     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11339
11340     // There is no overlap between these relatively aligned accesses of similar
11341     // size, return no alias.
11342     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11343       return false;
11344   }
11345
11346   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11347     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11348 #ifndef NDEBUG
11349   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11350       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11351     UseAA = false;
11352 #endif
11353   if (UseAA && SrcValue1 && SrcValue2) {
11354     // Use alias analysis information.
11355     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11356     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11357     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11358     AliasAnalysis::AliasResult AAResult =
11359       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11360                                        UseTBAA ? TBAAInfo1 : 0),
11361                AliasAnalysis::Location(SrcValue2, Overlap2,
11362                                        UseTBAA ? TBAAInfo2 : 0));
11363     if (AAResult == AliasAnalysis::NoAlias)
11364       return false;
11365   }
11366
11367   // Otherwise we have to assume they alias.
11368   return true;
11369 }
11370
11371 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11372   SDValue Ptr0, Ptr1;
11373   int64_t Size0, Size1;
11374   bool IsVolatile0, IsVolatile1;
11375   const Value *SrcValue0, *SrcValue1;
11376   int SrcValueOffset0, SrcValueOffset1;
11377   unsigned SrcValueAlign0, SrcValueAlign1;
11378   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11379   FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11380                 SrcValueAlign0, SrcTBAAInfo0);
11381   FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11382                 SrcValueAlign1, SrcTBAAInfo1);
11383   return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11384                  SrcValueAlign0, SrcTBAAInfo0,
11385                  Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11386                  SrcValueAlign1, SrcTBAAInfo1);
11387 }
11388
11389 /// FindAliasInfo - Extracts the relevant alias information from the memory
11390 /// node.  Returns true if the operand was a nonvolatile load.
11391 bool DAGCombiner::FindAliasInfo(SDNode *N,
11392                                 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11393                                 const Value *&SrcValue,
11394                                 int &SrcValueOffset,
11395                                 unsigned &SrcValueAlign,
11396                                 const MDNode *&TBAAInfo) const {
11397   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11398
11399   Ptr = LS->getBasePtr();
11400   Size = LS->getMemoryVT().getSizeInBits() >> 3;
11401   IsVolatile = LS->isVolatile();
11402   SrcValue = LS->getSrcValue();
11403   SrcValueOffset = LS->getSrcValueOffset();
11404   SrcValueAlign = LS->getOriginalAlignment();
11405   TBAAInfo = LS->getTBAAInfo();
11406   return isa<LoadSDNode>(LS) && !IsVolatile;
11407 }
11408
11409 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11410 /// looking for aliasing nodes and adding them to the Aliases vector.
11411 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11412                                    SmallVectorImpl<SDValue> &Aliases) {
11413   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11414   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11415
11416   // Get alias information for node.
11417   SDValue Ptr;
11418   int64_t Size;
11419   bool IsVolatile;
11420   const Value *SrcValue;
11421   int SrcValueOffset;
11422   unsigned SrcValueAlign;
11423   const MDNode *SrcTBAAInfo;
11424   bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11425                               SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11426
11427   // Starting off.
11428   Chains.push_back(OriginalChain);
11429   unsigned Depth = 0;
11430
11431   // Look at each chain and determine if it is an alias.  If so, add it to the
11432   // aliases list.  If not, then continue up the chain looking for the next
11433   // candidate.
11434   while (!Chains.empty()) {
11435     SDValue Chain = Chains.back();
11436     Chains.pop_back();
11437
11438     // For TokenFactor nodes, look at each operand and only continue up the
11439     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11440     // find more and revert to original chain since the xform is unlikely to be
11441     // profitable.
11442     //
11443     // FIXME: The depth check could be made to return the last non-aliasing
11444     // chain we found before we hit a tokenfactor rather than the original
11445     // chain.
11446     if (Depth > 6 || Aliases.size() == 2) {
11447       Aliases.clear();
11448       Aliases.push_back(OriginalChain);
11449       return;
11450     }
11451
11452     // Don't bother if we've been before.
11453     if (!Visited.insert(Chain.getNode()))
11454       continue;
11455
11456     switch (Chain.getOpcode()) {
11457     case ISD::EntryToken:
11458       // Entry token is ideal chain operand, but handled in FindBetterChain.
11459       break;
11460
11461     case ISD::LOAD:
11462     case ISD::STORE: {
11463       // Get alias information for Chain.
11464       SDValue OpPtr;
11465       int64_t OpSize;
11466       bool OpIsVolatile;
11467       const Value *OpSrcValue;
11468       int OpSrcValueOffset;
11469       unsigned OpSrcValueAlign;
11470       const MDNode *OpSrcTBAAInfo;
11471       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11472                                     OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11473                                     OpSrcValueAlign,
11474                                     OpSrcTBAAInfo);
11475
11476       // If chain is alias then stop here.
11477       if (!(IsLoad && IsOpLoad) &&
11478           isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11479                   SrcValueAlign, SrcTBAAInfo,
11480                   OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11481                   OpSrcValueAlign, OpSrcTBAAInfo)) {
11482         Aliases.push_back(Chain);
11483       } else {
11484         // Look further up the chain.
11485         Chains.push_back(Chain.getOperand(0));
11486         ++Depth;
11487       }
11488       break;
11489     }
11490
11491     case ISD::TokenFactor:
11492       // We have to check each of the operands of the token factor for "small"
11493       // token factors, so we queue them up.  Adding the operands to the queue
11494       // (stack) in reverse order maintains the original order and increases the
11495       // likelihood that getNode will find a matching token factor (CSE.)
11496       if (Chain.getNumOperands() > 16) {
11497         Aliases.push_back(Chain);
11498         break;
11499       }
11500       for (unsigned n = Chain.getNumOperands(); n;)
11501         Chains.push_back(Chain.getOperand(--n));
11502       ++Depth;
11503       break;
11504
11505     default:
11506       // For all other instructions we will just have to take what we can get.
11507       Aliases.push_back(Chain);
11508       break;
11509     }
11510   }
11511
11512   // We need to be careful here to also search for aliases through the
11513   // value operand of a store, etc. Consider the following situation:
11514   //   Token1 = ...
11515   //   L1 = load Token1, %52
11516   //   S1 = store Token1, L1, %51
11517   //   L2 = load Token1, %52+8
11518   //   S2 = store Token1, L2, %51+8
11519   //   Token2 = Token(S1, S2)
11520   //   L3 = load Token2, %53
11521   //   S3 = store Token2, L3, %52
11522   //   L4 = load Token2, %53+8
11523   //   S4 = store Token2, L4, %52+8
11524   // If we search for aliases of S3 (which loads address %52), and we look
11525   // only through the chain, then we'll miss the trivial dependence on L1
11526   // (which also loads from %52). We then might change all loads and
11527   // stores to use Token1 as their chain operand, which could result in
11528   // copying %53 into %52 before copying %52 into %51 (which should
11529   // happen first).
11530   //
11531   // The problem is, however, that searching for such data dependencies
11532   // can become expensive, and the cost is not directly related to the
11533   // chain depth. Instead, we'll rule out such configurations here by
11534   // insisting that we've visited all chain users (except for users
11535   // of the original chain, which is not necessary). When doing this,
11536   // we need to look through nodes we don't care about (otherwise, things
11537   // like register copies will interfere with trivial cases).
11538
11539   SmallVector<const SDNode *, 16> Worklist;
11540   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11541        IE = Visited.end(); I != IE; ++I)
11542     if (*I != OriginalChain.getNode())
11543       Worklist.push_back(*I);
11544
11545   while (!Worklist.empty()) {
11546     const SDNode *M = Worklist.pop_back_val();
11547
11548     // We have already visited M, and want to make sure we've visited any uses
11549     // of M that we care about. For uses that we've not visisted, and don't
11550     // care about, queue them to the worklist.
11551
11552     for (SDNode::use_iterator UI = M->use_begin(),
11553          UIE = M->use_end(); UI != UIE; ++UI)
11554       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11555         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11556           // We've not visited this use, and we care about it (it could have an
11557           // ordering dependency with the original node).
11558           Aliases.clear();
11559           Aliases.push_back(OriginalChain);
11560           return;
11561         }
11562
11563         // We've not visited this use, but we don't care about it. Mark it as
11564         // visited and enqueue it to the worklist.
11565         Worklist.push_back(*UI);
11566       }
11567   }
11568 }
11569
11570 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11571 /// for a better chain (aliasing node.)
11572 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11573   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11574
11575   // Accumulate all the aliases to this node.
11576   GatherAllAliases(N, OldChain, Aliases);
11577
11578   // If no operands then chain to entry token.
11579   if (Aliases.size() == 0)
11580     return DAG.getEntryNode();
11581
11582   // If a single operand then chain to it.  We don't need to revisit it.
11583   if (Aliases.size() == 1)
11584     return Aliases[0];
11585
11586   // Construct a custom tailored token factor.
11587   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11588                      &Aliases[0], Aliases.size());
11589 }
11590
11591 // SelectionDAG::Combine - This is the entry point for the file.
11592 //
11593 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11594                            CodeGenOpt::Level OptLevel) {
11595   /// run - This is the main entry point to this class.
11596   ///
11597   DAGCombiner(*this, AA, OptLevel).Run(Level);
11598 }