290f2a1ea278ab0745f9f5b145ce2ac6dc2c305b
[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 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunction.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/Target/TargetLowering.h"
35 #include "llvm/Target/TargetMachine.h"
36 #include "llvm/Target/TargetOptions.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 #define DEBUG_TYPE "dagcombine"
43
44 STATISTIC(NodesCombined   , "Number of dag nodes combined");
45 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
46 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
47 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
48 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
49 STATISTIC(SlicedLoads, "Number of load sliced");
50
51 namespace {
52   static cl::opt<bool>
53     CombinerAA("combiner-alias-analysis", cl::Hidden,
54                cl::desc("Enable DAG combiner alias-analysis heuristics"));
55
56   static cl::opt<bool>
57     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58                cl::desc("Enable DAG combiner's use of IR alias analysis"));
59
60   static cl::opt<bool>
61     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
62                cl::desc("Enable DAG combiner's use of TBAA"));
63
64 #ifndef NDEBUG
65   static cl::opt<std::string>
66     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
67                cl::desc("Only use DAG-combiner alias analysis in this"
68                         " function"));
69 #endif
70
71   /// Hidden option to stress test load slicing, i.e., when this option
72   /// is enabled, load slicing bypasses most of its profitability guards.
73   static cl::opt<bool>
74   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
75                     cl::desc("Bypass the profitability model of load "
76                              "slicing"),
77                     cl::init(false));
78
79 //------------------------------ DAGCombiner ---------------------------------//
80
81   class DAGCombiner {
82     SelectionDAG &DAG;
83     const TargetLowering &TLI;
84     CombineLevel Level;
85     CodeGenOpt::Level OptLevel;
86     bool LegalOperations;
87     bool LegalTypes;
88     bool ForCodeSize;
89
90     // Worklist of all of the nodes that need to be simplified.
91     //
92     // This has the semantics that when adding to the worklist,
93     // the item added must be next to be processed. It should
94     // also only appear once. The naive approach to this takes
95     // linear time.
96     //
97     // To reduce the insert/remove time to logarithmic, we use
98     // a set and a vector to maintain our worklist.
99     //
100     // The set contains the items on the worklist, but does not
101     // maintain the order they should be visited.
102     //
103     // The vector maintains the order nodes should be visited, but may
104     // contain duplicate or removed nodes. When choosing a node to
105     // visit, we pop off the order stack until we find an item that is
106     // also in the contents set. All operations are O(log N).
107     SmallPtrSet<SDNode*, 64> WorkListContents;
108     SmallVector<SDNode*, 64> WorkListOrder;
109
110     // AA - Used for DAG load/store alias analysis.
111     AliasAnalysis &AA;
112
113     /// AddUsersToWorkList - When an instruction is simplified, add all users of
114     /// the instruction to the work lists because they might get more simplified
115     /// now.
116     ///
117     void AddUsersToWorkList(SDNode *N) {
118       for (SDNode *Node : N->uses())
119         AddToWorkList(Node);
120     }
121
122     /// visit - call the node-specific routine that knows how to fold each
123     /// particular type of node.
124     SDValue visit(SDNode *N);
125
126   public:
127     /// AddToWorkList - Add to the work list making sure its instance is at the
128     /// back (next to be processed.)
129     void AddToWorkList(SDNode *N) {
130       WorkListContents.insert(N);
131       WorkListOrder.push_back(N);
132     }
133
134     /// removeFromWorkList - remove all instances of N from the worklist.
135     ///
136     void removeFromWorkList(SDNode *N) {
137       WorkListContents.erase(N);
138     }
139
140     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
141                       bool AddTo = true);
142
143     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
144       return CombineTo(N, &Res, 1, AddTo);
145     }
146
147     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
148                       bool AddTo = true) {
149       SDValue To[] = { Res0, Res1 };
150       return CombineTo(N, To, 2, AddTo);
151     }
152
153     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
154
155   private:
156
157     /// SimplifyDemandedBits - Check the specified integer node value to see if
158     /// it can be simplified or if things it uses can be simplified by bit
159     /// propagation.  If so, return true.
160     bool SimplifyDemandedBits(SDValue Op) {
161       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
162       APInt Demanded = APInt::getAllOnesValue(BitWidth);
163       return SimplifyDemandedBits(Op, Demanded);
164     }
165
166     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
167
168     bool CombineToPreIndexedLoadStore(SDNode *N);
169     bool CombineToPostIndexedLoadStore(SDNode *N);
170     bool SliceUpLoad(SDNode *N);
171
172     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
173     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
174     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
175     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
176     SDValue PromoteIntBinOp(SDValue Op);
177     SDValue PromoteIntShiftOp(SDValue Op);
178     SDValue PromoteExtend(SDValue Op);
179     bool PromoteLoad(SDValue Op);
180
181     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
182                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
183                          ISD::NodeType ExtType);
184
185     /// combine - call the node-specific routine that knows how to fold each
186     /// particular type of node. If that doesn't do anything, try the
187     /// target-specific DAG combines.
188     SDValue combine(SDNode *N);
189
190     // Visitation implementation - Implement dag node combining for different
191     // node types.  The semantics are as follows:
192     // Return Value:
193     //   SDValue.getNode() == 0 - No change was made
194     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
195     //   otherwise              - N should be replaced by the returned Operand.
196     //
197     SDValue visitTokenFactor(SDNode *N);
198     SDValue visitMERGE_VALUES(SDNode *N);
199     SDValue visitADD(SDNode *N);
200     SDValue visitSUB(SDNode *N);
201     SDValue visitADDC(SDNode *N);
202     SDValue visitSUBC(SDNode *N);
203     SDValue visitADDE(SDNode *N);
204     SDValue visitSUBE(SDNode *N);
205     SDValue visitMUL(SDNode *N);
206     SDValue visitSDIV(SDNode *N);
207     SDValue visitUDIV(SDNode *N);
208     SDValue visitSREM(SDNode *N);
209     SDValue visitUREM(SDNode *N);
210     SDValue visitMULHU(SDNode *N);
211     SDValue visitMULHS(SDNode *N);
212     SDValue visitSMUL_LOHI(SDNode *N);
213     SDValue visitUMUL_LOHI(SDNode *N);
214     SDValue visitSMULO(SDNode *N);
215     SDValue visitUMULO(SDNode *N);
216     SDValue visitSDIVREM(SDNode *N);
217     SDValue visitUDIVREM(SDNode *N);
218     SDValue visitAND(SDNode *N);
219     SDValue visitOR(SDNode *N);
220     SDValue visitXOR(SDNode *N);
221     SDValue SimplifyVBinOp(SDNode *N);
222     SDValue SimplifyVUnaryOp(SDNode *N);
223     SDValue visitSHL(SDNode *N);
224     SDValue visitSRA(SDNode *N);
225     SDValue visitSRL(SDNode *N);
226     SDValue visitRotate(SDNode *N);
227     SDValue visitCTLZ(SDNode *N);
228     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
229     SDValue visitCTTZ(SDNode *N);
230     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
231     SDValue visitCTPOP(SDNode *N);
232     SDValue visitSELECT(SDNode *N);
233     SDValue visitVSELECT(SDNode *N);
234     SDValue visitSELECT_CC(SDNode *N);
235     SDValue visitSETCC(SDNode *N);
236     SDValue visitSIGN_EXTEND(SDNode *N);
237     SDValue visitZERO_EXTEND(SDNode *N);
238     SDValue visitANY_EXTEND(SDNode *N);
239     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
240     SDValue visitTRUNCATE(SDNode *N);
241     SDValue visitBITCAST(SDNode *N);
242     SDValue visitBUILD_PAIR(SDNode *N);
243     SDValue visitFADD(SDNode *N);
244     SDValue visitFSUB(SDNode *N);
245     SDValue visitFMUL(SDNode *N);
246     SDValue visitFMA(SDNode *N);
247     SDValue visitFDIV(SDNode *N);
248     SDValue visitFREM(SDNode *N);
249     SDValue visitFCOPYSIGN(SDNode *N);
250     SDValue visitSINT_TO_FP(SDNode *N);
251     SDValue visitUINT_TO_FP(SDNode *N);
252     SDValue visitFP_TO_SINT(SDNode *N);
253     SDValue visitFP_TO_UINT(SDNode *N);
254     SDValue visitFP_ROUND(SDNode *N);
255     SDValue visitFP_ROUND_INREG(SDNode *N);
256     SDValue visitFP_EXTEND(SDNode *N);
257     SDValue visitFNEG(SDNode *N);
258     SDValue visitFABS(SDNode *N);
259     SDValue visitFCEIL(SDNode *N);
260     SDValue visitFTRUNC(SDNode *N);
261     SDValue visitFFLOOR(SDNode *N);
262     SDValue visitBRCOND(SDNode *N);
263     SDValue visitBR_CC(SDNode *N);
264     SDValue visitLOAD(SDNode *N);
265     SDValue visitSTORE(SDNode *N);
266     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
267     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
268     SDValue visitBUILD_VECTOR(SDNode *N);
269     SDValue visitCONCAT_VECTORS(SDNode *N);
270     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
271     SDValue visitVECTOR_SHUFFLE(SDNode *N);
272     SDValue visitINSERT_SUBVECTOR(SDNode *N);
273
274     SDValue XformToShuffleWithZero(SDNode *N);
275     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
276
277     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
278
279     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
280     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
281     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
282     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
283                              SDValue N3, ISD::CondCode CC,
284                              bool NotExtCompare = false);
285     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
286                           SDLoc DL, bool foldBooleans = true);
287
288     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
289                            SDValue &CC) const;
290     bool isOneUseSetCC(SDValue N) const;
291
292     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
293                                          unsigned HiOp);
294     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296     SDValue BuildSDIV(SDNode *N);
297     SDValue BuildUDIV(SDNode *N);
298     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299                                bool DemandHighBits = true);
300     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302                               SDValue InnerPos, SDValue InnerNeg,
303                               unsigned PosOpcode, unsigned NegOpcode,
304                               SDLoc DL);
305     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306     SDValue ReduceLoadWidth(SDNode *N);
307     SDValue ReduceLoadOpStoreWidth(SDNode *N);
308     SDValue TransformFPLoadStorePair(SDNode *N);
309     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
311
312     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
313
314     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315     /// looking for aliasing nodes and adding them to the Aliases vector.
316     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317                           SmallVectorImpl<SDValue> &Aliases);
318
319     /// isAlias - Return true if there is any possibility that the two addresses
320     /// overlap.
321     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
322
323     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
324     /// looking for a better chain (aliasing node.)
325     SDValue FindBetterChain(SDNode *N, SDValue Chain);
326
327     /// Merge consecutive store operations into a wide store.
328     /// This optimization uses wide integers or vectors when possible.
329     /// \return True if some memory operations were changed.
330     bool MergeConsecutiveStores(StoreSDNode *N);
331
332     /// \brief Try to transform a truncation where C is a constant:
333     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
334     ///
335     /// \p N needs to be a truncation and its first operand an AND. Other
336     /// requirements are checked by the function (e.g. that trunc is
337     /// single-use) and if missed an empty SDValue is returned.
338     SDValue distributeTruncateThroughAnd(SDNode *N);
339
340   public:
341     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
342         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
343           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
344       AttributeSet FnAttrs =
345           DAG.getMachineFunction().getFunction()->getAttributes();
346       ForCodeSize =
347           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
348                                Attribute::OptimizeForSize) ||
349           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
350     }
351
352     /// Run - runs the dag combiner on all nodes in the work list
353     void Run(CombineLevel AtLevel);
354
355     SelectionDAG &getDAG() const { return DAG; }
356
357     /// getShiftAmountTy - Returns a type large enough to hold any valid
358     /// shift amount - before type legalization these can be huge.
359     EVT getShiftAmountTy(EVT LHSTy) {
360       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
361       if (LHSTy.isVector())
362         return LHSTy;
363       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
364                         : TLI.getPointerTy();
365     }
366
367     /// isTypeLegal - This method returns true if we are running before type
368     /// legalization or if the specified VT is legal.
369     bool isTypeLegal(const EVT &VT) {
370       if (!LegalTypes) return true;
371       return TLI.isTypeLegal(VT);
372     }
373
374     /// getSetCCResultType - Convenience wrapper around
375     /// TargetLowering::getSetCCResultType
376     EVT getSetCCResultType(EVT VT) const {
377       return TLI.getSetCCResultType(*DAG.getContext(), VT);
378     }
379   };
380 }
381
382
383 namespace {
384 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
385 /// nodes from the worklist.
386 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
387   DAGCombiner &DC;
388 public:
389   explicit WorkListRemover(DAGCombiner &dc)
390     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
391
392   void NodeDeleted(SDNode *N, SDNode *E) override {
393     DC.removeFromWorkList(N);
394   }
395 };
396 }
397
398 //===----------------------------------------------------------------------===//
399 //  TargetLowering::DAGCombinerInfo implementation
400 //===----------------------------------------------------------------------===//
401
402 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
403   ((DAGCombiner*)DC)->AddToWorkList(N);
404 }
405
406 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
407   ((DAGCombiner*)DC)->removeFromWorkList(N);
408 }
409
410 SDValue TargetLowering::DAGCombinerInfo::
411 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
412   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
413 }
414
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
417   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
418 }
419
420
421 SDValue TargetLowering::DAGCombinerInfo::
422 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
423   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
424 }
425
426 void TargetLowering::DAGCombinerInfo::
427 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
428   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
429 }
430
431 //===----------------------------------------------------------------------===//
432 // Helper Functions
433 //===----------------------------------------------------------------------===//
434
435 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
436 /// specified expression for the same cost as the expression itself, or 2 if we
437 /// can compute the negated form more cheaply than the expression itself.
438 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
439                                const TargetLowering &TLI,
440                                const TargetOptions *Options,
441                                unsigned Depth = 0) {
442   // fneg is removable even if it has multiple uses.
443   if (Op.getOpcode() == ISD::FNEG) return 2;
444
445   // Don't allow anything with multiple uses.
446   if (!Op.hasOneUse()) return 0;
447
448   // Don't recurse exponentially.
449   if (Depth > 6) return 0;
450
451   switch (Op.getOpcode()) {
452   default: return false;
453   case ISD::ConstantFP:
454     // Don't invert constant FP values after legalize.  The negated constant
455     // isn't necessarily legal.
456     return LegalOperations ? 0 : 1;
457   case ISD::FADD:
458     // FIXME: determine better conditions for this xform.
459     if (!Options->UnsafeFPMath) return 0;
460
461     // After operation legalization, it might not be legal to create new FSUBs.
462     if (LegalOperations &&
463         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
464       return 0;
465
466     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
467     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
468                                     Options, Depth + 1))
469       return V;
470     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
471     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
472                               Depth + 1);
473   case ISD::FSUB:
474     // We can't turn -(A-B) into B-A when we honor signed zeros.
475     if (!Options->UnsafeFPMath) return 0;
476
477     // fold (fneg (fsub A, B)) -> (fsub B, A)
478     return 1;
479
480   case ISD::FMUL:
481   case ISD::FDIV:
482     if (Options->HonorSignDependentRoundingFPMath()) return 0;
483
484     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
485     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
486                                     Options, Depth + 1))
487       return V;
488
489     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
490                               Depth + 1);
491
492   case ISD::FP_EXTEND:
493   case ISD::FP_ROUND:
494   case ISD::FSIN:
495     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
496                               Depth + 1);
497   }
498 }
499
500 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
501 /// returns the newly negated expression.
502 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
503                                     bool LegalOperations, unsigned Depth = 0) {
504   // fneg is removable even if it has multiple uses.
505   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
506
507   // Don't allow anything with multiple uses.
508   assert(Op.hasOneUse() && "Unknown reuse!");
509
510   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
511   switch (Op.getOpcode()) {
512   default: llvm_unreachable("Unknown code");
513   case ISD::ConstantFP: {
514     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
515     V.changeSign();
516     return DAG.getConstantFP(V, Op.getValueType());
517   }
518   case ISD::FADD:
519     // FIXME: determine better conditions for this xform.
520     assert(DAG.getTarget().Options.UnsafeFPMath);
521
522     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
523     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
524                            DAG.getTargetLoweringInfo(),
525                            &DAG.getTarget().Options, Depth+1))
526       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
527                          GetNegatedExpression(Op.getOperand(0), DAG,
528                                               LegalOperations, Depth+1),
529                          Op.getOperand(1));
530     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
531     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532                        GetNegatedExpression(Op.getOperand(1), DAG,
533                                             LegalOperations, Depth+1),
534                        Op.getOperand(0));
535   case ISD::FSUB:
536     // We can't turn -(A-B) into B-A when we honor signed zeros.
537     assert(DAG.getTarget().Options.UnsafeFPMath);
538
539     // fold (fneg (fsub 0, B)) -> B
540     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
541       if (N0CFP->getValueAPF().isZero())
542         return Op.getOperand(1);
543
544     // fold (fneg (fsub A, B)) -> (fsub B, A)
545     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                        Op.getOperand(1), Op.getOperand(0));
547
548   case ISD::FMUL:
549   case ISD::FDIV:
550     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
551
552     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
553     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
554                            DAG.getTargetLoweringInfo(),
555                            &DAG.getTarget().Options, Depth+1))
556       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
557                          GetNegatedExpression(Op.getOperand(0), DAG,
558                                               LegalOperations, Depth+1),
559                          Op.getOperand(1));
560
561     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
562     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
563                        Op.getOperand(0),
564                        GetNegatedExpression(Op.getOperand(1), DAG,
565                                             LegalOperations, Depth+1));
566
567   case ISD::FP_EXTEND:
568   case ISD::FSIN:
569     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
570                        GetNegatedExpression(Op.getOperand(0), DAG,
571                                             LegalOperations, Depth+1));
572   case ISD::FP_ROUND:
573       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
574                          GetNegatedExpression(Op.getOperand(0), DAG,
575                                               LegalOperations, Depth+1),
576                          Op.getOperand(1));
577   }
578 }
579
580 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
581 // that selects between the target values used for true and false, making it
582 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
583 // the appropriate nodes based on the type of node we are checking. This
584 // simplifies life a bit for the callers.
585 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
586                                     SDValue &CC) const {
587   if (N.getOpcode() == ISD::SETCC) {
588     LHS = N.getOperand(0);
589     RHS = N.getOperand(1);
590     CC  = N.getOperand(2);
591     return true;
592   }
593
594   if (N.getOpcode() != ISD::SELECT_CC ||
595       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
596       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
597     return false;
598
599   LHS = N.getOperand(0);
600   RHS = N.getOperand(1);
601   CC  = N.getOperand(4);
602   return true;
603 }
604
605 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
606 // one use.  If this is true, it allows the users to invert the operation for
607 // free when it is profitable to do so.
608 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
609   SDValue N0, N1, N2;
610   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
611     return true;
612   return false;
613 }
614
615 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
616 /// elements are all the same constant or undefined.
617 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
618   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
619   if (!C)
620     return false;
621
622   APInt SplatUndef;
623   unsigned SplatBitSize;
624   bool HasAnyUndefs;
625   EVT EltVT = N->getValueType(0).getVectorElementType();
626   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
627                              HasAnyUndefs) &&
628           EltVT.getSizeInBits() >= SplatBitSize);
629 }
630
631 // \brief Returns the SDNode if it is a constant BuildVector or constant.
632 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
633   if (isa<ConstantSDNode>(N))
634     return N.getNode();
635   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
636   if(BV && BV->isConstant())
637     return BV;
638   return nullptr;
639 }
640
641 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
642 // int.
643 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
644   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
645     return CN;
646
647   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
648     ConstantSDNode *CN = BV->getConstantSplatValue();
649
650     // BuildVectors can truncate their operands. Ignore that case here.
651     if (CN && CN->getValueType(0) == N.getValueType().getScalarType())
652       return CN;
653   }
654
655   return nullptr;
656 }
657
658 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
659                                     SDValue N0, SDValue N1) {
660   EVT VT = N0.getValueType();
661   if (N0.getOpcode() == Opc) {
662     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
663       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
664         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
665         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
666         if (!OpNode.getNode())
667           return SDValue();
668         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
669       }
670       if (N0.hasOneUse()) {
671         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
672         // use
673         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
674         if (!OpNode.getNode())
675           return SDValue();
676         AddToWorkList(OpNode.getNode());
677         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
678       }
679     }
680   }
681
682   if (N1.getOpcode() == Opc) {
683     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
684       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
685         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
686         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
687         if (!OpNode.getNode())
688           return SDValue();
689         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
690       }
691       if (N1.hasOneUse()) {
692         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
693         // use
694         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
695         if (!OpNode.getNode())
696           return SDValue();
697         AddToWorkList(OpNode.getNode());
698         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
699       }
700     }
701   }
702
703   return SDValue();
704 }
705
706 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
707                                bool AddTo) {
708   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
709   ++NodesCombined;
710   DEBUG(dbgs() << "\nReplacing.1 ";
711         N->dump(&DAG);
712         dbgs() << "\nWith: ";
713         To[0].getNode()->dump(&DAG);
714         dbgs() << " and " << NumTo-1 << " other values\n";
715         for (unsigned i = 0, e = NumTo; i != e; ++i)
716           assert((!To[i].getNode() ||
717                   N->getValueType(i) == To[i].getValueType()) &&
718                  "Cannot combine value to value of different type!"));
719   WorkListRemover DeadNodes(*this);
720   DAG.ReplaceAllUsesWith(N, To);
721   if (AddTo) {
722     // Push the new nodes and any users onto the worklist
723     for (unsigned i = 0, e = NumTo; i != e; ++i) {
724       if (To[i].getNode()) {
725         AddToWorkList(To[i].getNode());
726         AddUsersToWorkList(To[i].getNode());
727       }
728     }
729   }
730
731   // Finally, if the node is now dead, remove it from the graph.  The node
732   // may not be dead if the replacement process recursively simplified to
733   // something else needing this node.
734   if (N->use_empty()) {
735     // Nodes can be reintroduced into the worklist.  Make sure we do not
736     // process a node that has been replaced.
737     removeFromWorkList(N);
738
739     // Finally, since the node is now dead, remove it from the graph.
740     DAG.DeleteNode(N);
741   }
742   return SDValue(N, 0);
743 }
744
745 void DAGCombiner::
746 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
747   // Replace all uses.  If any nodes become isomorphic to other nodes and
748   // are deleted, make sure to remove them from our worklist.
749   WorkListRemover DeadNodes(*this);
750   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
751
752   // Push the new node and any (possibly new) users onto the worklist.
753   AddToWorkList(TLO.New.getNode());
754   AddUsersToWorkList(TLO.New.getNode());
755
756   // Finally, if the node is now dead, remove it from the graph.  The node
757   // may not be dead if the replacement process recursively simplified to
758   // something else needing this node.
759   if (TLO.Old.getNode()->use_empty()) {
760     removeFromWorkList(TLO.Old.getNode());
761
762     // If the operands of this node are only used by the node, they will now
763     // be dead.  Make sure to visit them first to delete dead nodes early.
764     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
765       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
766         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
767
768     DAG.DeleteNode(TLO.Old.getNode());
769   }
770 }
771
772 /// SimplifyDemandedBits - Check the specified integer node value to see if
773 /// it can be simplified or if things it uses can be simplified by bit
774 /// propagation.  If so, return true.
775 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
776   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
777   APInt KnownZero, KnownOne;
778   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
779     return false;
780
781   // Revisit the node.
782   AddToWorkList(Op.getNode());
783
784   // Replace the old value with the new one.
785   ++NodesCombined;
786   DEBUG(dbgs() << "\nReplacing.2 ";
787         TLO.Old.getNode()->dump(&DAG);
788         dbgs() << "\nWith: ";
789         TLO.New.getNode()->dump(&DAG);
790         dbgs() << '\n');
791
792   CommitTargetLoweringOpt(TLO);
793   return true;
794 }
795
796 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
797   SDLoc dl(Load);
798   EVT VT = Load->getValueType(0);
799   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
800
801   DEBUG(dbgs() << "\nReplacing.9 ";
802         Load->dump(&DAG);
803         dbgs() << "\nWith: ";
804         Trunc.getNode()->dump(&DAG);
805         dbgs() << '\n');
806   WorkListRemover DeadNodes(*this);
807   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
808   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
809   removeFromWorkList(Load);
810   DAG.DeleteNode(Load);
811   AddToWorkList(Trunc.getNode());
812 }
813
814 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
815   Replace = false;
816   SDLoc dl(Op);
817   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
818     EVT MemVT = LD->getMemoryVT();
819     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
820       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
821                                                   : ISD::EXTLOAD)
822       : LD->getExtensionType();
823     Replace = true;
824     return DAG.getExtLoad(ExtType, dl, PVT,
825                           LD->getChain(), LD->getBasePtr(),
826                           MemVT, LD->getMemOperand());
827   }
828
829   unsigned Opc = Op.getOpcode();
830   switch (Opc) {
831   default: break;
832   case ISD::AssertSext:
833     return DAG.getNode(ISD::AssertSext, dl, PVT,
834                        SExtPromoteOperand(Op.getOperand(0), PVT),
835                        Op.getOperand(1));
836   case ISD::AssertZext:
837     return DAG.getNode(ISD::AssertZext, dl, PVT,
838                        ZExtPromoteOperand(Op.getOperand(0), PVT),
839                        Op.getOperand(1));
840   case ISD::Constant: {
841     unsigned ExtOpc =
842       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
843     return DAG.getNode(ExtOpc, dl, PVT, Op);
844   }
845   }
846
847   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
848     return SDValue();
849   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
850 }
851
852 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
853   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
854     return SDValue();
855   EVT OldVT = Op.getValueType();
856   SDLoc dl(Op);
857   bool Replace = false;
858   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
859   if (!NewOp.getNode())
860     return SDValue();
861   AddToWorkList(NewOp.getNode());
862
863   if (Replace)
864     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
865   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
866                      DAG.getValueType(OldVT));
867 }
868
869 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
870   EVT OldVT = Op.getValueType();
871   SDLoc dl(Op);
872   bool Replace = false;
873   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
874   if (!NewOp.getNode())
875     return SDValue();
876   AddToWorkList(NewOp.getNode());
877
878   if (Replace)
879     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
880   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
881 }
882
883 /// PromoteIntBinOp - Promote the specified integer binary operation if the
884 /// target indicates it is beneficial. e.g. On x86, it's usually better to
885 /// promote i16 operations to i32 since i16 instructions are longer.
886 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
887   if (!LegalOperations)
888     return SDValue();
889
890   EVT VT = Op.getValueType();
891   if (VT.isVector() || !VT.isInteger())
892     return SDValue();
893
894   // If operation type is 'undesirable', e.g. i16 on x86, consider
895   // promoting it.
896   unsigned Opc = Op.getOpcode();
897   if (TLI.isTypeDesirableForOp(Opc, VT))
898     return SDValue();
899
900   EVT PVT = VT;
901   // Consult target whether it is a good idea to promote this operation and
902   // what's the right type to promote it to.
903   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
904     assert(PVT != VT && "Don't know what type to promote to!");
905
906     bool Replace0 = false;
907     SDValue N0 = Op.getOperand(0);
908     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
909     if (!NN0.getNode())
910       return SDValue();
911
912     bool Replace1 = false;
913     SDValue N1 = Op.getOperand(1);
914     SDValue NN1;
915     if (N0 == N1)
916       NN1 = NN0;
917     else {
918       NN1 = PromoteOperand(N1, PVT, Replace1);
919       if (!NN1.getNode())
920         return SDValue();
921     }
922
923     AddToWorkList(NN0.getNode());
924     if (NN1.getNode())
925       AddToWorkList(NN1.getNode());
926
927     if (Replace0)
928       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
929     if (Replace1)
930       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
931
932     DEBUG(dbgs() << "\nPromoting ";
933           Op.getNode()->dump(&DAG));
934     SDLoc dl(Op);
935     return DAG.getNode(ISD::TRUNCATE, dl, VT,
936                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
937   }
938   return SDValue();
939 }
940
941 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
942 /// target indicates it is beneficial. e.g. On x86, it's usually better to
943 /// promote i16 operations to i32 since i16 instructions are longer.
944 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
945   if (!LegalOperations)
946     return SDValue();
947
948   EVT VT = Op.getValueType();
949   if (VT.isVector() || !VT.isInteger())
950     return SDValue();
951
952   // If operation type is 'undesirable', e.g. i16 on x86, consider
953   // promoting it.
954   unsigned Opc = Op.getOpcode();
955   if (TLI.isTypeDesirableForOp(Opc, VT))
956     return SDValue();
957
958   EVT PVT = VT;
959   // Consult target whether it is a good idea to promote this operation and
960   // what's the right type to promote it to.
961   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
962     assert(PVT != VT && "Don't know what type to promote to!");
963
964     bool Replace = false;
965     SDValue N0 = Op.getOperand(0);
966     if (Opc == ISD::SRA)
967       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
968     else if (Opc == ISD::SRL)
969       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
970     else
971       N0 = PromoteOperand(N0, PVT, Replace);
972     if (!N0.getNode())
973       return SDValue();
974
975     AddToWorkList(N0.getNode());
976     if (Replace)
977       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
978
979     DEBUG(dbgs() << "\nPromoting ";
980           Op.getNode()->dump(&DAG));
981     SDLoc dl(Op);
982     return DAG.getNode(ISD::TRUNCATE, dl, VT,
983                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
984   }
985   return SDValue();
986 }
987
988 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
989   if (!LegalOperations)
990     return SDValue();
991
992   EVT VT = Op.getValueType();
993   if (VT.isVector() || !VT.isInteger())
994     return SDValue();
995
996   // If operation type is 'undesirable', e.g. i16 on x86, consider
997   // promoting it.
998   unsigned Opc = Op.getOpcode();
999   if (TLI.isTypeDesirableForOp(Opc, VT))
1000     return SDValue();
1001
1002   EVT PVT = VT;
1003   // Consult target whether it is a good idea to promote this operation and
1004   // what's the right type to promote it to.
1005   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1006     assert(PVT != VT && "Don't know what type to promote to!");
1007     // fold (aext (aext x)) -> (aext x)
1008     // fold (aext (zext x)) -> (zext x)
1009     // fold (aext (sext x)) -> (sext x)
1010     DEBUG(dbgs() << "\nPromoting ";
1011           Op.getNode()->dump(&DAG));
1012     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1013   }
1014   return SDValue();
1015 }
1016
1017 bool DAGCombiner::PromoteLoad(SDValue Op) {
1018   if (!LegalOperations)
1019     return false;
1020
1021   EVT VT = Op.getValueType();
1022   if (VT.isVector() || !VT.isInteger())
1023     return false;
1024
1025   // If operation type is 'undesirable', e.g. i16 on x86, consider
1026   // promoting it.
1027   unsigned Opc = Op.getOpcode();
1028   if (TLI.isTypeDesirableForOp(Opc, VT))
1029     return false;
1030
1031   EVT PVT = VT;
1032   // Consult target whether it is a good idea to promote this operation and
1033   // what's the right type to promote it to.
1034   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1035     assert(PVT != VT && "Don't know what type to promote to!");
1036
1037     SDLoc dl(Op);
1038     SDNode *N = Op.getNode();
1039     LoadSDNode *LD = cast<LoadSDNode>(N);
1040     EVT MemVT = LD->getMemoryVT();
1041     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1042       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1043                                                   : ISD::EXTLOAD)
1044       : LD->getExtensionType();
1045     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1046                                    LD->getChain(), LD->getBasePtr(),
1047                                    MemVT, LD->getMemOperand());
1048     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1049
1050     DEBUG(dbgs() << "\nPromoting ";
1051           N->dump(&DAG);
1052           dbgs() << "\nTo: ";
1053           Result.getNode()->dump(&DAG);
1054           dbgs() << '\n');
1055     WorkListRemover DeadNodes(*this);
1056     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1057     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1058     removeFromWorkList(N);
1059     DAG.DeleteNode(N);
1060     AddToWorkList(Result.getNode());
1061     return true;
1062   }
1063   return false;
1064 }
1065
1066
1067 //===----------------------------------------------------------------------===//
1068 //  Main DAG Combiner implementation
1069 //===----------------------------------------------------------------------===//
1070
1071 void DAGCombiner::Run(CombineLevel AtLevel) {
1072   // set the instance variables, so that the various visit routines may use it.
1073   Level = AtLevel;
1074   LegalOperations = Level >= AfterLegalizeVectorOps;
1075   LegalTypes = Level >= AfterLegalizeTypes;
1076
1077   // Add all the dag nodes to the worklist.
1078   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1079        E = DAG.allnodes_end(); I != E; ++I)
1080     AddToWorkList(I);
1081
1082   // Create a dummy node (which is not added to allnodes), that adds a reference
1083   // to the root node, preventing it from being deleted, and tracking any
1084   // changes of the root.
1085   HandleSDNode Dummy(DAG.getRoot());
1086
1087   // The root of the dag may dangle to deleted nodes until the dag combiner is
1088   // done.  Set it to null to avoid confusion.
1089   DAG.setRoot(SDValue());
1090
1091   // while the worklist isn't empty, find a node and
1092   // try and combine it.
1093   while (!WorkListContents.empty()) {
1094     SDNode *N;
1095     // The WorkListOrder holds the SDNodes in order, but it may contain
1096     // duplicates.
1097     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1098     // worklist *should* contain, and check the node we want to visit is should
1099     // actually be visited.
1100     do {
1101       N = WorkListOrder.pop_back_val();
1102     } while (!WorkListContents.erase(N));
1103
1104     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1105     // N is deleted from the DAG, since they too may now be dead or may have a
1106     // reduced number of uses, allowing other xforms.
1107     if (N->use_empty() && N != &Dummy) {
1108       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1109         AddToWorkList(N->getOperand(i).getNode());
1110
1111       DAG.DeleteNode(N);
1112       continue;
1113     }
1114
1115     SDValue RV = combine(N);
1116
1117     if (!RV.getNode())
1118       continue;
1119
1120     ++NodesCombined;
1121
1122     // If we get back the same node we passed in, rather than a new node or
1123     // zero, we know that the node must have defined multiple values and
1124     // CombineTo was used.  Since CombineTo takes care of the worklist
1125     // mechanics for us, we have no work to do in this case.
1126     if (RV.getNode() == N)
1127       continue;
1128
1129     assert(N->getOpcode() != ISD::DELETED_NODE &&
1130            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1131            "Node was deleted but visit returned new node!");
1132
1133     DEBUG(dbgs() << "\nReplacing.3 ";
1134           N->dump(&DAG);
1135           dbgs() << "\nWith: ";
1136           RV.getNode()->dump(&DAG);
1137           dbgs() << '\n');
1138
1139     // Transfer debug value.
1140     DAG.TransferDbgValues(SDValue(N, 0), RV);
1141     WorkListRemover DeadNodes(*this);
1142     if (N->getNumValues() == RV.getNode()->getNumValues())
1143       DAG.ReplaceAllUsesWith(N, RV.getNode());
1144     else {
1145       assert(N->getValueType(0) == RV.getValueType() &&
1146              N->getNumValues() == 1 && "Type mismatch");
1147       SDValue OpV = RV;
1148       DAG.ReplaceAllUsesWith(N, &OpV);
1149     }
1150
1151     // Push the new node and any users onto the worklist
1152     AddToWorkList(RV.getNode());
1153     AddUsersToWorkList(RV.getNode());
1154
1155     // Add any uses of the old node to the worklist in case this node is the
1156     // last one that uses them.  They may become dead after this node is
1157     // deleted.
1158     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1159       AddToWorkList(N->getOperand(i).getNode());
1160
1161     // Finally, if the node is now dead, remove it from the graph.  The node
1162     // may not be dead if the replacement process recursively simplified to
1163     // something else needing this node.
1164     if (N->use_empty()) {
1165       // Nodes can be reintroduced into the worklist.  Make sure we do not
1166       // process a node that has been replaced.
1167       removeFromWorkList(N);
1168
1169       // Finally, since the node is now dead, remove it from the graph.
1170       DAG.DeleteNode(N);
1171     }
1172   }
1173
1174   // If the root changed (e.g. it was a dead load, update the root).
1175   DAG.setRoot(Dummy.getValue());
1176   DAG.RemoveDeadNodes();
1177 }
1178
1179 SDValue DAGCombiner::visit(SDNode *N) {
1180   switch (N->getOpcode()) {
1181   default: break;
1182   case ISD::TokenFactor:        return visitTokenFactor(N);
1183   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1184   case ISD::ADD:                return visitADD(N);
1185   case ISD::SUB:                return visitSUB(N);
1186   case ISD::ADDC:               return visitADDC(N);
1187   case ISD::SUBC:               return visitSUBC(N);
1188   case ISD::ADDE:               return visitADDE(N);
1189   case ISD::SUBE:               return visitSUBE(N);
1190   case ISD::MUL:                return visitMUL(N);
1191   case ISD::SDIV:               return visitSDIV(N);
1192   case ISD::UDIV:               return visitUDIV(N);
1193   case ISD::SREM:               return visitSREM(N);
1194   case ISD::UREM:               return visitUREM(N);
1195   case ISD::MULHU:              return visitMULHU(N);
1196   case ISD::MULHS:              return visitMULHS(N);
1197   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1198   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1199   case ISD::SMULO:              return visitSMULO(N);
1200   case ISD::UMULO:              return visitUMULO(N);
1201   case ISD::SDIVREM:            return visitSDIVREM(N);
1202   case ISD::UDIVREM:            return visitUDIVREM(N);
1203   case ISD::AND:                return visitAND(N);
1204   case ISD::OR:                 return visitOR(N);
1205   case ISD::XOR:                return visitXOR(N);
1206   case ISD::SHL:                return visitSHL(N);
1207   case ISD::SRA:                return visitSRA(N);
1208   case ISD::SRL:                return visitSRL(N);
1209   case ISD::ROTR:
1210   case ISD::ROTL:               return visitRotate(N);
1211   case ISD::CTLZ:               return visitCTLZ(N);
1212   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1213   case ISD::CTTZ:               return visitCTTZ(N);
1214   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1215   case ISD::CTPOP:              return visitCTPOP(N);
1216   case ISD::SELECT:             return visitSELECT(N);
1217   case ISD::VSELECT:            return visitVSELECT(N);
1218   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1219   case ISD::SETCC:              return visitSETCC(N);
1220   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1221   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1222   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1223   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1224   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1225   case ISD::BITCAST:            return visitBITCAST(N);
1226   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1227   case ISD::FADD:               return visitFADD(N);
1228   case ISD::FSUB:               return visitFSUB(N);
1229   case ISD::FMUL:               return visitFMUL(N);
1230   case ISD::FMA:                return visitFMA(N);
1231   case ISD::FDIV:               return visitFDIV(N);
1232   case ISD::FREM:               return visitFREM(N);
1233   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1234   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1235   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1236   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1237   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1238   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1239   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1240   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1241   case ISD::FNEG:               return visitFNEG(N);
1242   case ISD::FABS:               return visitFABS(N);
1243   case ISD::FFLOOR:             return visitFFLOOR(N);
1244   case ISD::FCEIL:              return visitFCEIL(N);
1245   case ISD::FTRUNC:             return visitFTRUNC(N);
1246   case ISD::BRCOND:             return visitBRCOND(N);
1247   case ISD::BR_CC:              return visitBR_CC(N);
1248   case ISD::LOAD:               return visitLOAD(N);
1249   case ISD::STORE:              return visitSTORE(N);
1250   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1251   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1252   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1253   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1254   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1255   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1256   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1257   }
1258   return SDValue();
1259 }
1260
1261 SDValue DAGCombiner::combine(SDNode *N) {
1262   SDValue RV = visit(N);
1263
1264   // If nothing happened, try a target-specific DAG combine.
1265   if (!RV.getNode()) {
1266     assert(N->getOpcode() != ISD::DELETED_NODE &&
1267            "Node was deleted but visit returned NULL!");
1268
1269     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1270         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1271
1272       // Expose the DAG combiner to the target combiner impls.
1273       TargetLowering::DAGCombinerInfo
1274         DagCombineInfo(DAG, Level, false, this);
1275
1276       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1277     }
1278   }
1279
1280   // If nothing happened still, try promoting the operation.
1281   if (!RV.getNode()) {
1282     switch (N->getOpcode()) {
1283     default: break;
1284     case ISD::ADD:
1285     case ISD::SUB:
1286     case ISD::MUL:
1287     case ISD::AND:
1288     case ISD::OR:
1289     case ISD::XOR:
1290       RV = PromoteIntBinOp(SDValue(N, 0));
1291       break;
1292     case ISD::SHL:
1293     case ISD::SRA:
1294     case ISD::SRL:
1295       RV = PromoteIntShiftOp(SDValue(N, 0));
1296       break;
1297     case ISD::SIGN_EXTEND:
1298     case ISD::ZERO_EXTEND:
1299     case ISD::ANY_EXTEND:
1300       RV = PromoteExtend(SDValue(N, 0));
1301       break;
1302     case ISD::LOAD:
1303       if (PromoteLoad(SDValue(N, 0)))
1304         RV = SDValue(N, 0);
1305       break;
1306     }
1307   }
1308
1309   // If N is a commutative binary node, try commuting it to enable more
1310   // sdisel CSE.
1311   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1312       N->getNumValues() == 1) {
1313     SDValue N0 = N->getOperand(0);
1314     SDValue N1 = N->getOperand(1);
1315
1316     // Constant operands are canonicalized to RHS.
1317     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1318       SDValue Ops[] = { N1, N0 };
1319       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1320                                             Ops);
1321       if (CSENode)
1322         return SDValue(CSENode, 0);
1323     }
1324   }
1325
1326   return RV;
1327 }
1328
1329 /// getInputChainForNode - Given a node, return its input chain if it has one,
1330 /// otherwise return a null sd operand.
1331 static SDValue getInputChainForNode(SDNode *N) {
1332   if (unsigned NumOps = N->getNumOperands()) {
1333     if (N->getOperand(0).getValueType() == MVT::Other)
1334       return N->getOperand(0);
1335     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1336       return N->getOperand(NumOps-1);
1337     for (unsigned i = 1; i < NumOps-1; ++i)
1338       if (N->getOperand(i).getValueType() == MVT::Other)
1339         return N->getOperand(i);
1340   }
1341   return SDValue();
1342 }
1343
1344 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1345   // If N has two operands, where one has an input chain equal to the other,
1346   // the 'other' chain is redundant.
1347   if (N->getNumOperands() == 2) {
1348     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1349       return N->getOperand(0);
1350     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1351       return N->getOperand(1);
1352   }
1353
1354   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1355   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1356   SmallPtrSet<SDNode*, 16> SeenOps;
1357   bool Changed = false;             // If we should replace this token factor.
1358
1359   // Start out with this token factor.
1360   TFs.push_back(N);
1361
1362   // Iterate through token factors.  The TFs grows when new token factors are
1363   // encountered.
1364   for (unsigned i = 0; i < TFs.size(); ++i) {
1365     SDNode *TF = TFs[i];
1366
1367     // Check each of the operands.
1368     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1369       SDValue Op = TF->getOperand(i);
1370
1371       switch (Op.getOpcode()) {
1372       case ISD::EntryToken:
1373         // Entry tokens don't need to be added to the list. They are
1374         // rededundant.
1375         Changed = true;
1376         break;
1377
1378       case ISD::TokenFactor:
1379         if (Op.hasOneUse() &&
1380             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1381           // Queue up for processing.
1382           TFs.push_back(Op.getNode());
1383           // Clean up in case the token factor is removed.
1384           AddToWorkList(Op.getNode());
1385           Changed = true;
1386           break;
1387         }
1388         // Fall thru
1389
1390       default:
1391         // Only add if it isn't already in the list.
1392         if (SeenOps.insert(Op.getNode()))
1393           Ops.push_back(Op);
1394         else
1395           Changed = true;
1396         break;
1397       }
1398     }
1399   }
1400
1401   SDValue Result;
1402
1403   // If we've change things around then replace token factor.
1404   if (Changed) {
1405     if (Ops.empty()) {
1406       // The entry token is the only possible outcome.
1407       Result = DAG.getEntryNode();
1408     } else {
1409       // New and improved token factor.
1410       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1411     }
1412
1413     // Don't add users to work list.
1414     return CombineTo(N, Result, false);
1415   }
1416
1417   return Result;
1418 }
1419
1420 /// MERGE_VALUES can always be eliminated.
1421 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1422   WorkListRemover DeadNodes(*this);
1423   // Replacing results may cause a different MERGE_VALUES to suddenly
1424   // be CSE'd with N, and carry its uses with it. Iterate until no
1425   // uses remain, to ensure that the node can be safely deleted.
1426   // First add the users of this node to the work list so that they
1427   // can be tried again once they have new operands.
1428   AddUsersToWorkList(N);
1429   do {
1430     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1431       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1432   } while (!N->use_empty());
1433   removeFromWorkList(N);
1434   DAG.DeleteNode(N);
1435   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1436 }
1437
1438 static
1439 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1440                               SelectionDAG &DAG) {
1441   EVT VT = N0.getValueType();
1442   SDValue N00 = N0.getOperand(0);
1443   SDValue N01 = N0.getOperand(1);
1444   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1445
1446   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1447       isa<ConstantSDNode>(N00.getOperand(1))) {
1448     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1449     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1450                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1451                                  N00.getOperand(0), N01),
1452                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1453                                  N00.getOperand(1), N01));
1454     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1455   }
1456
1457   return SDValue();
1458 }
1459
1460 SDValue DAGCombiner::visitADD(SDNode *N) {
1461   SDValue N0 = N->getOperand(0);
1462   SDValue N1 = N->getOperand(1);
1463   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1464   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465   EVT VT = N0.getValueType();
1466
1467   // fold vector ops
1468   if (VT.isVector()) {
1469     SDValue FoldedVOp = SimplifyVBinOp(N);
1470     if (FoldedVOp.getNode()) return FoldedVOp;
1471
1472     // fold (add x, 0) -> x, vector edition
1473     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1474       return N0;
1475     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1476       return N1;
1477   }
1478
1479   // fold (add x, undef) -> undef
1480   if (N0.getOpcode() == ISD::UNDEF)
1481     return N0;
1482   if (N1.getOpcode() == ISD::UNDEF)
1483     return N1;
1484   // fold (add c1, c2) -> c1+c2
1485   if (N0C && N1C)
1486     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1487   // canonicalize constant to RHS
1488   if (N0C && !N1C)
1489     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1490   // fold (add x, 0) -> x
1491   if (N1C && N1C->isNullValue())
1492     return N0;
1493   // fold (add Sym, c) -> Sym+c
1494   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1495     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1496         GA->getOpcode() == ISD::GlobalAddress)
1497       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1498                                   GA->getOffset() +
1499                                     (uint64_t)N1C->getSExtValue());
1500   // fold ((c1-A)+c2) -> (c1+c2)-A
1501   if (N1C && N0.getOpcode() == ISD::SUB)
1502     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1503       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1504                          DAG.getConstant(N1C->getAPIntValue()+
1505                                          N0C->getAPIntValue(), VT),
1506                          N0.getOperand(1));
1507   // reassociate add
1508   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1509   if (RADD.getNode())
1510     return RADD;
1511   // fold ((0-A) + B) -> B-A
1512   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1513       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1514     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1515   // fold (A + (0-B)) -> A-B
1516   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1517       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1518     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1519   // fold (A+(B-A)) -> B
1520   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1521     return N1.getOperand(0);
1522   // fold ((B-A)+A) -> B
1523   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1524     return N0.getOperand(0);
1525   // fold (A+(B-(A+C))) to (B-C)
1526   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1527       N0 == N1.getOperand(1).getOperand(0))
1528     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1529                        N1.getOperand(1).getOperand(1));
1530   // fold (A+(B-(C+A))) to (B-C)
1531   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1532       N0 == N1.getOperand(1).getOperand(1))
1533     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1534                        N1.getOperand(1).getOperand(0));
1535   // fold (A+((B-A)+or-C)) to (B+or-C)
1536   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1537       N1.getOperand(0).getOpcode() == ISD::SUB &&
1538       N0 == N1.getOperand(0).getOperand(1))
1539     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1540                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1541
1542   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1543   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1544     SDValue N00 = N0.getOperand(0);
1545     SDValue N01 = N0.getOperand(1);
1546     SDValue N10 = N1.getOperand(0);
1547     SDValue N11 = N1.getOperand(1);
1548
1549     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1550       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1551                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1552                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1553   }
1554
1555   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1556     return SDValue(N, 0);
1557
1558   // fold (a+b) -> (a|b) iff a and b share no bits.
1559   if (VT.isInteger() && !VT.isVector()) {
1560     APInt LHSZero, LHSOne;
1561     APInt RHSZero, RHSOne;
1562     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1563
1564     if (LHSZero.getBoolValue()) {
1565       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1566
1567       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1568       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1569       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1570         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1571           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1572       }
1573     }
1574   }
1575
1576   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1577   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1578     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1579     if (Result.getNode()) return Result;
1580   }
1581   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1582     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1583     if (Result.getNode()) return Result;
1584   }
1585
1586   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1587   if (N1.getOpcode() == ISD::SHL &&
1588       N1.getOperand(0).getOpcode() == ISD::SUB)
1589     if (ConstantSDNode *C =
1590           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1591       if (C->getAPIntValue() == 0)
1592         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1593                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1594                                        N1.getOperand(0).getOperand(1),
1595                                        N1.getOperand(1)));
1596   if (N0.getOpcode() == ISD::SHL &&
1597       N0.getOperand(0).getOpcode() == ISD::SUB)
1598     if (ConstantSDNode *C =
1599           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1600       if (C->getAPIntValue() == 0)
1601         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1602                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1603                                        N0.getOperand(0).getOperand(1),
1604                                        N0.getOperand(1)));
1605
1606   if (N1.getOpcode() == ISD::AND) {
1607     SDValue AndOp0 = N1.getOperand(0);
1608     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1609     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1610     unsigned DestBits = VT.getScalarType().getSizeInBits();
1611
1612     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1613     // and similar xforms where the inner op is either ~0 or 0.
1614     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1615       SDLoc DL(N);
1616       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1617     }
1618   }
1619
1620   // add (sext i1), X -> sub X, (zext i1)
1621   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1622       N0.getOperand(0).getValueType() == MVT::i1 &&
1623       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1624     SDLoc DL(N);
1625     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1626     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1627   }
1628
1629   return SDValue();
1630 }
1631
1632 SDValue DAGCombiner::visitADDC(SDNode *N) {
1633   SDValue N0 = N->getOperand(0);
1634   SDValue N1 = N->getOperand(1);
1635   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1636   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1637   EVT VT = N0.getValueType();
1638
1639   // If the flag result is dead, turn this into an ADD.
1640   if (!N->hasAnyUseOfValue(1))
1641     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1642                      DAG.getNode(ISD::CARRY_FALSE,
1643                                  SDLoc(N), MVT::Glue));
1644
1645   // canonicalize constant to RHS.
1646   if (N0C && !N1C)
1647     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1648
1649   // fold (addc x, 0) -> x + no carry out
1650   if (N1C && N1C->isNullValue())
1651     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1652                                         SDLoc(N), MVT::Glue));
1653
1654   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1655   APInt LHSZero, LHSOne;
1656   APInt RHSZero, RHSOne;
1657   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1658
1659   if (LHSZero.getBoolValue()) {
1660     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1661
1662     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1663     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1664     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1665       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1666                        DAG.getNode(ISD::CARRY_FALSE,
1667                                    SDLoc(N), MVT::Glue));
1668   }
1669
1670   return SDValue();
1671 }
1672
1673 SDValue DAGCombiner::visitADDE(SDNode *N) {
1674   SDValue N0 = N->getOperand(0);
1675   SDValue N1 = N->getOperand(1);
1676   SDValue CarryIn = N->getOperand(2);
1677   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1678   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1679
1680   // canonicalize constant to RHS
1681   if (N0C && !N1C)
1682     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1683                        N1, N0, CarryIn);
1684
1685   // fold (adde x, y, false) -> (addc x, y)
1686   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1687     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1688
1689   return SDValue();
1690 }
1691
1692 // Since it may not be valid to emit a fold to zero for vector initializers
1693 // check if we can before folding.
1694 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1695                              SelectionDAG &DAG,
1696                              bool LegalOperations, bool LegalTypes) {
1697   if (!VT.isVector())
1698     return DAG.getConstant(0, VT);
1699   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1700     return DAG.getConstant(0, VT);
1701   return SDValue();
1702 }
1703
1704 SDValue DAGCombiner::visitSUB(SDNode *N) {
1705   SDValue N0 = N->getOperand(0);
1706   SDValue N1 = N->getOperand(1);
1707   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1708   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1709   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1710     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1711   EVT VT = N0.getValueType();
1712
1713   // fold vector ops
1714   if (VT.isVector()) {
1715     SDValue FoldedVOp = SimplifyVBinOp(N);
1716     if (FoldedVOp.getNode()) return FoldedVOp;
1717
1718     // fold (sub x, 0) -> x, vector edition
1719     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1720       return N0;
1721   }
1722
1723   // fold (sub x, x) -> 0
1724   // FIXME: Refactor this and xor and other similar operations together.
1725   if (N0 == N1)
1726     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1727   // fold (sub c1, c2) -> c1-c2
1728   if (N0C && N1C)
1729     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1730   // fold (sub x, c) -> (add x, -c)
1731   if (N1C)
1732     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1733                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1734   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1735   if (N0C && N0C->isAllOnesValue())
1736     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1737   // fold A-(A-B) -> B
1738   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1739     return N1.getOperand(1);
1740   // fold (A+B)-A -> B
1741   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1742     return N0.getOperand(1);
1743   // fold (A+B)-B -> A
1744   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1745     return N0.getOperand(0);
1746   // fold C2-(A+C1) -> (C2-C1)-A
1747   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1748     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1749                                    VT);
1750     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1751                        N1.getOperand(0));
1752   }
1753   // fold ((A+(B+or-C))-B) -> A+or-C
1754   if (N0.getOpcode() == ISD::ADD &&
1755       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1756        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1757       N0.getOperand(1).getOperand(0) == N1)
1758     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1759                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1760   // fold ((A+(C+B))-B) -> A+C
1761   if (N0.getOpcode() == ISD::ADD &&
1762       N0.getOperand(1).getOpcode() == ISD::ADD &&
1763       N0.getOperand(1).getOperand(1) == N1)
1764     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1765                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1766   // fold ((A-(B-C))-C) -> A-B
1767   if (N0.getOpcode() == ISD::SUB &&
1768       N0.getOperand(1).getOpcode() == ISD::SUB &&
1769       N0.getOperand(1).getOperand(1) == N1)
1770     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1771                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1772
1773   // If either operand of a sub is undef, the result is undef
1774   if (N0.getOpcode() == ISD::UNDEF)
1775     return N0;
1776   if (N1.getOpcode() == ISD::UNDEF)
1777     return N1;
1778
1779   // If the relocation model supports it, consider symbol offsets.
1780   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1781     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1782       // fold (sub Sym, c) -> Sym-c
1783       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1784         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1785                                     GA->getOffset() -
1786                                       (uint64_t)N1C->getSExtValue());
1787       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1788       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1789         if (GA->getGlobal() == GB->getGlobal())
1790           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1791                                  VT);
1792     }
1793
1794   return SDValue();
1795 }
1796
1797 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1798   SDValue N0 = N->getOperand(0);
1799   SDValue N1 = N->getOperand(1);
1800   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1801   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1802   EVT VT = N0.getValueType();
1803
1804   // If the flag result is dead, turn this into an SUB.
1805   if (!N->hasAnyUseOfValue(1))
1806     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1807                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1808                                  MVT::Glue));
1809
1810   // fold (subc x, x) -> 0 + no borrow
1811   if (N0 == N1)
1812     return CombineTo(N, DAG.getConstant(0, VT),
1813                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1814                                  MVT::Glue));
1815
1816   // fold (subc x, 0) -> x + no borrow
1817   if (N1C && N1C->isNullValue())
1818     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1819                                         MVT::Glue));
1820
1821   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1822   if (N0C && N0C->isAllOnesValue())
1823     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1824                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1825                                  MVT::Glue));
1826
1827   return SDValue();
1828 }
1829
1830 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1831   SDValue N0 = N->getOperand(0);
1832   SDValue N1 = N->getOperand(1);
1833   SDValue CarryIn = N->getOperand(2);
1834
1835   // fold (sube x, y, false) -> (subc x, y)
1836   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1837     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1838
1839   return SDValue();
1840 }
1841
1842 SDValue DAGCombiner::visitMUL(SDNode *N) {
1843   SDValue N0 = N->getOperand(0);
1844   SDValue N1 = N->getOperand(1);
1845   EVT VT = N0.getValueType();
1846
1847   // fold (mul x, undef) -> 0
1848   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1849     return DAG.getConstant(0, VT);
1850
1851   bool N0IsConst = false;
1852   bool N1IsConst = false;
1853   APInt ConstValue0, ConstValue1;
1854   // fold vector ops
1855   if (VT.isVector()) {
1856     SDValue FoldedVOp = SimplifyVBinOp(N);
1857     if (FoldedVOp.getNode()) return FoldedVOp;
1858
1859     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1860     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1861   } else {
1862     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1863     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1864                             : APInt();
1865     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1866     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1867                             : APInt();
1868   }
1869
1870   // fold (mul c1, c2) -> c1*c2
1871   if (N0IsConst && N1IsConst)
1872     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1873
1874   // canonicalize constant to RHS
1875   if (N0IsConst && !N1IsConst)
1876     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1877   // fold (mul x, 0) -> 0
1878   if (N1IsConst && ConstValue1 == 0)
1879     return N1;
1880   // We require a splat of the entire scalar bit width for non-contiguous
1881   // bit patterns.
1882   bool IsFullSplat =
1883     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1884   // fold (mul x, 1) -> x
1885   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1886     return N0;
1887   // fold (mul x, -1) -> 0-x
1888   if (N1IsConst && ConstValue1.isAllOnesValue())
1889     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1890                        DAG.getConstant(0, VT), N0);
1891   // fold (mul x, (1 << c)) -> x << c
1892   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1893     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1894                        DAG.getConstant(ConstValue1.logBase2(),
1895                                        getShiftAmountTy(N0.getValueType())));
1896   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1897   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1898     unsigned Log2Val = (-ConstValue1).logBase2();
1899     // FIXME: If the input is something that is easily negated (e.g. a
1900     // single-use add), we should put the negate there.
1901     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1902                        DAG.getConstant(0, VT),
1903                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1904                             DAG.getConstant(Log2Val,
1905                                       getShiftAmountTy(N0.getValueType()))));
1906   }
1907
1908   APInt Val;
1909   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1910   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1911       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1912                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1913     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1914                              N1, N0.getOperand(1));
1915     AddToWorkList(C3.getNode());
1916     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1917                        N0.getOperand(0), C3);
1918   }
1919
1920   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1921   // use.
1922   {
1923     SDValue Sh(nullptr,0), Y(nullptr,0);
1924     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1925     if (N0.getOpcode() == ISD::SHL &&
1926         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1927                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1928         N0.getNode()->hasOneUse()) {
1929       Sh = N0; Y = N1;
1930     } else if (N1.getOpcode() == ISD::SHL &&
1931                isa<ConstantSDNode>(N1.getOperand(1)) &&
1932                N1.getNode()->hasOneUse()) {
1933       Sh = N1; Y = N0;
1934     }
1935
1936     if (Sh.getNode()) {
1937       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1938                                 Sh.getOperand(0), Y);
1939       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1940                          Mul, Sh.getOperand(1));
1941     }
1942   }
1943
1944   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1945   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1946       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1947                      isa<ConstantSDNode>(N0.getOperand(1))))
1948     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1949                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1950                                    N0.getOperand(0), N1),
1951                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1952                                    N0.getOperand(1), N1));
1953
1954   // reassociate mul
1955   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1956   if (RMUL.getNode())
1957     return RMUL;
1958
1959   return SDValue();
1960 }
1961
1962 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1963   SDValue N0 = N->getOperand(0);
1964   SDValue N1 = N->getOperand(1);
1965   ConstantSDNode *N0C = isConstOrConstSplat(N0);
1966   ConstantSDNode *N1C = isConstOrConstSplat(N1);
1967   EVT VT = N->getValueType(0);
1968
1969   // fold vector ops
1970   if (VT.isVector()) {
1971     SDValue FoldedVOp = SimplifyVBinOp(N);
1972     if (FoldedVOp.getNode()) return FoldedVOp;
1973   }
1974
1975   // fold (sdiv c1, c2) -> c1/c2
1976   if (N0C && N1C && !N1C->isNullValue())
1977     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1978   // fold (sdiv X, 1) -> X
1979   if (N1C && N1C->getAPIntValue() == 1LL)
1980     return N0;
1981   // fold (sdiv X, -1) -> 0-X
1982   if (N1C && N1C->isAllOnesValue())
1983     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1984                        DAG.getConstant(0, VT), N0);
1985   // If we know the sign bits of both operands are zero, strength reduce to a
1986   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1987   if (!VT.isVector()) {
1988     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1989       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1990                          N0, N1);
1991   }
1992
1993   // fold (sdiv X, pow2) -> simple ops after legalize
1994   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
1995                                      (-N1C->getAPIntValue()).isPowerOf2())) {
1996     // If dividing by powers of two is cheap, then don't perform the following
1997     // fold.
1998     if (TLI.isPow2DivCheap())
1999       return SDValue();
2000
2001     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2002
2003     // Splat the sign bit into the register
2004     SDValue SGN =
2005         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2006                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2007                                     getShiftAmountTy(N0.getValueType())));
2008     AddToWorkList(SGN.getNode());
2009
2010     // Add (N0 < 0) ? abs2 - 1 : 0;
2011     SDValue SRL =
2012         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2013                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2014                                     getShiftAmountTy(SGN.getValueType())));
2015     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2016     AddToWorkList(SRL.getNode());
2017     AddToWorkList(ADD.getNode());    // Divide by pow2
2018     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2019                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2020
2021     // If we're dividing by a positive value, we're done.  Otherwise, we must
2022     // negate the result.
2023     if (N1C->getAPIntValue().isNonNegative())
2024       return SRA;
2025
2026     AddToWorkList(SRA.getNode());
2027     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2028   }
2029
2030   // if integer divide is expensive and we satisfy the requirements, emit an
2031   // alternate sequence.
2032   if (N1C && !TLI.isIntDivCheap()) {
2033     SDValue Op = BuildSDIV(N);
2034     if (Op.getNode()) return Op;
2035   }
2036
2037   // undef / X -> 0
2038   if (N0.getOpcode() == ISD::UNDEF)
2039     return DAG.getConstant(0, VT);
2040   // X / undef -> undef
2041   if (N1.getOpcode() == ISD::UNDEF)
2042     return N1;
2043
2044   return SDValue();
2045 }
2046
2047 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2048   SDValue N0 = N->getOperand(0);
2049   SDValue N1 = N->getOperand(1);
2050   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2051   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2052   EVT VT = N->getValueType(0);
2053
2054   // fold vector ops
2055   if (VT.isVector()) {
2056     SDValue FoldedVOp = SimplifyVBinOp(N);
2057     if (FoldedVOp.getNode()) return FoldedVOp;
2058   }
2059
2060   // fold (udiv c1, c2) -> c1/c2
2061   if (N0C && N1C && !N1C->isNullValue())
2062     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2063   // fold (udiv x, (1 << c)) -> x >>u c
2064   if (N1C && N1C->getAPIntValue().isPowerOf2())
2065     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2066                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2067                                        getShiftAmountTy(N0.getValueType())));
2068   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2069   if (N1.getOpcode() == ISD::SHL) {
2070     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2071       if (SHC->getAPIntValue().isPowerOf2()) {
2072         EVT ADDVT = N1.getOperand(1).getValueType();
2073         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2074                                   N1.getOperand(1),
2075                                   DAG.getConstant(SHC->getAPIntValue()
2076                                                                   .logBase2(),
2077                                                   ADDVT));
2078         AddToWorkList(Add.getNode());
2079         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2080       }
2081     }
2082   }
2083   // fold (udiv x, c) -> alternate
2084   if (N1C && !TLI.isIntDivCheap()) {
2085     SDValue Op = BuildUDIV(N);
2086     if (Op.getNode()) return Op;
2087   }
2088
2089   // undef / X -> 0
2090   if (N0.getOpcode() == ISD::UNDEF)
2091     return DAG.getConstant(0, VT);
2092   // X / undef -> undef
2093   if (N1.getOpcode() == ISD::UNDEF)
2094     return N1;
2095
2096   return SDValue();
2097 }
2098
2099 SDValue DAGCombiner::visitSREM(SDNode *N) {
2100   SDValue N0 = N->getOperand(0);
2101   SDValue N1 = N->getOperand(1);
2102   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2103   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2104   EVT VT = N->getValueType(0);
2105
2106   // fold (srem c1, c2) -> c1%c2
2107   if (N0C && N1C && !N1C->isNullValue())
2108     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2109   // If we know the sign bits of both operands are zero, strength reduce to a
2110   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2111   if (!VT.isVector()) {
2112     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2113       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2114   }
2115
2116   // If X/C can be simplified by the division-by-constant logic, lower
2117   // X%C to the equivalent of X-X/C*C.
2118   if (N1C && !N1C->isNullValue()) {
2119     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2120     AddToWorkList(Div.getNode());
2121     SDValue OptimizedDiv = combine(Div.getNode());
2122     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2123       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2124                                 OptimizedDiv, N1);
2125       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2126       AddToWorkList(Mul.getNode());
2127       return Sub;
2128     }
2129   }
2130
2131   // undef % X -> 0
2132   if (N0.getOpcode() == ISD::UNDEF)
2133     return DAG.getConstant(0, VT);
2134   // X % undef -> undef
2135   if (N1.getOpcode() == ISD::UNDEF)
2136     return N1;
2137
2138   return SDValue();
2139 }
2140
2141 SDValue DAGCombiner::visitUREM(SDNode *N) {
2142   SDValue N0 = N->getOperand(0);
2143   SDValue N1 = N->getOperand(1);
2144   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2146   EVT VT = N->getValueType(0);
2147
2148   // fold (urem c1, c2) -> c1%c2
2149   if (N0C && N1C && !N1C->isNullValue())
2150     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2151   // fold (urem x, pow2) -> (and x, pow2-1)
2152   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2153     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2154                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2155   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2156   if (N1.getOpcode() == ISD::SHL) {
2157     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2158       if (SHC->getAPIntValue().isPowerOf2()) {
2159         SDValue Add =
2160           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2161                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2162                                  VT));
2163         AddToWorkList(Add.getNode());
2164         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2165       }
2166     }
2167   }
2168
2169   // If X/C can be simplified by the division-by-constant logic, lower
2170   // X%C to the equivalent of X-X/C*C.
2171   if (N1C && !N1C->isNullValue()) {
2172     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2173     AddToWorkList(Div.getNode());
2174     SDValue OptimizedDiv = combine(Div.getNode());
2175     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2176       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2177                                 OptimizedDiv, N1);
2178       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2179       AddToWorkList(Mul.getNode());
2180       return Sub;
2181     }
2182   }
2183
2184   // undef % X -> 0
2185   if (N0.getOpcode() == ISD::UNDEF)
2186     return DAG.getConstant(0, VT);
2187   // X % undef -> undef
2188   if (N1.getOpcode() == ISD::UNDEF)
2189     return N1;
2190
2191   return SDValue();
2192 }
2193
2194 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2195   SDValue N0 = N->getOperand(0);
2196   SDValue N1 = N->getOperand(1);
2197   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2198   EVT VT = N->getValueType(0);
2199   SDLoc DL(N);
2200
2201   // fold (mulhs x, 0) -> 0
2202   if (N1C && N1C->isNullValue())
2203     return N1;
2204   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2205   if (N1C && N1C->getAPIntValue() == 1)
2206     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2207                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2208                                        getShiftAmountTy(N0.getValueType())));
2209   // fold (mulhs x, undef) -> 0
2210   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2211     return DAG.getConstant(0, VT);
2212
2213   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2214   // plus a shift.
2215   if (VT.isSimple() && !VT.isVector()) {
2216     MVT Simple = VT.getSimpleVT();
2217     unsigned SimpleSize = Simple.getSizeInBits();
2218     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2219     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2220       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2221       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2222       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2223       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2224             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2225       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2226     }
2227   }
2228
2229   return SDValue();
2230 }
2231
2232 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2233   SDValue N0 = N->getOperand(0);
2234   SDValue N1 = N->getOperand(1);
2235   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2236   EVT VT = N->getValueType(0);
2237   SDLoc DL(N);
2238
2239   // fold (mulhu x, 0) -> 0
2240   if (N1C && N1C->isNullValue())
2241     return N1;
2242   // fold (mulhu x, 1) -> 0
2243   if (N1C && N1C->getAPIntValue() == 1)
2244     return DAG.getConstant(0, N0.getValueType());
2245   // fold (mulhu x, undef) -> 0
2246   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2247     return DAG.getConstant(0, VT);
2248
2249   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2250   // plus a shift.
2251   if (VT.isSimple() && !VT.isVector()) {
2252     MVT Simple = VT.getSimpleVT();
2253     unsigned SimpleSize = Simple.getSizeInBits();
2254     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2255     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2256       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2257       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2258       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2259       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2260             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2261       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2262     }
2263   }
2264
2265   return SDValue();
2266 }
2267
2268 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2269 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2270 /// that are being performed. Return true if a simplification was made.
2271 ///
2272 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2273                                                 unsigned HiOp) {
2274   // If the high half is not needed, just compute the low half.
2275   bool HiExists = N->hasAnyUseOfValue(1);
2276   if (!HiExists &&
2277       (!LegalOperations ||
2278        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2279     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2280                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2281     return CombineTo(N, Res, Res);
2282   }
2283
2284   // If the low half is not needed, just compute the high half.
2285   bool LoExists = N->hasAnyUseOfValue(0);
2286   if (!LoExists &&
2287       (!LegalOperations ||
2288        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2289     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2290                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2291     return CombineTo(N, Res, Res);
2292   }
2293
2294   // If both halves are used, return as it is.
2295   if (LoExists && HiExists)
2296     return SDValue();
2297
2298   // If the two computed results can be simplified separately, separate them.
2299   if (LoExists) {
2300     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2301                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2302     AddToWorkList(Lo.getNode());
2303     SDValue LoOpt = combine(Lo.getNode());
2304     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2305         (!LegalOperations ||
2306          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2307       return CombineTo(N, LoOpt, LoOpt);
2308   }
2309
2310   if (HiExists) {
2311     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2312                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2313     AddToWorkList(Hi.getNode());
2314     SDValue HiOpt = combine(Hi.getNode());
2315     if (HiOpt.getNode() && HiOpt != Hi &&
2316         (!LegalOperations ||
2317          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2318       return CombineTo(N, HiOpt, HiOpt);
2319   }
2320
2321   return SDValue();
2322 }
2323
2324 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2325   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2326   if (Res.getNode()) return Res;
2327
2328   EVT VT = N->getValueType(0);
2329   SDLoc DL(N);
2330
2331   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2332   // plus a shift.
2333   if (VT.isSimple() && !VT.isVector()) {
2334     MVT Simple = VT.getSimpleVT();
2335     unsigned SimpleSize = Simple.getSizeInBits();
2336     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2337     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2338       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2339       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2340       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2341       // Compute the high part as N1.
2342       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2343             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2344       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2345       // Compute the low part as N0.
2346       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2347       return CombineTo(N, Lo, Hi);
2348     }
2349   }
2350
2351   return SDValue();
2352 }
2353
2354 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2355   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2356   if (Res.getNode()) return Res;
2357
2358   EVT VT = N->getValueType(0);
2359   SDLoc DL(N);
2360
2361   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2362   // plus a shift.
2363   if (VT.isSimple() && !VT.isVector()) {
2364     MVT Simple = VT.getSimpleVT();
2365     unsigned SimpleSize = Simple.getSizeInBits();
2366     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2367     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2368       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2369       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2370       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2371       // Compute the high part as N1.
2372       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2373             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2374       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2375       // Compute the low part as N0.
2376       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2377       return CombineTo(N, Lo, Hi);
2378     }
2379   }
2380
2381   return SDValue();
2382 }
2383
2384 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2385   // (smulo x, 2) -> (saddo x, x)
2386   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2387     if (C2->getAPIntValue() == 2)
2388       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2389                          N->getOperand(0), N->getOperand(0));
2390
2391   return SDValue();
2392 }
2393
2394 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2395   // (umulo x, 2) -> (uaddo x, x)
2396   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2397     if (C2->getAPIntValue() == 2)
2398       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2399                          N->getOperand(0), N->getOperand(0));
2400
2401   return SDValue();
2402 }
2403
2404 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2405   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2406   if (Res.getNode()) return Res;
2407
2408   return SDValue();
2409 }
2410
2411 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2412   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2413   if (Res.getNode()) return Res;
2414
2415   return SDValue();
2416 }
2417
2418 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2419 /// two operands of the same opcode, try to simplify it.
2420 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2421   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2422   EVT VT = N0.getValueType();
2423   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2424
2425   // Bail early if none of these transforms apply.
2426   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2427
2428   // For each of OP in AND/OR/XOR:
2429   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2430   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2431   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2432   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2433   //
2434   // do not sink logical op inside of a vector extend, since it may combine
2435   // into a vsetcc.
2436   EVT Op0VT = N0.getOperand(0).getValueType();
2437   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2438        N0.getOpcode() == ISD::SIGN_EXTEND ||
2439        // Avoid infinite looping with PromoteIntBinOp.
2440        (N0.getOpcode() == ISD::ANY_EXTEND &&
2441         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2442        (N0.getOpcode() == ISD::TRUNCATE &&
2443         (!TLI.isZExtFree(VT, Op0VT) ||
2444          !TLI.isTruncateFree(Op0VT, VT)) &&
2445         TLI.isTypeLegal(Op0VT))) &&
2446       !VT.isVector() &&
2447       Op0VT == N1.getOperand(0).getValueType() &&
2448       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2449     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2450                                  N0.getOperand(0).getValueType(),
2451                                  N0.getOperand(0), N1.getOperand(0));
2452     AddToWorkList(ORNode.getNode());
2453     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2454   }
2455
2456   // For each of OP in SHL/SRL/SRA/AND...
2457   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2458   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2459   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2460   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2461        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2462       N0.getOperand(1) == N1.getOperand(1)) {
2463     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2464                                  N0.getOperand(0).getValueType(),
2465                                  N0.getOperand(0), N1.getOperand(0));
2466     AddToWorkList(ORNode.getNode());
2467     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2468                        ORNode, N0.getOperand(1));
2469   }
2470
2471   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2472   // Only perform this optimization after type legalization and before
2473   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2474   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2475   // we don't want to undo this promotion.
2476   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2477   // on scalars.
2478   if ((N0.getOpcode() == ISD::BITCAST ||
2479        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2480       Level == AfterLegalizeTypes) {
2481     SDValue In0 = N0.getOperand(0);
2482     SDValue In1 = N1.getOperand(0);
2483     EVT In0Ty = In0.getValueType();
2484     EVT In1Ty = In1.getValueType();
2485     SDLoc DL(N);
2486     // If both incoming values are integers, and the original types are the
2487     // same.
2488     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2489       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2490       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2491       AddToWorkList(Op.getNode());
2492       return BC;
2493     }
2494   }
2495
2496   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2497   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2498   // If both shuffles use the same mask, and both shuffle within a single
2499   // vector, then it is worthwhile to move the swizzle after the operation.
2500   // The type-legalizer generates this pattern when loading illegal
2501   // vector types from memory. In many cases this allows additional shuffle
2502   // optimizations.
2503   // There are other cases where moving the shuffle after the xor/and/or
2504   // is profitable even if shuffles don't perform a swizzle.
2505   // If both shuffles use the same mask, and both shuffles have the same first
2506   // or second operand, then it might still be profitable to move the shuffle
2507   // after the xor/and/or operation.
2508   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2509     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2511
2512     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2513            "Inputs to shuffles are not the same type");
2514
2515     // Check that both shuffles use the same mask. The masks are known to be of
2516     // the same length because the result vector type is the same.
2517     // Check also that shuffles have only one use to avoid introducing extra
2518     // instructions.
2519     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2520         SVN0->getMask().equals(SVN1->getMask())) {
2521       SDValue ShOp = N0->getOperand(1);
2522
2523       // Don't try to fold this node if it requires introducing a
2524       // build vector of all zeros that might be illegal at this stage.
2525       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2526         if (!LegalTypes)
2527           ShOp = DAG.getConstant(0, VT);
2528         else
2529           ShOp = SDValue();
2530       }
2531
2532       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2533       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2534       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2535       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2536         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2537                                       N0->getOperand(0), N1->getOperand(0));
2538         AddToWorkList(NewNode.getNode());
2539         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2540                                     &SVN0->getMask()[0]);
2541       }
2542
2543       // Don't try to fold this node if it requires introducing a
2544       // build vector of all zeros that might be illegal at this stage.
2545       ShOp = N0->getOperand(0);
2546       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2547         if (!LegalTypes)
2548           ShOp = DAG.getConstant(0, VT);
2549         else
2550           ShOp = SDValue();
2551       }
2552
2553       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2554       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2555       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2556       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2557         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2558                                       N0->getOperand(1), N1->getOperand(1));
2559         AddToWorkList(NewNode.getNode());
2560         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2561                                     &SVN0->getMask()[0]);
2562       }
2563     }
2564   }
2565
2566   return SDValue();
2567 }
2568
2569 SDValue DAGCombiner::visitAND(SDNode *N) {
2570   SDValue N0 = N->getOperand(0);
2571   SDValue N1 = N->getOperand(1);
2572   SDValue LL, LR, RL, RR, CC0, CC1;
2573   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2574   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2575   EVT VT = N1.getValueType();
2576   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2577
2578   // fold vector ops
2579   if (VT.isVector()) {
2580     SDValue FoldedVOp = SimplifyVBinOp(N);
2581     if (FoldedVOp.getNode()) return FoldedVOp;
2582
2583     // fold (and x, 0) -> 0, vector edition
2584     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2585       return N0;
2586     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2587       return N1;
2588
2589     // fold (and x, -1) -> x, vector edition
2590     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2591       return N1;
2592     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2593       return N0;
2594   }
2595
2596   // fold (and x, undef) -> 0
2597   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2598     return DAG.getConstant(0, VT);
2599   // fold (and c1, c2) -> c1&c2
2600   if (N0C && N1C)
2601     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2602   // canonicalize constant to RHS
2603   if (N0C && !N1C)
2604     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2605   // fold (and x, -1) -> x
2606   if (N1C && N1C->isAllOnesValue())
2607     return N0;
2608   // if (and x, c) is known to be zero, return 0
2609   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2610                                    APInt::getAllOnesValue(BitWidth)))
2611     return DAG.getConstant(0, VT);
2612   // reassociate and
2613   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2614   if (RAND.getNode())
2615     return RAND;
2616   // fold (and (or x, C), D) -> D if (C & D) == D
2617   if (N1C && N0.getOpcode() == ISD::OR)
2618     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2619       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2620         return N1;
2621   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2622   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2623     SDValue N0Op0 = N0.getOperand(0);
2624     APInt Mask = ~N1C->getAPIntValue();
2625     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2626     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2627       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2628                                  N0.getValueType(), N0Op0);
2629
2630       // Replace uses of the AND with uses of the Zero extend node.
2631       CombineTo(N, Zext);
2632
2633       // We actually want to replace all uses of the any_extend with the
2634       // zero_extend, to avoid duplicating things.  This will later cause this
2635       // AND to be folded.
2636       CombineTo(N0.getNode(), Zext);
2637       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2638     }
2639   }
2640   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2641   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2642   // already be zero by virtue of the width of the base type of the load.
2643   //
2644   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2645   // more cases.
2646   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2647        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2648       N0.getOpcode() == ISD::LOAD) {
2649     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2650                                          N0 : N0.getOperand(0) );
2651
2652     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2653     // This can be a pure constant or a vector splat, in which case we treat the
2654     // vector as a scalar and use the splat value.
2655     APInt Constant = APInt::getNullValue(1);
2656     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2657       Constant = C->getAPIntValue();
2658     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2659       APInt SplatValue, SplatUndef;
2660       unsigned SplatBitSize;
2661       bool HasAnyUndefs;
2662       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2663                                              SplatBitSize, HasAnyUndefs);
2664       if (IsSplat) {
2665         // Undef bits can contribute to a possible optimisation if set, so
2666         // set them.
2667         SplatValue |= SplatUndef;
2668
2669         // The splat value may be something like "0x00FFFFFF", which means 0 for
2670         // the first vector value and FF for the rest, repeating. We need a mask
2671         // that will apply equally to all members of the vector, so AND all the
2672         // lanes of the constant together.
2673         EVT VT = Vector->getValueType(0);
2674         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2675
2676         // If the splat value has been compressed to a bitlength lower
2677         // than the size of the vector lane, we need to re-expand it to
2678         // the lane size.
2679         if (BitWidth > SplatBitSize)
2680           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2681                SplatBitSize < BitWidth;
2682                SplatBitSize = SplatBitSize * 2)
2683             SplatValue |= SplatValue.shl(SplatBitSize);
2684
2685         Constant = APInt::getAllOnesValue(BitWidth);
2686         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2687           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2688       }
2689     }
2690
2691     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2692     // actually legal and isn't going to get expanded, else this is a false
2693     // optimisation.
2694     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2695                                                     Load->getMemoryVT());
2696
2697     // Resize the constant to the same size as the original memory access before
2698     // extension. If it is still the AllOnesValue then this AND is completely
2699     // unneeded.
2700     Constant =
2701       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2702
2703     bool B;
2704     switch (Load->getExtensionType()) {
2705     default: B = false; break;
2706     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2707     case ISD::ZEXTLOAD:
2708     case ISD::NON_EXTLOAD: B = true; break;
2709     }
2710
2711     if (B && Constant.isAllOnesValue()) {
2712       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2713       // preserve semantics once we get rid of the AND.
2714       SDValue NewLoad(Load, 0);
2715       if (Load->getExtensionType() == ISD::EXTLOAD) {
2716         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2717                               Load->getValueType(0), SDLoc(Load),
2718                               Load->getChain(), Load->getBasePtr(),
2719                               Load->getOffset(), Load->getMemoryVT(),
2720                               Load->getMemOperand());
2721         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2722         if (Load->getNumValues() == 3) {
2723           // PRE/POST_INC loads have 3 values.
2724           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2725                            NewLoad.getValue(2) };
2726           CombineTo(Load, To, 3, true);
2727         } else {
2728           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2729         }
2730       }
2731
2732       // Fold the AND away, taking care not to fold to the old load node if we
2733       // replaced it.
2734       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2735
2736       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2737     }
2738   }
2739   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2740   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2741     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2742     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2743
2744     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2745         LL.getValueType().isInteger()) {
2746       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2747       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2748         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2749                                      LR.getValueType(), LL, RL);
2750         AddToWorkList(ORNode.getNode());
2751         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2752       }
2753       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2754       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2755         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2756                                       LR.getValueType(), LL, RL);
2757         AddToWorkList(ANDNode.getNode());
2758         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2759       }
2760       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2761       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2762         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2763                                      LR.getValueType(), LL, RL);
2764         AddToWorkList(ORNode.getNode());
2765         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2766       }
2767     }
2768     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2769     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2770         Op0 == Op1 && LL.getValueType().isInteger() &&
2771       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2772                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2773                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2774                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2775       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2776                                     LL, DAG.getConstant(1, LL.getValueType()));
2777       AddToWorkList(ADDNode.getNode());
2778       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2779                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2780     }
2781     // canonicalize equivalent to ll == rl
2782     if (LL == RR && LR == RL) {
2783       Op1 = ISD::getSetCCSwappedOperands(Op1);
2784       std::swap(RL, RR);
2785     }
2786     if (LL == RL && LR == RR) {
2787       bool isInteger = LL.getValueType().isInteger();
2788       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2789       if (Result != ISD::SETCC_INVALID &&
2790           (!LegalOperations ||
2791            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2792             TLI.isOperationLegal(ISD::SETCC,
2793                             getSetCCResultType(N0.getSimpleValueType())))))
2794         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2795                             LL, LR, Result);
2796     }
2797   }
2798
2799   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2800   if (N0.getOpcode() == N1.getOpcode()) {
2801     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2802     if (Tmp.getNode()) return Tmp;
2803   }
2804
2805   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2806   // fold (and (sra)) -> (and (srl)) when possible.
2807   if (!VT.isVector() &&
2808       SimplifyDemandedBits(SDValue(N, 0)))
2809     return SDValue(N, 0);
2810
2811   // fold (zext_inreg (extload x)) -> (zextload x)
2812   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2813     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2814     EVT MemVT = LN0->getMemoryVT();
2815     // If we zero all the possible extended bits, then we can turn this into
2816     // a zextload if we are running before legalize or the operation is legal.
2817     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2818     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2819                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2820         ((!LegalOperations && !LN0->isVolatile()) ||
2821          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2822       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2823                                        LN0->getChain(), LN0->getBasePtr(),
2824                                        MemVT, LN0->getMemOperand());
2825       AddToWorkList(N);
2826       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2827       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2828     }
2829   }
2830   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2831   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2832       N0.hasOneUse()) {
2833     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2834     EVT MemVT = LN0->getMemoryVT();
2835     // If we zero all the possible extended bits, then we can turn this into
2836     // a zextload if we are running before legalize or the operation is legal.
2837     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2838     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2839                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2840         ((!LegalOperations && !LN0->isVolatile()) ||
2841          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2842       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2843                                        LN0->getChain(), LN0->getBasePtr(),
2844                                        MemVT, LN0->getMemOperand());
2845       AddToWorkList(N);
2846       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2848     }
2849   }
2850
2851   // fold (and (load x), 255) -> (zextload x, i8)
2852   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2853   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2854   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2855               (N0.getOpcode() == ISD::ANY_EXTEND &&
2856                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2857     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2858     LoadSDNode *LN0 = HasAnyExt
2859       ? cast<LoadSDNode>(N0.getOperand(0))
2860       : cast<LoadSDNode>(N0);
2861     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2862         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2863       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2864       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2865         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2866         EVT LoadedVT = LN0->getMemoryVT();
2867
2868         if (ExtVT == LoadedVT &&
2869             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2870           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2871
2872           SDValue NewLoad =
2873             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2874                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2875                            LN0->getMemOperand());
2876           AddToWorkList(N);
2877           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2878           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2879         }
2880
2881         // Do not change the width of a volatile load.
2882         // Do not generate loads of non-round integer types since these can
2883         // be expensive (and would be wrong if the type is not byte sized).
2884         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2885             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886           EVT PtrType = LN0->getOperand(1).getValueType();
2887
2888           unsigned Alignment = LN0->getAlignment();
2889           SDValue NewPtr = LN0->getBasePtr();
2890
2891           // For big endian targets, we need to add an offset to the pointer
2892           // to load the correct bytes.  For little endian systems, we merely
2893           // need to read fewer bytes from the same pointer.
2894           if (TLI.isBigEndian()) {
2895             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2896             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2897             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2898             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2899                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2900             Alignment = MinAlign(Alignment, PtrOff);
2901           }
2902
2903           AddToWorkList(NewPtr.getNode());
2904
2905           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2906           SDValue Load =
2907             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2908                            LN0->getChain(), NewPtr,
2909                            LN0->getPointerInfo(),
2910                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2911                            Alignment, LN0->getTBAAInfo());
2912           AddToWorkList(N);
2913           CombineTo(LN0, Load, Load.getValue(1));
2914           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2915         }
2916       }
2917     }
2918   }
2919
2920   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2921       VT.getSizeInBits() <= 64) {
2922     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2923       APInt ADDC = ADDI->getAPIntValue();
2924       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2925         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2926         // immediate for an add, but it is legal if its top c2 bits are set,
2927         // transform the ADD so the immediate doesn't need to be materialized
2928         // in a register.
2929         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2930           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2931                                              SRLI->getZExtValue());
2932           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2933             ADDC |= Mask;
2934             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2935               SDValue NewAdd =
2936                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2937                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2938               CombineTo(N0.getNode(), NewAdd);
2939               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2940             }
2941           }
2942         }
2943       }
2944     }
2945   }
2946
2947   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2948   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2949     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2950                                        N0.getOperand(1), false);
2951     if (BSwap.getNode())
2952       return BSwap;
2953   }
2954
2955   return SDValue();
2956 }
2957
2958 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2959 ///
2960 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2961                                         bool DemandHighBits) {
2962   if (!LegalOperations)
2963     return SDValue();
2964
2965   EVT VT = N->getValueType(0);
2966   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2967     return SDValue();
2968   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2969     return SDValue();
2970
2971   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2972   bool LookPassAnd0 = false;
2973   bool LookPassAnd1 = false;
2974   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2975       std::swap(N0, N1);
2976   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2977       std::swap(N0, N1);
2978   if (N0.getOpcode() == ISD::AND) {
2979     if (!N0.getNode()->hasOneUse())
2980       return SDValue();
2981     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2982     if (!N01C || N01C->getZExtValue() != 0xFF00)
2983       return SDValue();
2984     N0 = N0.getOperand(0);
2985     LookPassAnd0 = true;
2986   }
2987
2988   if (N1.getOpcode() == ISD::AND) {
2989     if (!N1.getNode()->hasOneUse())
2990       return SDValue();
2991     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2992     if (!N11C || N11C->getZExtValue() != 0xFF)
2993       return SDValue();
2994     N1 = N1.getOperand(0);
2995     LookPassAnd1 = true;
2996   }
2997
2998   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2999     std::swap(N0, N1);
3000   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3001     return SDValue();
3002   if (!N0.getNode()->hasOneUse() ||
3003       !N1.getNode()->hasOneUse())
3004     return SDValue();
3005
3006   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3007   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008   if (!N01C || !N11C)
3009     return SDValue();
3010   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3011     return SDValue();
3012
3013   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3014   SDValue N00 = N0->getOperand(0);
3015   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3016     if (!N00.getNode()->hasOneUse())
3017       return SDValue();
3018     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3019     if (!N001C || N001C->getZExtValue() != 0xFF)
3020       return SDValue();
3021     N00 = N00.getOperand(0);
3022     LookPassAnd0 = true;
3023   }
3024
3025   SDValue N10 = N1->getOperand(0);
3026   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3027     if (!N10.getNode()->hasOneUse())
3028       return SDValue();
3029     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3030     if (!N101C || N101C->getZExtValue() != 0xFF00)
3031       return SDValue();
3032     N10 = N10.getOperand(0);
3033     LookPassAnd1 = true;
3034   }
3035
3036   if (N00 != N10)
3037     return SDValue();
3038
3039   // Make sure everything beyond the low halfword gets set to zero since the SRL
3040   // 16 will clear the top bits.
3041   unsigned OpSizeInBits = VT.getSizeInBits();
3042   if (DemandHighBits && OpSizeInBits > 16) {
3043     // If the left-shift isn't masked out then the only way this is a bswap is
3044     // if all bits beyond the low 8 are 0. In that case the entire pattern
3045     // reduces to a left shift anyway: leave it for other parts of the combiner.
3046     if (!LookPassAnd0)
3047       return SDValue();
3048
3049     // However, if the right shift isn't masked out then it might be because
3050     // it's not needed. See if we can spot that too.
3051     if (!LookPassAnd1 &&
3052         !DAG.MaskedValueIsZero(
3053             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3054       return SDValue();
3055   }
3056
3057   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3058   if (OpSizeInBits > 16)
3059     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3060                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3061   return Res;
3062 }
3063
3064 /// isBSwapHWordElement - Return true if the specified node is an element
3065 /// that makes up a 32-bit packed halfword byteswap. i.e.
3066 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3067 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3068   if (!N.getNode()->hasOneUse())
3069     return false;
3070
3071   unsigned Opc = N.getOpcode();
3072   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3073     return false;
3074
3075   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3076   if (!N1C)
3077     return false;
3078
3079   unsigned Num;
3080   switch (N1C->getZExtValue()) {
3081   default:
3082     return false;
3083   case 0xFF:       Num = 0; break;
3084   case 0xFF00:     Num = 1; break;
3085   case 0xFF0000:   Num = 2; break;
3086   case 0xFF000000: Num = 3; break;
3087   }
3088
3089   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3090   SDValue N0 = N.getOperand(0);
3091   if (Opc == ISD::AND) {
3092     if (Num == 0 || Num == 2) {
3093       // (x >> 8) & 0xff
3094       // (x >> 8) & 0xff0000
3095       if (N0.getOpcode() != ISD::SRL)
3096         return false;
3097       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3098       if (!C || C->getZExtValue() != 8)
3099         return false;
3100     } else {
3101       // (x << 8) & 0xff00
3102       // (x << 8) & 0xff000000
3103       if (N0.getOpcode() != ISD::SHL)
3104         return false;
3105       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3106       if (!C || C->getZExtValue() != 8)
3107         return false;
3108     }
3109   } else if (Opc == ISD::SHL) {
3110     // (x & 0xff) << 8
3111     // (x & 0xff0000) << 8
3112     if (Num != 0 && Num != 2)
3113       return false;
3114     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3115     if (!C || C->getZExtValue() != 8)
3116       return false;
3117   } else { // Opc == ISD::SRL
3118     // (x & 0xff00) >> 8
3119     // (x & 0xff000000) >> 8
3120     if (Num != 1 && Num != 3)
3121       return false;
3122     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3123     if (!C || C->getZExtValue() != 8)
3124       return false;
3125   }
3126
3127   if (Parts[Num])
3128     return false;
3129
3130   Parts[Num] = N0.getOperand(0).getNode();
3131   return true;
3132 }
3133
3134 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3135 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3136 /// => (rotl (bswap x), 16)
3137 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3138   if (!LegalOperations)
3139     return SDValue();
3140
3141   EVT VT = N->getValueType(0);
3142   if (VT != MVT::i32)
3143     return SDValue();
3144   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3145     return SDValue();
3146
3147   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3148   // Look for either
3149   // (or (or (and), (and)), (or (and), (and)))
3150   // (or (or (or (and), (and)), (and)), (and))
3151   if (N0.getOpcode() != ISD::OR)
3152     return SDValue();
3153   SDValue N00 = N0.getOperand(0);
3154   SDValue N01 = N0.getOperand(1);
3155
3156   if (N1.getOpcode() == ISD::OR &&
3157       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3158     // (or (or (and), (and)), (or (and), (and)))
3159     SDValue N000 = N00.getOperand(0);
3160     if (!isBSwapHWordElement(N000, Parts))
3161       return SDValue();
3162
3163     SDValue N001 = N00.getOperand(1);
3164     if (!isBSwapHWordElement(N001, Parts))
3165       return SDValue();
3166     SDValue N010 = N01.getOperand(0);
3167     if (!isBSwapHWordElement(N010, Parts))
3168       return SDValue();
3169     SDValue N011 = N01.getOperand(1);
3170     if (!isBSwapHWordElement(N011, Parts))
3171       return SDValue();
3172   } else {
3173     // (or (or (or (and), (and)), (and)), (and))
3174     if (!isBSwapHWordElement(N1, Parts))
3175       return SDValue();
3176     if (!isBSwapHWordElement(N01, Parts))
3177       return SDValue();
3178     if (N00.getOpcode() != ISD::OR)
3179       return SDValue();
3180     SDValue N000 = N00.getOperand(0);
3181     if (!isBSwapHWordElement(N000, Parts))
3182       return SDValue();
3183     SDValue N001 = N00.getOperand(1);
3184     if (!isBSwapHWordElement(N001, Parts))
3185       return SDValue();
3186   }
3187
3188   // Make sure the parts are all coming from the same node.
3189   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3190     return SDValue();
3191
3192   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3193                               SDValue(Parts[0],0));
3194
3195   // Result of the bswap should be rotated by 16. If it's not legal, then
3196   // do  (x << 16) | (x >> 16).
3197   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3198   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3199     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3200   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3201     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3202   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3203                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3204                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3205 }
3206
3207 SDValue DAGCombiner::visitOR(SDNode *N) {
3208   SDValue N0 = N->getOperand(0);
3209   SDValue N1 = N->getOperand(1);
3210   SDValue LL, LR, RL, RR, CC0, CC1;
3211   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3212   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3213   EVT VT = N1.getValueType();
3214
3215   // fold vector ops
3216   if (VT.isVector()) {
3217     SDValue FoldedVOp = SimplifyVBinOp(N);
3218     if (FoldedVOp.getNode()) return FoldedVOp;
3219
3220     // fold (or x, 0) -> x, vector edition
3221     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3222       return N1;
3223     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3224       return N0;
3225
3226     // fold (or x, -1) -> -1, vector edition
3227     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3228       return N0;
3229     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3230       return N1;
3231
3232     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3233     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3234     // Do this only if the resulting shuffle is legal.
3235     if (isa<ShuffleVectorSDNode>(N0) &&
3236         isa<ShuffleVectorSDNode>(N1) &&
3237         N0->getOperand(1) == N1->getOperand(1) &&
3238         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3239       bool CanFold = true;
3240       unsigned NumElts = VT.getVectorNumElements();
3241       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3242       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3243       // We construct two shuffle masks:
3244       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3245       // and N1 as the second operand.
3246       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3247       // and N0 as the second operand.
3248       // We do this because OR is commutable and therefore there might be
3249       // two ways to fold this node into a shuffle.
3250       SmallVector<int,4> Mask1;
3251       SmallVector<int,4> Mask2;
3252
3253       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3254         int M0 = SV0->getMaskElt(i);
3255         int M1 = SV1->getMaskElt(i);
3256
3257         // Both shuffle indexes are undef. Propagate Undef.
3258         if (M0 < 0 && M1 < 0) {
3259           Mask1.push_back(M0);
3260           Mask2.push_back(M0);
3261           continue;
3262         }
3263
3264         if (M0 < 0 || M1 < 0 ||
3265             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3266             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3267           CanFold = false;
3268           break;
3269         }
3270
3271         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3272         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3273       }
3274
3275       if (CanFold) {
3276         // Fold this sequence only if the resulting shuffle is 'legal'.
3277         if (TLI.isShuffleMaskLegal(Mask1, VT))
3278           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3279                                       N1->getOperand(0), &Mask1[0]);
3280         if (TLI.isShuffleMaskLegal(Mask2, VT))
3281           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3282                                       N0->getOperand(0), &Mask2[0]);
3283       }
3284     }
3285   }
3286
3287   // fold (or x, undef) -> -1
3288   if (!LegalOperations &&
3289       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3290     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3291     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3292   }
3293   // fold (or c1, c2) -> c1|c2
3294   if (N0C && N1C)
3295     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3296   // canonicalize constant to RHS
3297   if (N0C && !N1C)
3298     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3299   // fold (or x, 0) -> x
3300   if (N1C && N1C->isNullValue())
3301     return N0;
3302   // fold (or x, -1) -> -1
3303   if (N1C && N1C->isAllOnesValue())
3304     return N1;
3305   // fold (or x, c) -> c iff (x & ~c) == 0
3306   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3307     return N1;
3308
3309   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3310   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3311   if (BSwap.getNode())
3312     return BSwap;
3313   BSwap = MatchBSwapHWordLow(N, N0, N1);
3314   if (BSwap.getNode())
3315     return BSwap;
3316
3317   // reassociate or
3318   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3319   if (ROR.getNode())
3320     return ROR;
3321   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3322   // iff (c1 & c2) == 0.
3323   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3324              isa<ConstantSDNode>(N0.getOperand(1))) {
3325     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3326     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3327       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3328       if (!COR.getNode())
3329         return SDValue();
3330       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3331                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3332                                      N0.getOperand(0), N1), COR);
3333     }
3334   }
3335   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3336   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3337     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3338     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3339
3340     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3341         LL.getValueType().isInteger()) {
3342       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3343       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3344       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3345           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3346         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3347                                      LR.getValueType(), LL, RL);
3348         AddToWorkList(ORNode.getNode());
3349         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3350       }
3351       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3352       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3353       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3354           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3355         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3356                                       LR.getValueType(), LL, RL);
3357         AddToWorkList(ANDNode.getNode());
3358         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3359       }
3360     }
3361     // canonicalize equivalent to ll == rl
3362     if (LL == RR && LR == RL) {
3363       Op1 = ISD::getSetCCSwappedOperands(Op1);
3364       std::swap(RL, RR);
3365     }
3366     if (LL == RL && LR == RR) {
3367       bool isInteger = LL.getValueType().isInteger();
3368       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3369       if (Result != ISD::SETCC_INVALID &&
3370           (!LegalOperations ||
3371            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3372             TLI.isOperationLegal(ISD::SETCC,
3373               getSetCCResultType(N0.getValueType())))))
3374         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3375                             LL, LR, Result);
3376     }
3377   }
3378
3379   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3380   if (N0.getOpcode() == N1.getOpcode()) {
3381     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3382     if (Tmp.getNode()) return Tmp;
3383   }
3384
3385   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3386   if (N0.getOpcode() == ISD::AND &&
3387       N1.getOpcode() == ISD::AND &&
3388       N0.getOperand(1).getOpcode() == ISD::Constant &&
3389       N1.getOperand(1).getOpcode() == ISD::Constant &&
3390       // Don't increase # computations.
3391       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3392     // We can only do this xform if we know that bits from X that are set in C2
3393     // but not in C1 are already zero.  Likewise for Y.
3394     const APInt &LHSMask =
3395       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3396     const APInt &RHSMask =
3397       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3398
3399     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3400         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3401       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3402                               N0.getOperand(0), N1.getOperand(0));
3403       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3404                          DAG.getConstant(LHSMask | RHSMask, VT));
3405     }
3406   }
3407
3408   // See if this is some rotate idiom.
3409   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3410     return SDValue(Rot, 0);
3411
3412   // Simplify the operands using demanded-bits information.
3413   if (!VT.isVector() &&
3414       SimplifyDemandedBits(SDValue(N, 0)))
3415     return SDValue(N, 0);
3416
3417   return SDValue();
3418 }
3419
3420 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3421 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3422   if (Op.getOpcode() == ISD::AND) {
3423     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3424       Mask = Op.getOperand(1);
3425       Op = Op.getOperand(0);
3426     } else {
3427       return false;
3428     }
3429   }
3430
3431   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3432     Shift = Op;
3433     return true;
3434   }
3435
3436   return false;
3437 }
3438
3439 // Return true if we can prove that, whenever Neg and Pos are both in the
3440 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3441 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3442 //
3443 //     (or (shift1 X, Neg), (shift2 X, Pos))
3444 //
3445 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3446 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3447 // to consider shift amounts with defined behavior.
3448 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3449   // If OpSize is a power of 2 then:
3450   //
3451   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3452   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3453   //
3454   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3455   // for the stronger condition:
3456   //
3457   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3458   //
3459   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3460   // we can just replace Neg with Neg' for the rest of the function.
3461   //
3462   // In other cases we check for the even stronger condition:
3463   //
3464   //     Neg == OpSize - Pos                                    [B]
3465   //
3466   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3467   // behavior if Pos == 0 (and consequently Neg == OpSize).
3468   //
3469   // We could actually use [A] whenever OpSize is a power of 2, but the
3470   // only extra cases that it would match are those uninteresting ones
3471   // where Neg and Pos are never in range at the same time.  E.g. for
3472   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3473   // as well as (sub 32, Pos), but:
3474   //
3475   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3476   //
3477   // always invokes undefined behavior for 32-bit X.
3478   //
3479   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3480   unsigned MaskLoBits = 0;
3481   if (Neg.getOpcode() == ISD::AND &&
3482       isPowerOf2_64(OpSize) &&
3483       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3484       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3485     Neg = Neg.getOperand(0);
3486     MaskLoBits = Log2_64(OpSize);
3487   }
3488
3489   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3490   if (Neg.getOpcode() != ISD::SUB)
3491     return 0;
3492   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3493   if (!NegC)
3494     return 0;
3495   SDValue NegOp1 = Neg.getOperand(1);
3496
3497   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3498   // Pos'.  The truncation is redundant for the purpose of the equality.
3499   if (MaskLoBits &&
3500       Pos.getOpcode() == ISD::AND &&
3501       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3502       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3503     Pos = Pos.getOperand(0);
3504
3505   // The condition we need is now:
3506   //
3507   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3508   //
3509   // If NegOp1 == Pos then we need:
3510   //
3511   //              OpSize & Mask == NegC & Mask
3512   //
3513   // (because "x & Mask" is a truncation and distributes through subtraction).
3514   APInt Width;
3515   if (Pos == NegOp1)
3516     Width = NegC->getAPIntValue();
3517   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3518   // Then the condition we want to prove becomes:
3519   //
3520   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3521   //
3522   // which, again because "x & Mask" is a truncation, becomes:
3523   //
3524   //                NegC & Mask == (OpSize - PosC) & Mask
3525   //              OpSize & Mask == (NegC + PosC) & Mask
3526   else if (Pos.getOpcode() == ISD::ADD &&
3527            Pos.getOperand(0) == NegOp1 &&
3528            Pos.getOperand(1).getOpcode() == ISD::Constant)
3529     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3530              NegC->getAPIntValue());
3531   else
3532     return false;
3533
3534   // Now we just need to check that OpSize & Mask == Width & Mask.
3535   if (MaskLoBits)
3536     // Opsize & Mask is 0 since Mask is Opsize - 1.
3537     return Width.getLoBits(MaskLoBits) == 0;
3538   return Width == OpSize;
3539 }
3540
3541 // A subroutine of MatchRotate used once we have found an OR of two opposite
3542 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3543 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3544 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3545 // Neg with outer conversions stripped away.
3546 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3547                                        SDValue Neg, SDValue InnerPos,
3548                                        SDValue InnerNeg, unsigned PosOpcode,
3549                                        unsigned NegOpcode, SDLoc DL) {
3550   // fold (or (shl x, (*ext y)),
3551   //          (srl x, (*ext (sub 32, y)))) ->
3552   //   (rotl x, y) or (rotr x, (sub 32, y))
3553   //
3554   // fold (or (shl x, (*ext (sub 32, y))),
3555   //          (srl x, (*ext y))) ->
3556   //   (rotr x, y) or (rotl x, (sub 32, y))
3557   EVT VT = Shifted.getValueType();
3558   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3559     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3560     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3561                        HasPos ? Pos : Neg).getNode();
3562   }
3563
3564   return nullptr;
3565 }
3566
3567 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3568 // idioms for rotate, and if the target supports rotation instructions, generate
3569 // a rot[lr].
3570 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3571   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3572   EVT VT = LHS.getValueType();
3573   if (!TLI.isTypeLegal(VT)) return nullptr;
3574
3575   // The target must have at least one rotate flavor.
3576   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3577   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3578   if (!HasROTL && !HasROTR) return nullptr;
3579
3580   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3581   SDValue LHSShift;   // The shift.
3582   SDValue LHSMask;    // AND value if any.
3583   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3584     return nullptr; // Not part of a rotate.
3585
3586   SDValue RHSShift;   // The shift.
3587   SDValue RHSMask;    // AND value if any.
3588   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3589     return nullptr; // Not part of a rotate.
3590
3591   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3592     return nullptr;   // Not shifting the same value.
3593
3594   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3595     return nullptr;   // Shifts must disagree.
3596
3597   // Canonicalize shl to left side in a shl/srl pair.
3598   if (RHSShift.getOpcode() == ISD::SHL) {
3599     std::swap(LHS, RHS);
3600     std::swap(LHSShift, RHSShift);
3601     std::swap(LHSMask , RHSMask );
3602   }
3603
3604   unsigned OpSizeInBits = VT.getSizeInBits();
3605   SDValue LHSShiftArg = LHSShift.getOperand(0);
3606   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3607   SDValue RHSShiftArg = RHSShift.getOperand(0);
3608   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3609
3610   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3611   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3612   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3613       RHSShiftAmt.getOpcode() == ISD::Constant) {
3614     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3615     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3616     if ((LShVal + RShVal) != OpSizeInBits)
3617       return nullptr;
3618
3619     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3620                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3621
3622     // If there is an AND of either shifted operand, apply it to the result.
3623     if (LHSMask.getNode() || RHSMask.getNode()) {
3624       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3625
3626       if (LHSMask.getNode()) {
3627         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3628         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3629       }
3630       if (RHSMask.getNode()) {
3631         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3632         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3633       }
3634
3635       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3636     }
3637
3638     return Rot.getNode();
3639   }
3640
3641   // If there is a mask here, and we have a variable shift, we can't be sure
3642   // that we're masking out the right stuff.
3643   if (LHSMask.getNode() || RHSMask.getNode())
3644     return nullptr;
3645
3646   // If the shift amount is sign/zext/any-extended just peel it off.
3647   SDValue LExtOp0 = LHSShiftAmt;
3648   SDValue RExtOp0 = RHSShiftAmt;
3649   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3650        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3651        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3652        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3653       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3654        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3655        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3656        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3657     LExtOp0 = LHSShiftAmt.getOperand(0);
3658     RExtOp0 = RHSShiftAmt.getOperand(0);
3659   }
3660
3661   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3662                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3663   if (TryL)
3664     return TryL;
3665
3666   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3667                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3668   if (TryR)
3669     return TryR;
3670
3671   return nullptr;
3672 }
3673
3674 SDValue DAGCombiner::visitXOR(SDNode *N) {
3675   SDValue N0 = N->getOperand(0);
3676   SDValue N1 = N->getOperand(1);
3677   SDValue LHS, RHS, CC;
3678   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3679   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3680   EVT VT = N0.getValueType();
3681
3682   // fold vector ops
3683   if (VT.isVector()) {
3684     SDValue FoldedVOp = SimplifyVBinOp(N);
3685     if (FoldedVOp.getNode()) return FoldedVOp;
3686
3687     // fold (xor x, 0) -> x, vector edition
3688     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3689       return N1;
3690     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3691       return N0;
3692   }
3693
3694   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3695   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3696     return DAG.getConstant(0, VT);
3697   // fold (xor x, undef) -> undef
3698   if (N0.getOpcode() == ISD::UNDEF)
3699     return N0;
3700   if (N1.getOpcode() == ISD::UNDEF)
3701     return N1;
3702   // fold (xor c1, c2) -> c1^c2
3703   if (N0C && N1C)
3704     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3705   // canonicalize constant to RHS
3706   if (N0C && !N1C)
3707     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3708   // fold (xor x, 0) -> x
3709   if (N1C && N1C->isNullValue())
3710     return N0;
3711   // reassociate xor
3712   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3713   if (RXOR.getNode())
3714     return RXOR;
3715
3716   // fold !(x cc y) -> (x !cc y)
3717   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3718     bool isInt = LHS.getValueType().isInteger();
3719     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3720                                                isInt);
3721
3722     if (!LegalOperations ||
3723         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3724       switch (N0.getOpcode()) {
3725       default:
3726         llvm_unreachable("Unhandled SetCC Equivalent!");
3727       case ISD::SETCC:
3728         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3729       case ISD::SELECT_CC:
3730         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3731                                N0.getOperand(3), NotCC);
3732       }
3733     }
3734   }
3735
3736   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3737   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3738       N0.getNode()->hasOneUse() &&
3739       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3740     SDValue V = N0.getOperand(0);
3741     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3742                     DAG.getConstant(1, V.getValueType()));
3743     AddToWorkList(V.getNode());
3744     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3745   }
3746
3747   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3748   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3749       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3750     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3751     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3752       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3753       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3754       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3755       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3756       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3757     }
3758   }
3759   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3760   if (N1C && N1C->isAllOnesValue() &&
3761       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3762     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3763     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3764       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3765       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3766       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3767       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3768       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3769     }
3770   }
3771   // fold (xor (and x, y), y) -> (and (not x), y)
3772   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3773       N0->getOperand(1) == N1) {
3774     SDValue X = N0->getOperand(0);
3775     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3776     AddToWorkList(NotX.getNode());
3777     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3778   }
3779   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3780   if (N1C && N0.getOpcode() == ISD::XOR) {
3781     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3782     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3783     if (N00C)
3784       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3785                          DAG.getConstant(N1C->getAPIntValue() ^
3786                                          N00C->getAPIntValue(), VT));
3787     if (N01C)
3788       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3789                          DAG.getConstant(N1C->getAPIntValue() ^
3790                                          N01C->getAPIntValue(), VT));
3791   }
3792   // fold (xor x, x) -> 0
3793   if (N0 == N1)
3794     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3795
3796   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3797   if (N0.getOpcode() == N1.getOpcode()) {
3798     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3799     if (Tmp.getNode()) return Tmp;
3800   }
3801
3802   // Simplify the expression using non-local knowledge.
3803   if (!VT.isVector() &&
3804       SimplifyDemandedBits(SDValue(N, 0)))
3805     return SDValue(N, 0);
3806
3807   return SDValue();
3808 }
3809
3810 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3811 /// the shift amount is a constant.
3812 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3813   // We can't and shouldn't fold opaque constants.
3814   if (Amt->isOpaque())
3815     return SDValue();
3816
3817   SDNode *LHS = N->getOperand(0).getNode();
3818   if (!LHS->hasOneUse()) return SDValue();
3819
3820   // We want to pull some binops through shifts, so that we have (and (shift))
3821   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3822   // thing happens with address calculations, so it's important to canonicalize
3823   // it.
3824   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3825
3826   switch (LHS->getOpcode()) {
3827   default: return SDValue();
3828   case ISD::OR:
3829   case ISD::XOR:
3830     HighBitSet = false; // We can only transform sra if the high bit is clear.
3831     break;
3832   case ISD::AND:
3833     HighBitSet = true;  // We can only transform sra if the high bit is set.
3834     break;
3835   case ISD::ADD:
3836     if (N->getOpcode() != ISD::SHL)
3837       return SDValue(); // only shl(add) not sr[al](add).
3838     HighBitSet = false; // We can only transform sra if the high bit is clear.
3839     break;
3840   }
3841
3842   // We require the RHS of the binop to be a constant and not opaque as well.
3843   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3844   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3845
3846   // FIXME: disable this unless the input to the binop is a shift by a constant.
3847   // If it is not a shift, it pessimizes some common cases like:
3848   //
3849   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3850   //    int bar(int *X, int i) { return X[i & 255]; }
3851   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3852   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3853        BinOpLHSVal->getOpcode() != ISD::SRA &&
3854        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3855       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3856     return SDValue();
3857
3858   EVT VT = N->getValueType(0);
3859
3860   // If this is a signed shift right, and the high bit is modified by the
3861   // logical operation, do not perform the transformation. The highBitSet
3862   // boolean indicates the value of the high bit of the constant which would
3863   // cause it to be modified for this operation.
3864   if (N->getOpcode() == ISD::SRA) {
3865     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3866     if (BinOpRHSSignSet != HighBitSet)
3867       return SDValue();
3868   }
3869
3870   if (!TLI.isDesirableToCommuteWithShift(LHS))
3871     return SDValue();
3872
3873   // Fold the constants, shifting the binop RHS by the shift amount.
3874   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3875                                N->getValueType(0),
3876                                LHS->getOperand(1), N->getOperand(1));
3877   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3878
3879   // Create the new shift.
3880   SDValue NewShift = DAG.getNode(N->getOpcode(),
3881                                  SDLoc(LHS->getOperand(0)),
3882                                  VT, LHS->getOperand(0), N->getOperand(1));
3883
3884   // Create the new binop.
3885   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3886 }
3887
3888 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3889   assert(N->getOpcode() == ISD::TRUNCATE);
3890   assert(N->getOperand(0).getOpcode() == ISD::AND);
3891
3892   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3893   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3894     SDValue N01 = N->getOperand(0).getOperand(1);
3895
3896     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3897       EVT TruncVT = N->getValueType(0);
3898       SDValue N00 = N->getOperand(0).getOperand(0);
3899       APInt TruncC = N01C->getAPIntValue();
3900       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3901
3902       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3903                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3904                          DAG.getConstant(TruncC, TruncVT));
3905     }
3906   }
3907
3908   return SDValue();
3909 }
3910
3911 SDValue DAGCombiner::visitRotate(SDNode *N) {
3912   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3913   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3914       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3915     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3916     if (NewOp1.getNode())
3917       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3918                          N->getOperand(0), NewOp1);
3919   }
3920   return SDValue();
3921 }
3922
3923 SDValue DAGCombiner::visitSHL(SDNode *N) {
3924   SDValue N0 = N->getOperand(0);
3925   SDValue N1 = N->getOperand(1);
3926   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3927   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3928   EVT VT = N0.getValueType();
3929   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3930
3931   // fold vector ops
3932   if (VT.isVector()) {
3933     SDValue FoldedVOp = SimplifyVBinOp(N);
3934     if (FoldedVOp.getNode()) return FoldedVOp;
3935
3936     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3937     // If setcc produces all-one true value then:
3938     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3939     if (N1CV && N1CV->isConstant()) {
3940       if (N0.getOpcode() == ISD::AND &&
3941           TLI.getBooleanContents(true) ==
3942           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3943         SDValue N00 = N0->getOperand(0);
3944         SDValue N01 = N0->getOperand(1);
3945         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3946
3947         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3948           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3949           if (C.getNode())
3950             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3951         }
3952       } else {
3953         N1C = isConstOrConstSplat(N1);
3954       }
3955     }
3956   }
3957
3958   // fold (shl c1, c2) -> c1<<c2
3959   if (N0C && N1C)
3960     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3961   // fold (shl 0, x) -> 0
3962   if (N0C && N0C->isNullValue())
3963     return N0;
3964   // fold (shl x, c >= size(x)) -> undef
3965   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3966     return DAG.getUNDEF(VT);
3967   // fold (shl x, 0) -> x
3968   if (N1C && N1C->isNullValue())
3969     return N0;
3970   // fold (shl undef, x) -> 0
3971   if (N0.getOpcode() == ISD::UNDEF)
3972     return DAG.getConstant(0, VT);
3973   // if (shl x, c) is known to be zero, return 0
3974   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3975                             APInt::getAllOnesValue(OpSizeInBits)))
3976     return DAG.getConstant(0, VT);
3977   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3978   if (N1.getOpcode() == ISD::TRUNCATE &&
3979       N1.getOperand(0).getOpcode() == ISD::AND) {
3980     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3981     if (NewOp1.getNode())
3982       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3983   }
3984
3985   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3986     return SDValue(N, 0);
3987
3988   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3989   if (N1C && N0.getOpcode() == ISD::SHL) {
3990     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3991       uint64_t c1 = N0C1->getZExtValue();
3992       uint64_t c2 = N1C->getZExtValue();
3993       if (c1 + c2 >= OpSizeInBits)
3994         return DAG.getConstant(0, VT);
3995       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3996                          DAG.getConstant(c1 + c2, N1.getValueType()));
3997     }
3998   }
3999
4000   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4001   // For this to be valid, the second form must not preserve any of the bits
4002   // that are shifted out by the inner shift in the first form.  This means
4003   // the outer shift size must be >= the number of bits added by the ext.
4004   // As a corollary, we don't care what kind of ext it is.
4005   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4006               N0.getOpcode() == ISD::ANY_EXTEND ||
4007               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4008       N0.getOperand(0).getOpcode() == ISD::SHL) {
4009     SDValue N0Op0 = N0.getOperand(0);
4010     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4011       uint64_t c1 = N0Op0C1->getZExtValue();
4012       uint64_t c2 = N1C->getZExtValue();
4013       EVT InnerShiftVT = N0Op0.getValueType();
4014       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4015       if (c2 >= OpSizeInBits - InnerShiftSize) {
4016         if (c1 + c2 >= OpSizeInBits)
4017           return DAG.getConstant(0, VT);
4018         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4019                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4020                                        N0Op0->getOperand(0)),
4021                            DAG.getConstant(c1 + c2, N1.getValueType()));
4022       }
4023     }
4024   }
4025
4026   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4027   // Only fold this if the inner zext has no other uses to avoid increasing
4028   // the total number of instructions.
4029   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4030       N0.getOperand(0).getOpcode() == ISD::SRL) {
4031     SDValue N0Op0 = N0.getOperand(0);
4032     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4033       uint64_t c1 = N0Op0C1->getZExtValue();
4034       if (c1 < VT.getScalarSizeInBits()) {
4035         uint64_t c2 = N1C->getZExtValue();
4036         if (c1 == c2) {
4037           SDValue NewOp0 = N0.getOperand(0);
4038           EVT CountVT = NewOp0.getOperand(1).getValueType();
4039           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4040                                        NewOp0, DAG.getConstant(c2, CountVT));
4041           AddToWorkList(NewSHL.getNode());
4042           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4043         }
4044       }
4045     }
4046   }
4047
4048   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4049   //                               (and (srl x, (sub c1, c2), MASK)
4050   // Only fold this if the inner shift has no other uses -- if it does, folding
4051   // this will increase the total number of instructions.
4052   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4053     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4054       uint64_t c1 = N0C1->getZExtValue();
4055       if (c1 < OpSizeInBits) {
4056         uint64_t c2 = N1C->getZExtValue();
4057         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4058         SDValue Shift;
4059         if (c2 > c1) {
4060           Mask = Mask.shl(c2 - c1);
4061           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4062                               DAG.getConstant(c2 - c1, N1.getValueType()));
4063         } else {
4064           Mask = Mask.lshr(c1 - c2);
4065           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4066                               DAG.getConstant(c1 - c2, N1.getValueType()));
4067         }
4068         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4069                            DAG.getConstant(Mask, VT));
4070       }
4071     }
4072   }
4073   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4074   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4075     unsigned BitSize = VT.getScalarSizeInBits();
4076     SDValue HiBitsMask =
4077       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4078                                             BitSize - N1C->getZExtValue()), VT);
4079     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4080                        HiBitsMask);
4081   }
4082
4083   if (N1C) {
4084     SDValue NewSHL = visitShiftByConstant(N, N1C);
4085     if (NewSHL.getNode())
4086       return NewSHL;
4087   }
4088
4089   return SDValue();
4090 }
4091
4092 SDValue DAGCombiner::visitSRA(SDNode *N) {
4093   SDValue N0 = N->getOperand(0);
4094   SDValue N1 = N->getOperand(1);
4095   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4096   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4097   EVT VT = N0.getValueType();
4098   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4099
4100   // fold vector ops
4101   if (VT.isVector()) {
4102     SDValue FoldedVOp = SimplifyVBinOp(N);
4103     if (FoldedVOp.getNode()) return FoldedVOp;
4104
4105     N1C = isConstOrConstSplat(N1);
4106   }
4107
4108   // fold (sra c1, c2) -> (sra c1, c2)
4109   if (N0C && N1C)
4110     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4111   // fold (sra 0, x) -> 0
4112   if (N0C && N0C->isNullValue())
4113     return N0;
4114   // fold (sra -1, x) -> -1
4115   if (N0C && N0C->isAllOnesValue())
4116     return N0;
4117   // fold (sra x, (setge c, size(x))) -> undef
4118   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4119     return DAG.getUNDEF(VT);
4120   // fold (sra x, 0) -> x
4121   if (N1C && N1C->isNullValue())
4122     return N0;
4123   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4124   // sext_inreg.
4125   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4126     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4127     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4128     if (VT.isVector())
4129       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4130                                ExtVT, VT.getVectorNumElements());
4131     if ((!LegalOperations ||
4132          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4133       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4134                          N0.getOperand(0), DAG.getValueType(ExtVT));
4135   }
4136
4137   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4138   if (N1C && N0.getOpcode() == ISD::SRA) {
4139     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4140       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4141       if (Sum >= OpSizeInBits)
4142         Sum = OpSizeInBits - 1;
4143       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4144                          DAG.getConstant(Sum, N1.getValueType()));
4145     }
4146   }
4147
4148   // fold (sra (shl X, m), (sub result_size, n))
4149   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4150   // result_size - n != m.
4151   // If truncate is free for the target sext(shl) is likely to result in better
4152   // code.
4153   if (N0.getOpcode() == ISD::SHL && N1C) {
4154     // Get the two constanst of the shifts, CN0 = m, CN = n.
4155     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4156     if (N01C) {
4157       LLVMContext &Ctx = *DAG.getContext();
4158       // Determine what the truncate's result bitsize and type would be.
4159       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4160
4161       if (VT.isVector())
4162         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4163
4164       // Determine the residual right-shift amount.
4165       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4166
4167       // If the shift is not a no-op (in which case this should be just a sign
4168       // extend already), the truncated to type is legal, sign_extend is legal
4169       // on that type, and the truncate to that type is both legal and free,
4170       // perform the transform.
4171       if ((ShiftAmt > 0) &&
4172           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4173           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4174           TLI.isTruncateFree(VT, TruncVT)) {
4175
4176           SDValue Amt = DAG.getConstant(ShiftAmt,
4177               getShiftAmountTy(N0.getOperand(0).getValueType()));
4178           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4179                                       N0.getOperand(0), Amt);
4180           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4181                                       Shift);
4182           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4183                              N->getValueType(0), Trunc);
4184       }
4185     }
4186   }
4187
4188   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4189   if (N1.getOpcode() == ISD::TRUNCATE &&
4190       N1.getOperand(0).getOpcode() == ISD::AND) {
4191     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4192     if (NewOp1.getNode())
4193       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4194   }
4195
4196   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4197   //      if c1 is equal to the number of bits the trunc removes
4198   if (N0.getOpcode() == ISD::TRUNCATE &&
4199       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4200        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4201       N0.getOperand(0).hasOneUse() &&
4202       N0.getOperand(0).getOperand(1).hasOneUse() &&
4203       N1C) {
4204     SDValue N0Op0 = N0.getOperand(0);
4205     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4206       unsigned LargeShiftVal = LargeShift->getZExtValue();
4207       EVT LargeVT = N0Op0.getValueType();
4208
4209       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4210         SDValue Amt =
4211           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4212                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4213         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4214                                   N0Op0.getOperand(0), Amt);
4215         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4216       }
4217     }
4218   }
4219
4220   // Simplify, based on bits shifted out of the LHS.
4221   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4222     return SDValue(N, 0);
4223
4224
4225   // If the sign bit is known to be zero, switch this to a SRL.
4226   if (DAG.SignBitIsZero(N0))
4227     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4228
4229   if (N1C) {
4230     SDValue NewSRA = visitShiftByConstant(N, N1C);
4231     if (NewSRA.getNode())
4232       return NewSRA;
4233   }
4234
4235   return SDValue();
4236 }
4237
4238 SDValue DAGCombiner::visitSRL(SDNode *N) {
4239   SDValue N0 = N->getOperand(0);
4240   SDValue N1 = N->getOperand(1);
4241   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4242   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4243   EVT VT = N0.getValueType();
4244   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4245
4246   // fold vector ops
4247   if (VT.isVector()) {
4248     SDValue FoldedVOp = SimplifyVBinOp(N);
4249     if (FoldedVOp.getNode()) return FoldedVOp;
4250
4251     N1C = isConstOrConstSplat(N1);
4252   }
4253
4254   // fold (srl c1, c2) -> c1 >>u c2
4255   if (N0C && N1C)
4256     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4257   // fold (srl 0, x) -> 0
4258   if (N0C && N0C->isNullValue())
4259     return N0;
4260   // fold (srl x, c >= size(x)) -> undef
4261   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4262     return DAG.getUNDEF(VT);
4263   // fold (srl x, 0) -> x
4264   if (N1C && N1C->isNullValue())
4265     return N0;
4266   // if (srl x, c) is known to be zero, return 0
4267   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4268                                    APInt::getAllOnesValue(OpSizeInBits)))
4269     return DAG.getConstant(0, VT);
4270
4271   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4272   if (N1C && N0.getOpcode() == ISD::SRL) {
4273     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4274       uint64_t c1 = N01C->getZExtValue();
4275       uint64_t c2 = N1C->getZExtValue();
4276       if (c1 + c2 >= OpSizeInBits)
4277         return DAG.getConstant(0, VT);
4278       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4279                          DAG.getConstant(c1 + c2, N1.getValueType()));
4280     }
4281   }
4282
4283   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4284   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4285       N0.getOperand(0).getOpcode() == ISD::SRL &&
4286       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4287     uint64_t c1 =
4288       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4289     uint64_t c2 = N1C->getZExtValue();
4290     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4291     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4292     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4293     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4294     if (c1 + OpSizeInBits == InnerShiftSize) {
4295       if (c1 + c2 >= InnerShiftSize)
4296         return DAG.getConstant(0, VT);
4297       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4298                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4299                                      N0.getOperand(0)->getOperand(0),
4300                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4301     }
4302   }
4303
4304   // fold (srl (shl x, c), c) -> (and x, cst2)
4305   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4306     unsigned BitSize = N0.getScalarValueSizeInBits();
4307     if (BitSize <= 64) {
4308       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4309       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4310                          DAG.getConstant(~0ULL >> ShAmt, VT));
4311     }
4312   }
4313
4314   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4315   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4316     // Shifting in all undef bits?
4317     EVT SmallVT = N0.getOperand(0).getValueType();
4318     unsigned BitSize = SmallVT.getScalarSizeInBits();
4319     if (N1C->getZExtValue() >= BitSize)
4320       return DAG.getUNDEF(VT);
4321
4322     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4323       uint64_t ShiftAmt = N1C->getZExtValue();
4324       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4325                                        N0.getOperand(0),
4326                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4327       AddToWorkList(SmallShift.getNode());
4328       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4329       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4330                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4331                          DAG.getConstant(Mask, VT));
4332     }
4333   }
4334
4335   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4336   // bit, which is unmodified by sra.
4337   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4338     if (N0.getOpcode() == ISD::SRA)
4339       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4340   }
4341
4342   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4343   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4344       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4345     APInt KnownZero, KnownOne;
4346     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4347
4348     // If any of the input bits are KnownOne, then the input couldn't be all
4349     // zeros, thus the result of the srl will always be zero.
4350     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4351
4352     // If all of the bits input the to ctlz node are known to be zero, then
4353     // the result of the ctlz is "32" and the result of the shift is one.
4354     APInt UnknownBits = ~KnownZero;
4355     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4356
4357     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4358     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4359       // Okay, we know that only that the single bit specified by UnknownBits
4360       // could be set on input to the CTLZ node. If this bit is set, the SRL
4361       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4362       // to an SRL/XOR pair, which is likely to simplify more.
4363       unsigned ShAmt = UnknownBits.countTrailingZeros();
4364       SDValue Op = N0.getOperand(0);
4365
4366       if (ShAmt) {
4367         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4368                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4369         AddToWorkList(Op.getNode());
4370       }
4371
4372       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4373                          Op, DAG.getConstant(1, VT));
4374     }
4375   }
4376
4377   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4378   if (N1.getOpcode() == ISD::TRUNCATE &&
4379       N1.getOperand(0).getOpcode() == ISD::AND) {
4380     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4381     if (NewOp1.getNode())
4382       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4383   }
4384
4385   // fold operands of srl based on knowledge that the low bits are not
4386   // demanded.
4387   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4388     return SDValue(N, 0);
4389
4390   if (N1C) {
4391     SDValue NewSRL = visitShiftByConstant(N, N1C);
4392     if (NewSRL.getNode())
4393       return NewSRL;
4394   }
4395
4396   // Attempt to convert a srl of a load into a narrower zero-extending load.
4397   SDValue NarrowLoad = ReduceLoadWidth(N);
4398   if (NarrowLoad.getNode())
4399     return NarrowLoad;
4400
4401   // Here is a common situation. We want to optimize:
4402   //
4403   //   %a = ...
4404   //   %b = and i32 %a, 2
4405   //   %c = srl i32 %b, 1
4406   //   brcond i32 %c ...
4407   //
4408   // into
4409   //
4410   //   %a = ...
4411   //   %b = and %a, 2
4412   //   %c = setcc eq %b, 0
4413   //   brcond %c ...
4414   //
4415   // However when after the source operand of SRL is optimized into AND, the SRL
4416   // itself may not be optimized further. Look for it and add the BRCOND into
4417   // the worklist.
4418   if (N->hasOneUse()) {
4419     SDNode *Use = *N->use_begin();
4420     if (Use->getOpcode() == ISD::BRCOND)
4421       AddToWorkList(Use);
4422     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4423       // Also look pass the truncate.
4424       Use = *Use->use_begin();
4425       if (Use->getOpcode() == ISD::BRCOND)
4426         AddToWorkList(Use);
4427     }
4428   }
4429
4430   return SDValue();
4431 }
4432
4433 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4434   SDValue N0 = N->getOperand(0);
4435   EVT VT = N->getValueType(0);
4436
4437   // fold (ctlz c1) -> c2
4438   if (isa<ConstantSDNode>(N0))
4439     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4440   return SDValue();
4441 }
4442
4443 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4444   SDValue N0 = N->getOperand(0);
4445   EVT VT = N->getValueType(0);
4446
4447   // fold (ctlz_zero_undef c1) -> c2
4448   if (isa<ConstantSDNode>(N0))
4449     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4450   return SDValue();
4451 }
4452
4453 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4454   SDValue N0 = N->getOperand(0);
4455   EVT VT = N->getValueType(0);
4456
4457   // fold (cttz c1) -> c2
4458   if (isa<ConstantSDNode>(N0))
4459     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4460   return SDValue();
4461 }
4462
4463 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4464   SDValue N0 = N->getOperand(0);
4465   EVT VT = N->getValueType(0);
4466
4467   // fold (cttz_zero_undef c1) -> c2
4468   if (isa<ConstantSDNode>(N0))
4469     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4470   return SDValue();
4471 }
4472
4473 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4474   SDValue N0 = N->getOperand(0);
4475   EVT VT = N->getValueType(0);
4476
4477   // fold (ctpop c1) -> c2
4478   if (isa<ConstantSDNode>(N0))
4479     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4480   return SDValue();
4481 }
4482
4483 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4484   SDValue N0 = N->getOperand(0);
4485   SDValue N1 = N->getOperand(1);
4486   SDValue N2 = N->getOperand(2);
4487   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4488   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4489   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4490   EVT VT = N->getValueType(0);
4491   EVT VT0 = N0.getValueType();
4492
4493   // fold (select C, X, X) -> X
4494   if (N1 == N2)
4495     return N1;
4496   // fold (select true, X, Y) -> X
4497   if (N0C && !N0C->isNullValue())
4498     return N1;
4499   // fold (select false, X, Y) -> Y
4500   if (N0C && N0C->isNullValue())
4501     return N2;
4502   // fold (select C, 1, X) -> (or C, X)
4503   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4504     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4505   // fold (select C, 0, 1) -> (xor C, 1)
4506   if (VT.isInteger() &&
4507       (VT0 == MVT::i1 ||
4508        (VT0.isInteger() &&
4509         TLI.getBooleanContents(false) ==
4510         TargetLowering::ZeroOrOneBooleanContent)) &&
4511       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4512     SDValue XORNode;
4513     if (VT == VT0)
4514       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4515                          N0, DAG.getConstant(1, VT0));
4516     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4517                           N0, DAG.getConstant(1, VT0));
4518     AddToWorkList(XORNode.getNode());
4519     if (VT.bitsGT(VT0))
4520       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4521     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4522   }
4523   // fold (select C, 0, X) -> (and (not C), X)
4524   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4525     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4526     AddToWorkList(NOTNode.getNode());
4527     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4528   }
4529   // fold (select C, X, 1) -> (or (not C), X)
4530   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4531     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4532     AddToWorkList(NOTNode.getNode());
4533     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4534   }
4535   // fold (select C, X, 0) -> (and C, X)
4536   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4537     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4538   // fold (select X, X, Y) -> (or X, Y)
4539   // fold (select X, 1, Y) -> (or X, Y)
4540   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4541     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4542   // fold (select X, Y, X) -> (and X, Y)
4543   // fold (select X, Y, 0) -> (and X, Y)
4544   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4545     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4546
4547   // If we can fold this based on the true/false value, do so.
4548   if (SimplifySelectOps(N, N1, N2))
4549     return SDValue(N, 0);  // Don't revisit N.
4550
4551   // fold selects based on a setcc into other things, such as min/max/abs
4552   if (N0.getOpcode() == ISD::SETCC) {
4553     // FIXME:
4554     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4555     // having to say they don't support SELECT_CC on every type the DAG knows
4556     // about, since there is no way to mark an opcode illegal at all value types
4557     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4558         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4559       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4560                          N0.getOperand(0), N0.getOperand(1),
4561                          N1, N2, N0.getOperand(2));
4562     return SimplifySelect(SDLoc(N), N0, N1, N2);
4563   }
4564
4565   return SDValue();
4566 }
4567
4568 static
4569 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4570   SDLoc DL(N);
4571   EVT LoVT, HiVT;
4572   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4573
4574   // Split the inputs.
4575   SDValue Lo, Hi, LL, LH, RL, RH;
4576   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4577   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4578
4579   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4580   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4581
4582   return std::make_pair(Lo, Hi);
4583 }
4584
4585 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4586   SDValue N0 = N->getOperand(0);
4587   SDValue N1 = N->getOperand(1);
4588   SDValue N2 = N->getOperand(2);
4589   SDLoc DL(N);
4590
4591   // Canonicalize integer abs.
4592   // vselect (setg[te] X,  0),  X, -X ->
4593   // vselect (setgt    X, -1),  X, -X ->
4594   // vselect (setl[te] X,  0), -X,  X ->
4595   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4596   if (N0.getOpcode() == ISD::SETCC) {
4597     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4598     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4599     bool isAbs = false;
4600     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4601
4602     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4603          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4604         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4605       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4606     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4607              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4608       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4609
4610     if (isAbs) {
4611       EVT VT = LHS.getValueType();
4612       SDValue Shift = DAG.getNode(
4613           ISD::SRA, DL, VT, LHS,
4614           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4615       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4616       AddToWorkList(Shift.getNode());
4617       AddToWorkList(Add.getNode());
4618       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4619     }
4620   }
4621
4622   // If the VSELECT result requires splitting and the mask is provided by a
4623   // SETCC, then split both nodes and its operands before legalization. This
4624   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4625   // and enables future optimizations (e.g. min/max pattern matching on X86).
4626   if (N0.getOpcode() == ISD::SETCC) {
4627     EVT VT = N->getValueType(0);
4628
4629     // Check if any splitting is required.
4630     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4631         TargetLowering::TypeSplitVector)
4632       return SDValue();
4633
4634     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4635     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4636     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4637     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4638
4639     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4640     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4641
4642     // Add the new VSELECT nodes to the work list in case they need to be split
4643     // again.
4644     AddToWorkList(Lo.getNode());
4645     AddToWorkList(Hi.getNode());
4646
4647     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4648   }
4649
4650   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4651   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4652     return N1;
4653   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4654   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4655     return N2;
4656
4657   return SDValue();
4658 }
4659
4660 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4661   SDValue N0 = N->getOperand(0);
4662   SDValue N1 = N->getOperand(1);
4663   SDValue N2 = N->getOperand(2);
4664   SDValue N3 = N->getOperand(3);
4665   SDValue N4 = N->getOperand(4);
4666   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4667
4668   // fold select_cc lhs, rhs, x, x, cc -> x
4669   if (N2 == N3)
4670     return N2;
4671
4672   // Determine if the condition we're dealing with is constant
4673   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4674                               N0, N1, CC, SDLoc(N), false);
4675   if (SCC.getNode()) {
4676     AddToWorkList(SCC.getNode());
4677
4678     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4679       if (!SCCC->isNullValue())
4680         return N2;    // cond always true -> true val
4681       else
4682         return N3;    // cond always false -> false val
4683     }
4684
4685     // Fold to a simpler select_cc
4686     if (SCC.getOpcode() == ISD::SETCC)
4687       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4688                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4689                          SCC.getOperand(2));
4690   }
4691
4692   // If we can fold this based on the true/false value, do so.
4693   if (SimplifySelectOps(N, N2, N3))
4694     return SDValue(N, 0);  // Don't revisit N.
4695
4696   // fold select_cc into other things, such as min/max/abs
4697   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4698 }
4699
4700 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4701   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4702                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4703                        SDLoc(N));
4704 }
4705
4706 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4707 // dag node into a ConstantSDNode or a build_vector of constants.
4708 // This function is called by the DAGCombiner when visiting sext/zext/aext
4709 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4710 // Vector extends are not folded if operations are legal; this is to
4711 // avoid introducing illegal build_vector dag nodes.
4712 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4713                                          SelectionDAG &DAG, bool LegalTypes,
4714                                          bool LegalOperations) {
4715   unsigned Opcode = N->getOpcode();
4716   SDValue N0 = N->getOperand(0);
4717   EVT VT = N->getValueType(0);
4718
4719   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4720          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4721
4722   // fold (sext c1) -> c1
4723   // fold (zext c1) -> c1
4724   // fold (aext c1) -> c1
4725   if (isa<ConstantSDNode>(N0))
4726     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4727
4728   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4729   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4730   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4731   EVT SVT = VT.getScalarType();
4732   if (!(VT.isVector() &&
4733       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4734       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4735     return nullptr;
4736
4737   // We can fold this node into a build_vector.
4738   unsigned VTBits = SVT.getSizeInBits();
4739   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4740   unsigned ShAmt = VTBits - EVTBits;
4741   SmallVector<SDValue, 8> Elts;
4742   unsigned NumElts = N0->getNumOperands();
4743   SDLoc DL(N);
4744
4745   for (unsigned i=0; i != NumElts; ++i) {
4746     SDValue Op = N0->getOperand(i);
4747     if (Op->getOpcode() == ISD::UNDEF) {
4748       Elts.push_back(DAG.getUNDEF(SVT));
4749       continue;
4750     }
4751
4752     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4753     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4754     if (Opcode == ISD::SIGN_EXTEND)
4755       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4756                                      SVT));
4757     else
4758       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4759                                      SVT));
4760   }
4761
4762   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4763 }
4764
4765 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4766 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4767 // transformation. Returns true if extension are possible and the above
4768 // mentioned transformation is profitable.
4769 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4770                                     unsigned ExtOpc,
4771                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4772                                     const TargetLowering &TLI) {
4773   bool HasCopyToRegUses = false;
4774   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4775   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4776                             UE = N0.getNode()->use_end();
4777        UI != UE; ++UI) {
4778     SDNode *User = *UI;
4779     if (User == N)
4780       continue;
4781     if (UI.getUse().getResNo() != N0.getResNo())
4782       continue;
4783     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4784     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4785       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4786       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4787         // Sign bits will be lost after a zext.
4788         return false;
4789       bool Add = false;
4790       for (unsigned i = 0; i != 2; ++i) {
4791         SDValue UseOp = User->getOperand(i);
4792         if (UseOp == N0)
4793           continue;
4794         if (!isa<ConstantSDNode>(UseOp))
4795           return false;
4796         Add = true;
4797       }
4798       if (Add)
4799         ExtendNodes.push_back(User);
4800       continue;
4801     }
4802     // If truncates aren't free and there are users we can't
4803     // extend, it isn't worthwhile.
4804     if (!isTruncFree)
4805       return false;
4806     // Remember if this value is live-out.
4807     if (User->getOpcode() == ISD::CopyToReg)
4808       HasCopyToRegUses = true;
4809   }
4810
4811   if (HasCopyToRegUses) {
4812     bool BothLiveOut = false;
4813     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4814          UI != UE; ++UI) {
4815       SDUse &Use = UI.getUse();
4816       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4817         BothLiveOut = true;
4818         break;
4819       }
4820     }
4821     if (BothLiveOut)
4822       // Both unextended and extended values are live out. There had better be
4823       // a good reason for the transformation.
4824       return ExtendNodes.size();
4825   }
4826   return true;
4827 }
4828
4829 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4830                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4831                                   ISD::NodeType ExtType) {
4832   // Extend SetCC uses if necessary.
4833   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4834     SDNode *SetCC = SetCCs[i];
4835     SmallVector<SDValue, 4> Ops;
4836
4837     for (unsigned j = 0; j != 2; ++j) {
4838       SDValue SOp = SetCC->getOperand(j);
4839       if (SOp == Trunc)
4840         Ops.push_back(ExtLoad);
4841       else
4842         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4843     }
4844
4845     Ops.push_back(SetCC->getOperand(2));
4846     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4847   }
4848 }
4849
4850 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4851   SDValue N0 = N->getOperand(0);
4852   EVT VT = N->getValueType(0);
4853
4854   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4855                                               LegalOperations))
4856     return SDValue(Res, 0);
4857
4858   // fold (sext (sext x)) -> (sext x)
4859   // fold (sext (aext x)) -> (sext x)
4860   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4861     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4862                        N0.getOperand(0));
4863
4864   if (N0.getOpcode() == ISD::TRUNCATE) {
4865     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4866     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4867     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4868     if (NarrowLoad.getNode()) {
4869       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4870       if (NarrowLoad.getNode() != N0.getNode()) {
4871         CombineTo(N0.getNode(), NarrowLoad);
4872         // CombineTo deleted the truncate, if needed, but not what's under it.
4873         AddToWorkList(oye);
4874       }
4875       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4876     }
4877
4878     // See if the value being truncated is already sign extended.  If so, just
4879     // eliminate the trunc/sext pair.
4880     SDValue Op = N0.getOperand(0);
4881     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4882     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4883     unsigned DestBits = VT.getScalarType().getSizeInBits();
4884     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4885
4886     if (OpBits == DestBits) {
4887       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4888       // bits, it is already ready.
4889       if (NumSignBits > DestBits-MidBits)
4890         return Op;
4891     } else if (OpBits < DestBits) {
4892       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4893       // bits, just sext from i32.
4894       if (NumSignBits > OpBits-MidBits)
4895         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4896     } else {
4897       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4898       // bits, just truncate to i32.
4899       if (NumSignBits > OpBits-MidBits)
4900         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4901     }
4902
4903     // fold (sext (truncate x)) -> (sextinreg x).
4904     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4905                                                  N0.getValueType())) {
4906       if (OpBits < DestBits)
4907         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4908       else if (OpBits > DestBits)
4909         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4910       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4911                          DAG.getValueType(N0.getValueType()));
4912     }
4913   }
4914
4915   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4916   // None of the supported targets knows how to perform load and sign extend
4917   // on vectors in one instruction.  We only perform this transformation on
4918   // scalars.
4919   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4920       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4921       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4922        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4923     bool DoXform = true;
4924     SmallVector<SDNode*, 4> SetCCs;
4925     if (!N0.hasOneUse())
4926       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4927     if (DoXform) {
4928       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4929       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4930                                        LN0->getChain(),
4931                                        LN0->getBasePtr(), N0.getValueType(),
4932                                        LN0->getMemOperand());
4933       CombineTo(N, ExtLoad);
4934       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4935                                   N0.getValueType(), ExtLoad);
4936       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4937       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4938                       ISD::SIGN_EXTEND);
4939       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4940     }
4941   }
4942
4943   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4944   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4945   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4946       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4947     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4948     EVT MemVT = LN0->getMemoryVT();
4949     if ((!LegalOperations && !LN0->isVolatile()) ||
4950         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4951       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4952                                        LN0->getChain(),
4953                                        LN0->getBasePtr(), MemVT,
4954                                        LN0->getMemOperand());
4955       CombineTo(N, ExtLoad);
4956       CombineTo(N0.getNode(),
4957                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4958                             N0.getValueType(), ExtLoad),
4959                 ExtLoad.getValue(1));
4960       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4961     }
4962   }
4963
4964   // fold (sext (and/or/xor (load x), cst)) ->
4965   //      (and/or/xor (sextload x), (sext cst))
4966   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4967        N0.getOpcode() == ISD::XOR) &&
4968       isa<LoadSDNode>(N0.getOperand(0)) &&
4969       N0.getOperand(1).getOpcode() == ISD::Constant &&
4970       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4971       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4972     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4973     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4974       bool DoXform = true;
4975       SmallVector<SDNode*, 4> SetCCs;
4976       if (!N0.hasOneUse())
4977         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4978                                           SetCCs, TLI);
4979       if (DoXform) {
4980         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4981                                          LN0->getChain(), LN0->getBasePtr(),
4982                                          LN0->getMemoryVT(),
4983                                          LN0->getMemOperand());
4984         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4985         Mask = Mask.sext(VT.getSizeInBits());
4986         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4987                                   ExtLoad, DAG.getConstant(Mask, VT));
4988         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4989                                     SDLoc(N0.getOperand(0)),
4990                                     N0.getOperand(0).getValueType(), ExtLoad);
4991         CombineTo(N, And);
4992         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4993         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4994                         ISD::SIGN_EXTEND);
4995         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4996       }
4997     }
4998   }
4999
5000   if (N0.getOpcode() == ISD::SETCC) {
5001     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5002     // Only do this before legalize for now.
5003     if (VT.isVector() && !LegalOperations &&
5004         TLI.getBooleanContents(true) ==
5005           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5006       EVT N0VT = N0.getOperand(0).getValueType();
5007       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5008       // of the same size as the compared operands. Only optimize sext(setcc())
5009       // if this is the case.
5010       EVT SVT = getSetCCResultType(N0VT);
5011
5012       // We know that the # elements of the results is the same as the
5013       // # elements of the compare (and the # elements of the compare result
5014       // for that matter).  Check to see that they are the same size.  If so,
5015       // we know that the element size of the sext'd result matches the
5016       // element size of the compare operands.
5017       if (VT.getSizeInBits() == SVT.getSizeInBits())
5018         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5019                              N0.getOperand(1),
5020                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5021
5022       // If the desired elements are smaller or larger than the source
5023       // elements we can use a matching integer vector type and then
5024       // truncate/sign extend
5025       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5026       if (SVT == MatchingVectorType) {
5027         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5028                                N0.getOperand(0), N0.getOperand(1),
5029                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5030         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5031       }
5032     }
5033
5034     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5035     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5036     SDValue NegOne =
5037       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5038     SDValue SCC =
5039       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5040                        NegOne, DAG.getConstant(0, VT),
5041                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5042     if (SCC.getNode()) return SCC;
5043
5044     if (!VT.isVector()) {
5045       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5046       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5047         SDLoc DL(N);
5048         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5049         SDValue SetCC = DAG.getSetCC(DL,
5050                                      SetCCVT,
5051                                      N0.getOperand(0), N0.getOperand(1), CC);
5052         EVT SelectVT = getSetCCResultType(VT);
5053         return DAG.getSelect(DL, VT,
5054                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5055                              NegOne, DAG.getConstant(0, VT));
5056
5057       }
5058     }
5059   }
5060
5061   // fold (sext x) -> (zext x) if the sign bit is known zero.
5062   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5063       DAG.SignBitIsZero(N0))
5064     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5065
5066   return SDValue();
5067 }
5068
5069 // isTruncateOf - If N is a truncate of some other value, return true, record
5070 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5071 // This function computes KnownZero to avoid a duplicated call to
5072 // ComputeMaskedBits in the caller.
5073 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5074                          APInt &KnownZero) {
5075   APInt KnownOne;
5076   if (N->getOpcode() == ISD::TRUNCATE) {
5077     Op = N->getOperand(0);
5078     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5079     return true;
5080   }
5081
5082   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5083       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5084     return false;
5085
5086   SDValue Op0 = N->getOperand(0);
5087   SDValue Op1 = N->getOperand(1);
5088   assert(Op0.getValueType() == Op1.getValueType());
5089
5090   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5091   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5092   if (COp0 && COp0->isNullValue())
5093     Op = Op1;
5094   else if (COp1 && COp1->isNullValue())
5095     Op = Op0;
5096   else
5097     return false;
5098
5099   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5100
5101   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5102     return false;
5103
5104   return true;
5105 }
5106
5107 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5108   SDValue N0 = N->getOperand(0);
5109   EVT VT = N->getValueType(0);
5110
5111   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5112                                               LegalOperations))
5113     return SDValue(Res, 0);
5114
5115   // fold (zext (zext x)) -> (zext x)
5116   // fold (zext (aext x)) -> (zext x)
5117   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5118     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5119                        N0.getOperand(0));
5120
5121   // fold (zext (truncate x)) -> (zext x) or
5122   //      (zext (truncate x)) -> (truncate x)
5123   // This is valid when the truncated bits of x are already zero.
5124   // FIXME: We should extend this to work for vectors too.
5125   SDValue Op;
5126   APInt KnownZero;
5127   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5128     APInt TruncatedBits =
5129       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5130       APInt(Op.getValueSizeInBits(), 0) :
5131       APInt::getBitsSet(Op.getValueSizeInBits(),
5132                         N0.getValueSizeInBits(),
5133                         std::min(Op.getValueSizeInBits(),
5134                                  VT.getSizeInBits()));
5135     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5136       if (VT.bitsGT(Op.getValueType()))
5137         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5138       if (VT.bitsLT(Op.getValueType()))
5139         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5140
5141       return Op;
5142     }
5143   }
5144
5145   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5146   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5147   if (N0.getOpcode() == ISD::TRUNCATE) {
5148     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5149     if (NarrowLoad.getNode()) {
5150       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5151       if (NarrowLoad.getNode() != N0.getNode()) {
5152         CombineTo(N0.getNode(), NarrowLoad);
5153         // CombineTo deleted the truncate, if needed, but not what's under it.
5154         AddToWorkList(oye);
5155       }
5156       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5157     }
5158   }
5159
5160   // fold (zext (truncate x)) -> (and x, mask)
5161   if (N0.getOpcode() == ISD::TRUNCATE &&
5162       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5163
5164     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5165     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5166     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5167     if (NarrowLoad.getNode()) {
5168       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5169       if (NarrowLoad.getNode() != N0.getNode()) {
5170         CombineTo(N0.getNode(), NarrowLoad);
5171         // CombineTo deleted the truncate, if needed, but not what's under it.
5172         AddToWorkList(oye);
5173       }
5174       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5175     }
5176
5177     SDValue Op = N0.getOperand(0);
5178     if (Op.getValueType().bitsLT(VT)) {
5179       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5180       AddToWorkList(Op.getNode());
5181     } else if (Op.getValueType().bitsGT(VT)) {
5182       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5183       AddToWorkList(Op.getNode());
5184     }
5185     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5186                                   N0.getValueType().getScalarType());
5187   }
5188
5189   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5190   // if either of the casts is not free.
5191   if (N0.getOpcode() == ISD::AND &&
5192       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5193       N0.getOperand(1).getOpcode() == ISD::Constant &&
5194       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5195                            N0.getValueType()) ||
5196        !TLI.isZExtFree(N0.getValueType(), VT))) {
5197     SDValue X = N0.getOperand(0).getOperand(0);
5198     if (X.getValueType().bitsLT(VT)) {
5199       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5200     } else if (X.getValueType().bitsGT(VT)) {
5201       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5202     }
5203     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5204     Mask = Mask.zext(VT.getSizeInBits());
5205     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5206                        X, DAG.getConstant(Mask, VT));
5207   }
5208
5209   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5210   // None of the supported targets knows how to perform load and vector_zext
5211   // on vectors in one instruction.  We only perform this transformation on
5212   // scalars.
5213   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5214       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5215       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5216        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5217     bool DoXform = true;
5218     SmallVector<SDNode*, 4> SetCCs;
5219     if (!N0.hasOneUse())
5220       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5221     if (DoXform) {
5222       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5223       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5224                                        LN0->getChain(),
5225                                        LN0->getBasePtr(), N0.getValueType(),
5226                                        LN0->getMemOperand());
5227       CombineTo(N, ExtLoad);
5228       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5229                                   N0.getValueType(), ExtLoad);
5230       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5231
5232       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5233                       ISD::ZERO_EXTEND);
5234       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5235     }
5236   }
5237
5238   // fold (zext (and/or/xor (load x), cst)) ->
5239   //      (and/or/xor (zextload x), (zext cst))
5240   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5241        N0.getOpcode() == ISD::XOR) &&
5242       isa<LoadSDNode>(N0.getOperand(0)) &&
5243       N0.getOperand(1).getOpcode() == ISD::Constant &&
5244       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5245       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5246     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5247     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5248       bool DoXform = true;
5249       SmallVector<SDNode*, 4> SetCCs;
5250       if (!N0.hasOneUse())
5251         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5252                                           SetCCs, TLI);
5253       if (DoXform) {
5254         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5255                                          LN0->getChain(), LN0->getBasePtr(),
5256                                          LN0->getMemoryVT(),
5257                                          LN0->getMemOperand());
5258         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5259         Mask = Mask.zext(VT.getSizeInBits());
5260         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5261                                   ExtLoad, DAG.getConstant(Mask, VT));
5262         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5263                                     SDLoc(N0.getOperand(0)),
5264                                     N0.getOperand(0).getValueType(), ExtLoad);
5265         CombineTo(N, And);
5266         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
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
5274   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5275   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5276   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5277       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5278     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5279     EVT MemVT = LN0->getMemoryVT();
5280     if ((!LegalOperations && !LN0->isVolatile()) ||
5281         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5282       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5283                                        LN0->getChain(),
5284                                        LN0->getBasePtr(), MemVT,
5285                                        LN0->getMemOperand());
5286       CombineTo(N, ExtLoad);
5287       CombineTo(N0.getNode(),
5288                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5289                             ExtLoad),
5290                 ExtLoad.getValue(1));
5291       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5292     }
5293   }
5294
5295   if (N0.getOpcode() == ISD::SETCC) {
5296     if (!LegalOperations && VT.isVector() &&
5297         N0.getValueType().getVectorElementType() == MVT::i1) {
5298       EVT N0VT = N0.getOperand(0).getValueType();
5299       if (getSetCCResultType(N0VT) == N0.getValueType())
5300         return SDValue();
5301
5302       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5303       // Only do this before legalize for now.
5304       EVT EltVT = VT.getVectorElementType();
5305       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5306                                     DAG.getConstant(1, EltVT));
5307       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5308         // We know that the # elements of the results is the same as the
5309         // # elements of the compare (and the # elements of the compare result
5310         // for that matter).  Check to see that they are the same size.  If so,
5311         // we know that the element size of the sext'd result matches the
5312         // element size of the compare operands.
5313         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5314                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5315                                          N0.getOperand(1),
5316                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5317                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5318                                        OneOps));
5319
5320       // If the desired elements are smaller or larger than the source
5321       // elements we can use a matching integer vector type and then
5322       // truncate/sign extend
5323       EVT MatchingElementType =
5324         EVT::getIntegerVT(*DAG.getContext(),
5325                           N0VT.getScalarType().getSizeInBits());
5326       EVT MatchingVectorType =
5327         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5328                          N0VT.getVectorNumElements());
5329       SDValue VsetCC =
5330         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5331                       N0.getOperand(1),
5332                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5333       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5334                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5335                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5336     }
5337
5338     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5339     SDValue SCC =
5340       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5341                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5342                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5343     if (SCC.getNode()) return SCC;
5344   }
5345
5346   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5347   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5348       isa<ConstantSDNode>(N0.getOperand(1)) &&
5349       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5350       N0.hasOneUse()) {
5351     SDValue ShAmt = N0.getOperand(1);
5352     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5353     if (N0.getOpcode() == ISD::SHL) {
5354       SDValue InnerZExt = N0.getOperand(0);
5355       // If the original shl may be shifting out bits, do not perform this
5356       // transformation.
5357       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5358         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5359       if (ShAmtVal > KnownZeroBits)
5360         return SDValue();
5361     }
5362
5363     SDLoc DL(N);
5364
5365     // Ensure that the shift amount is wide enough for the shifted value.
5366     if (VT.getSizeInBits() >= 256)
5367       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5368
5369     return DAG.getNode(N0.getOpcode(), DL, VT,
5370                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5371                        ShAmt);
5372   }
5373
5374   return SDValue();
5375 }
5376
5377 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5378   SDValue N0 = N->getOperand(0);
5379   EVT VT = N->getValueType(0);
5380
5381   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5382                                               LegalOperations))
5383     return SDValue(Res, 0);
5384
5385   // fold (aext (aext x)) -> (aext x)
5386   // fold (aext (zext x)) -> (zext x)
5387   // fold (aext (sext x)) -> (sext x)
5388   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5389       N0.getOpcode() == ISD::ZERO_EXTEND ||
5390       N0.getOpcode() == ISD::SIGN_EXTEND)
5391     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5392
5393   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5394   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5395   if (N0.getOpcode() == ISD::TRUNCATE) {
5396     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5397     if (NarrowLoad.getNode()) {
5398       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5399       if (NarrowLoad.getNode() != N0.getNode()) {
5400         CombineTo(N0.getNode(), NarrowLoad);
5401         // CombineTo deleted the truncate, if needed, but not what's under it.
5402         AddToWorkList(oye);
5403       }
5404       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5405     }
5406   }
5407
5408   // fold (aext (truncate x))
5409   if (N0.getOpcode() == ISD::TRUNCATE) {
5410     SDValue TruncOp = N0.getOperand(0);
5411     if (TruncOp.getValueType() == VT)
5412       return TruncOp; // x iff x size == zext size.
5413     if (TruncOp.getValueType().bitsGT(VT))
5414       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5415     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5416   }
5417
5418   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5419   // if the trunc is not free.
5420   if (N0.getOpcode() == ISD::AND &&
5421       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5422       N0.getOperand(1).getOpcode() == ISD::Constant &&
5423       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5424                           N0.getValueType())) {
5425     SDValue X = N0.getOperand(0).getOperand(0);
5426     if (X.getValueType().bitsLT(VT)) {
5427       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5428     } else if (X.getValueType().bitsGT(VT)) {
5429       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5430     }
5431     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5432     Mask = Mask.zext(VT.getSizeInBits());
5433     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5434                        X, DAG.getConstant(Mask, VT));
5435   }
5436
5437   // fold (aext (load x)) -> (aext (truncate (extload x)))
5438   // None of the supported targets knows how to perform load and any_ext
5439   // on vectors in one instruction.  We only perform this transformation on
5440   // scalars.
5441   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5442       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5443       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5444        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5445     bool DoXform = true;
5446     SmallVector<SDNode*, 4> SetCCs;
5447     if (!N0.hasOneUse())
5448       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5449     if (DoXform) {
5450       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5451       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5452                                        LN0->getChain(),
5453                                        LN0->getBasePtr(), N0.getValueType(),
5454                                        LN0->getMemOperand());
5455       CombineTo(N, ExtLoad);
5456       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5457                                   N0.getValueType(), ExtLoad);
5458       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5459       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5460                       ISD::ANY_EXTEND);
5461       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5462     }
5463   }
5464
5465   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5466   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5467   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5468   if (N0.getOpcode() == ISD::LOAD &&
5469       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5470       N0.hasOneUse()) {
5471     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472     ISD::LoadExtType ExtType = LN0->getExtensionType();
5473     EVT MemVT = LN0->getMemoryVT();
5474     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5475       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5476                                        VT, LN0->getChain(), LN0->getBasePtr(),
5477                                        MemVT, LN0->getMemOperand());
5478       CombineTo(N, ExtLoad);
5479       CombineTo(N0.getNode(),
5480                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5481                             N0.getValueType(), ExtLoad),
5482                 ExtLoad.getValue(1));
5483       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5484     }
5485   }
5486
5487   if (N0.getOpcode() == ISD::SETCC) {
5488     // For vectors:
5489     // aext(setcc) -> vsetcc
5490     // aext(setcc) -> truncate(vsetcc)
5491     // aext(setcc) -> aext(vsetcc)
5492     // Only do this before legalize for now.
5493     if (VT.isVector() && !LegalOperations) {
5494       EVT N0VT = N0.getOperand(0).getValueType();
5495         // We know that the # elements of the results is the same as the
5496         // # elements of the compare (and the # elements of the compare result
5497         // for that matter).  Check to see that they are the same size.  If so,
5498         // we know that the element size of the sext'd result matches the
5499         // element size of the compare operands.
5500       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5501         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5502                              N0.getOperand(1),
5503                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5504       // If the desired elements are smaller or larger than the source
5505       // elements we can use a matching integer vector type and then
5506       // truncate/any extend
5507       else {
5508         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5509         SDValue VsetCC =
5510           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5511                         N0.getOperand(1),
5512                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5513         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5514       }
5515     }
5516
5517     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5518     SDValue SCC =
5519       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5520                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5521                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5522     if (SCC.getNode())
5523       return SCC;
5524   }
5525
5526   return SDValue();
5527 }
5528
5529 /// GetDemandedBits - See if the specified operand can be simplified with the
5530 /// knowledge that only the bits specified by Mask are used.  If so, return the
5531 /// simpler operand, otherwise return a null SDValue.
5532 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5533   switch (V.getOpcode()) {
5534   default: break;
5535   case ISD::Constant: {
5536     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5537     assert(CV && "Const value should be ConstSDNode.");
5538     const APInt &CVal = CV->getAPIntValue();
5539     APInt NewVal = CVal & Mask;
5540     if (NewVal != CVal)
5541       return DAG.getConstant(NewVal, V.getValueType());
5542     break;
5543   }
5544   case ISD::OR:
5545   case ISD::XOR:
5546     // If the LHS or RHS don't contribute bits to the or, drop them.
5547     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5548       return V.getOperand(1);
5549     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5550       return V.getOperand(0);
5551     break;
5552   case ISD::SRL:
5553     // Only look at single-use SRLs.
5554     if (!V.getNode()->hasOneUse())
5555       break;
5556     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5557       // See if we can recursively simplify the LHS.
5558       unsigned Amt = RHSC->getZExtValue();
5559
5560       // Watch out for shift count overflow though.
5561       if (Amt >= Mask.getBitWidth()) break;
5562       APInt NewMask = Mask << Amt;
5563       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5564       if (SimplifyLHS.getNode())
5565         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5566                            SimplifyLHS, V.getOperand(1));
5567     }
5568   }
5569   return SDValue();
5570 }
5571
5572 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5573 /// bits and then truncated to a narrower type and where N is a multiple
5574 /// of number of bits of the narrower type, transform it to a narrower load
5575 /// from address + N / num of bits of new type. If the result is to be
5576 /// extended, also fold the extension to form a extending load.
5577 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5578   unsigned Opc = N->getOpcode();
5579
5580   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5581   SDValue N0 = N->getOperand(0);
5582   EVT VT = N->getValueType(0);
5583   EVT ExtVT = VT;
5584
5585   // This transformation isn't valid for vector loads.
5586   if (VT.isVector())
5587     return SDValue();
5588
5589   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5590   // extended to VT.
5591   if (Opc == ISD::SIGN_EXTEND_INREG) {
5592     ExtType = ISD::SEXTLOAD;
5593     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5594   } else if (Opc == ISD::SRL) {
5595     // Another special-case: SRL is basically zero-extending a narrower value.
5596     ExtType = ISD::ZEXTLOAD;
5597     N0 = SDValue(N, 0);
5598     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5599     if (!N01) return SDValue();
5600     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5601                               VT.getSizeInBits() - N01->getZExtValue());
5602   }
5603   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5604     return SDValue();
5605
5606   unsigned EVTBits = ExtVT.getSizeInBits();
5607
5608   // Do not generate loads of non-round integer types since these can
5609   // be expensive (and would be wrong if the type is not byte sized).
5610   if (!ExtVT.isRound())
5611     return SDValue();
5612
5613   unsigned ShAmt = 0;
5614   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5615     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5616       ShAmt = N01->getZExtValue();
5617       // Is the shift amount a multiple of size of VT?
5618       if ((ShAmt & (EVTBits-1)) == 0) {
5619         N0 = N0.getOperand(0);
5620         // Is the load width a multiple of size of VT?
5621         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5622           return SDValue();
5623       }
5624
5625       // At this point, we must have a load or else we can't do the transform.
5626       if (!isa<LoadSDNode>(N0)) return SDValue();
5627
5628       // Because a SRL must be assumed to *need* to zero-extend the high bits
5629       // (as opposed to anyext the high bits), we can't combine the zextload
5630       // lowering of SRL and an sextload.
5631       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5632         return SDValue();
5633
5634       // If the shift amount is larger than the input type then we're not
5635       // accessing any of the loaded bytes.  If the load was a zextload/extload
5636       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5637       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5638         return SDValue();
5639     }
5640   }
5641
5642   // If the load is shifted left (and the result isn't shifted back right),
5643   // we can fold the truncate through the shift.
5644   unsigned ShLeftAmt = 0;
5645   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5646       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5647     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5648       ShLeftAmt = N01->getZExtValue();
5649       N0 = N0.getOperand(0);
5650     }
5651   }
5652
5653   // If we haven't found a load, we can't narrow it.  Don't transform one with
5654   // multiple uses, this would require adding a new load.
5655   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5656     return SDValue();
5657
5658   // Don't change the width of a volatile load.
5659   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5660   if (LN0->isVolatile())
5661     return SDValue();
5662
5663   // Verify that we are actually reducing a load width here.
5664   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5665     return SDValue();
5666
5667   // For the transform to be legal, the load must produce only two values
5668   // (the value loaded and the chain).  Don't transform a pre-increment
5669   // load, for example, which produces an extra value.  Otherwise the
5670   // transformation is not equivalent, and the downstream logic to replace
5671   // uses gets things wrong.
5672   if (LN0->getNumValues() > 2)
5673     return SDValue();
5674
5675   // If the load that we're shrinking is an extload and we're not just
5676   // discarding the extension we can't simply shrink the load. Bail.
5677   // TODO: It would be possible to merge the extensions in some cases.
5678   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5679       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5680     return SDValue();
5681
5682   EVT PtrType = N0.getOperand(1).getValueType();
5683
5684   if (PtrType == MVT::Untyped || PtrType.isExtended())
5685     // It's not possible to generate a constant of extended or untyped type.
5686     return SDValue();
5687
5688   // For big endian targets, we need to adjust the offset to the pointer to
5689   // load the correct bytes.
5690   if (TLI.isBigEndian()) {
5691     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5692     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5693     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5694   }
5695
5696   uint64_t PtrOff = ShAmt / 8;
5697   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5698   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5699                                PtrType, LN0->getBasePtr(),
5700                                DAG.getConstant(PtrOff, PtrType));
5701   AddToWorkList(NewPtr.getNode());
5702
5703   SDValue Load;
5704   if (ExtType == ISD::NON_EXTLOAD)
5705     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5706                         LN0->getPointerInfo().getWithOffset(PtrOff),
5707                         LN0->isVolatile(), LN0->isNonTemporal(),
5708                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5709   else
5710     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5711                           LN0->getPointerInfo().getWithOffset(PtrOff),
5712                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5713                           NewAlign, LN0->getTBAAInfo());
5714
5715   // Replace the old load's chain with the new load's chain.
5716   WorkListRemover DeadNodes(*this);
5717   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5718
5719   // Shift the result left, if we've swallowed a left shift.
5720   SDValue Result = Load;
5721   if (ShLeftAmt != 0) {
5722     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5723     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5724       ShImmTy = VT;
5725     // If the shift amount is as large as the result size (but, presumably,
5726     // no larger than the source) then the useful bits of the result are
5727     // zero; we can't simply return the shortened shift, because the result
5728     // of that operation is undefined.
5729     if (ShLeftAmt >= VT.getSizeInBits())
5730       Result = DAG.getConstant(0, VT);
5731     else
5732       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5733                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5734   }
5735
5736   // Return the new loaded value.
5737   return Result;
5738 }
5739
5740 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5741   SDValue N0 = N->getOperand(0);
5742   SDValue N1 = N->getOperand(1);
5743   EVT VT = N->getValueType(0);
5744   EVT EVT = cast<VTSDNode>(N1)->getVT();
5745   unsigned VTBits = VT.getScalarType().getSizeInBits();
5746   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5747
5748   // fold (sext_in_reg c1) -> c1
5749   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5750     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5751
5752   // If the input is already sign extended, just drop the extension.
5753   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5754     return N0;
5755
5756   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5757   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5758       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5759     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5760                        N0.getOperand(0), N1);
5761
5762   // fold (sext_in_reg (sext x)) -> (sext x)
5763   // fold (sext_in_reg (aext x)) -> (sext x)
5764   // if x is small enough.
5765   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5766     SDValue N00 = N0.getOperand(0);
5767     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5768         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5769       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5770   }
5771
5772   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5773   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5774     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5775
5776   // fold operands of sext_in_reg based on knowledge that the top bits are not
5777   // demanded.
5778   if (SimplifyDemandedBits(SDValue(N, 0)))
5779     return SDValue(N, 0);
5780
5781   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5782   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5783   SDValue NarrowLoad = ReduceLoadWidth(N);
5784   if (NarrowLoad.getNode())
5785     return NarrowLoad;
5786
5787   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5788   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5789   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5790   if (N0.getOpcode() == ISD::SRL) {
5791     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5792       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5793         // We can turn this into an SRA iff the input to the SRL is already sign
5794         // extended enough.
5795         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5796         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5797           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5798                              N0.getOperand(0), N0.getOperand(1));
5799       }
5800   }
5801
5802   // fold (sext_inreg (extload x)) -> (sextload x)
5803   if (ISD::isEXTLoad(N0.getNode()) &&
5804       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5805       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5806       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5807        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5808     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5809     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5810                                      LN0->getChain(),
5811                                      LN0->getBasePtr(), EVT,
5812                                      LN0->getMemOperand());
5813     CombineTo(N, ExtLoad);
5814     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5815     AddToWorkList(ExtLoad.getNode());
5816     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5817   }
5818   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5819   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5820       N0.hasOneUse() &&
5821       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5822       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5823        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5824     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5825     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5826                                      LN0->getChain(),
5827                                      LN0->getBasePtr(), EVT,
5828                                      LN0->getMemOperand());
5829     CombineTo(N, ExtLoad);
5830     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5831     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5832   }
5833
5834   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5835   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5836     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5837                                        N0.getOperand(1), false);
5838     if (BSwap.getNode())
5839       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5840                          BSwap, N1);
5841   }
5842
5843   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5844   // into a build_vector.
5845   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5846     SmallVector<SDValue, 8> Elts;
5847     unsigned NumElts = N0->getNumOperands();
5848     unsigned ShAmt = VTBits - EVTBits;
5849
5850     for (unsigned i = 0; i != NumElts; ++i) {
5851       SDValue Op = N0->getOperand(i);
5852       if (Op->getOpcode() == ISD::UNDEF) {
5853         Elts.push_back(Op);
5854         continue;
5855       }
5856
5857       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5858       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5859       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5860                                      Op.getValueType()));
5861     }
5862
5863     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5864   }
5865
5866   return SDValue();
5867 }
5868
5869 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5870   SDValue N0 = N->getOperand(0);
5871   EVT VT = N->getValueType(0);
5872   bool isLE = TLI.isLittleEndian();
5873
5874   // noop truncate
5875   if (N0.getValueType() == N->getValueType(0))
5876     return N0;
5877   // fold (truncate c1) -> c1
5878   if (isa<ConstantSDNode>(N0))
5879     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5880   // fold (truncate (truncate x)) -> (truncate x)
5881   if (N0.getOpcode() == ISD::TRUNCATE)
5882     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5883   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5884   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5885       N0.getOpcode() == ISD::SIGN_EXTEND ||
5886       N0.getOpcode() == ISD::ANY_EXTEND) {
5887     if (N0.getOperand(0).getValueType().bitsLT(VT))
5888       // if the source is smaller than the dest, we still need an extend
5889       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5890                          N0.getOperand(0));
5891     if (N0.getOperand(0).getValueType().bitsGT(VT))
5892       // if the source is larger than the dest, than we just need the truncate
5893       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5894     // if the source and dest are the same type, we can drop both the extend
5895     // and the truncate.
5896     return N0.getOperand(0);
5897   }
5898
5899   // Fold extract-and-trunc into a narrow extract. For example:
5900   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5901   //   i32 y = TRUNCATE(i64 x)
5902   //        -- becomes --
5903   //   v16i8 b = BITCAST (v2i64 val)
5904   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5905   //
5906   // Note: We only run this optimization after type legalization (which often
5907   // creates this pattern) and before operation legalization after which
5908   // we need to be more careful about the vector instructions that we generate.
5909   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5910       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5911
5912     EVT VecTy = N0.getOperand(0).getValueType();
5913     EVT ExTy = N0.getValueType();
5914     EVT TrTy = N->getValueType(0);
5915
5916     unsigned NumElem = VecTy.getVectorNumElements();
5917     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5918
5919     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5920     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5921
5922     SDValue EltNo = N0->getOperand(1);
5923     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5924       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5925       EVT IndexTy = TLI.getVectorIdxTy();
5926       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5927
5928       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5929                               NVT, N0.getOperand(0));
5930
5931       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5932                          SDLoc(N), TrTy, V,
5933                          DAG.getConstant(Index, IndexTy));
5934     }
5935   }
5936
5937   // Fold a series of buildvector, bitcast, and truncate if possible.
5938   // For example fold
5939   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5940   //   (2xi32 (buildvector x, y)).
5941   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5942       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5943       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5944       N0.getOperand(0).hasOneUse()) {
5945
5946     SDValue BuildVect = N0.getOperand(0);
5947     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5948     EVT TruncVecEltTy = VT.getVectorElementType();
5949
5950     // Check that the element types match.
5951     if (BuildVectEltTy == TruncVecEltTy) {
5952       // Now we only need to compute the offset of the truncated elements.
5953       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5954       unsigned TruncVecNumElts = VT.getVectorNumElements();
5955       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5956
5957       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5958              "Invalid number of elements");
5959
5960       SmallVector<SDValue, 8> Opnds;
5961       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5962         Opnds.push_back(BuildVect.getOperand(i));
5963
5964       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
5965     }
5966   }
5967
5968   // See if we can simplify the input to this truncate through knowledge that
5969   // only the low bits are being used.
5970   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5971   // Currently we only perform this optimization on scalars because vectors
5972   // may have different active low bits.
5973   if (!VT.isVector()) {
5974     SDValue Shorter =
5975       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5976                                                VT.getSizeInBits()));
5977     if (Shorter.getNode())
5978       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5979   }
5980   // fold (truncate (load x)) -> (smaller load x)
5981   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5982   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5983     SDValue Reduced = ReduceLoadWidth(N);
5984     if (Reduced.getNode())
5985       return Reduced;
5986     // Handle the case where the load remains an extending load even
5987     // after truncation.
5988     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5989       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5990       if (!LN0->isVolatile() &&
5991           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5992         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5993                                          VT, LN0->getChain(), LN0->getBasePtr(),
5994                                          LN0->getMemoryVT(),
5995                                          LN0->getMemOperand());
5996         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5997         return NewLoad;
5998       }
5999     }
6000   }
6001   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6002   // where ... are all 'undef'.
6003   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6004     SmallVector<EVT, 8> VTs;
6005     SDValue V;
6006     unsigned Idx = 0;
6007     unsigned NumDefs = 0;
6008
6009     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6010       SDValue X = N0.getOperand(i);
6011       if (X.getOpcode() != ISD::UNDEF) {
6012         V = X;
6013         Idx = i;
6014         NumDefs++;
6015       }
6016       // Stop if more than one members are non-undef.
6017       if (NumDefs > 1)
6018         break;
6019       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6020                                      VT.getVectorElementType(),
6021                                      X.getValueType().getVectorNumElements()));
6022     }
6023
6024     if (NumDefs == 0)
6025       return DAG.getUNDEF(VT);
6026
6027     if (NumDefs == 1) {
6028       assert(V.getNode() && "The single defined operand is empty!");
6029       SmallVector<SDValue, 8> Opnds;
6030       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6031         if (i != Idx) {
6032           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6033           continue;
6034         }
6035         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6036         AddToWorkList(NV.getNode());
6037         Opnds.push_back(NV);
6038       }
6039       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6040     }
6041   }
6042
6043   // Simplify the operands using demanded-bits information.
6044   if (!VT.isVector() &&
6045       SimplifyDemandedBits(SDValue(N, 0)))
6046     return SDValue(N, 0);
6047
6048   return SDValue();
6049 }
6050
6051 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6052   SDValue Elt = N->getOperand(i);
6053   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6054     return Elt.getNode();
6055   return Elt.getOperand(Elt.getResNo()).getNode();
6056 }
6057
6058 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6059 /// if load locations are consecutive.
6060 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6061   assert(N->getOpcode() == ISD::BUILD_PAIR);
6062
6063   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6064   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6065   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6066       LD1->getAddressSpace() != LD2->getAddressSpace())
6067     return SDValue();
6068   EVT LD1VT = LD1->getValueType(0);
6069
6070   if (ISD::isNON_EXTLoad(LD2) &&
6071       LD2->hasOneUse() &&
6072       // If both are volatile this would reduce the number of volatile loads.
6073       // If one is volatile it might be ok, but play conservative and bail out.
6074       !LD1->isVolatile() &&
6075       !LD2->isVolatile() &&
6076       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6077     unsigned Align = LD1->getAlignment();
6078     unsigned NewAlign = TLI.getDataLayout()->
6079       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6080
6081     if (NewAlign <= Align &&
6082         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6083       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6084                          LD1->getBasePtr(), LD1->getPointerInfo(),
6085                          false, false, false, Align);
6086   }
6087
6088   return SDValue();
6089 }
6090
6091 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6092   SDValue N0 = N->getOperand(0);
6093   EVT VT = N->getValueType(0);
6094
6095   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6096   // Only do this before legalize, since afterward the target may be depending
6097   // on the bitconvert.
6098   // First check to see if this is all constant.
6099   if (!LegalTypes &&
6100       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6101       VT.isVector()) {
6102     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6103
6104     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6105     assert(!DestEltVT.isVector() &&
6106            "Element type of vector ValueType must not be vector!");
6107     if (isSimple)
6108       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6109   }
6110
6111   // If the input is a constant, let getNode fold it.
6112   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6113     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6114     if (Res.getNode() != N) {
6115       if (!LegalOperations ||
6116           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6117         return Res;
6118
6119       // Folding it resulted in an illegal node, and it's too late to
6120       // do that. Clean up the old node and forego the transformation.
6121       // Ideally this won't happen very often, because instcombine
6122       // and the earlier dagcombine runs (where illegal nodes are
6123       // permitted) should have folded most of them already.
6124       DAG.DeleteNode(Res.getNode());
6125     }
6126   }
6127
6128   // (conv (conv x, t1), t2) -> (conv x, t2)
6129   if (N0.getOpcode() == ISD::BITCAST)
6130     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6131                        N0.getOperand(0));
6132
6133   // fold (conv (load x)) -> (load (conv*)x)
6134   // If the resultant load doesn't need a higher alignment than the original!
6135   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6136       // Do not change the width of a volatile load.
6137       !cast<LoadSDNode>(N0)->isVolatile() &&
6138       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6139       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6140     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6141     unsigned Align = TLI.getDataLayout()->
6142       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6143     unsigned OrigAlign = LN0->getAlignment();
6144
6145     if (Align <= OrigAlign) {
6146       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6147                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6148                                  LN0->isVolatile(), LN0->isNonTemporal(),
6149                                  LN0->isInvariant(), OrigAlign,
6150                                  LN0->getTBAAInfo());
6151       AddToWorkList(N);
6152       CombineTo(N0.getNode(),
6153                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6154                             N0.getValueType(), Load),
6155                 Load.getValue(1));
6156       return Load;
6157     }
6158   }
6159
6160   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6161   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6162   // This often reduces constant pool loads.
6163   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6164        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6165       N0.getNode()->hasOneUse() && VT.isInteger() &&
6166       !VT.isVector() && !N0.getValueType().isVector()) {
6167     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6168                                   N0.getOperand(0));
6169     AddToWorkList(NewConv.getNode());
6170
6171     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6172     if (N0.getOpcode() == ISD::FNEG)
6173       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6174                          NewConv, DAG.getConstant(SignBit, VT));
6175     assert(N0.getOpcode() == ISD::FABS);
6176     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6177                        NewConv, DAG.getConstant(~SignBit, VT));
6178   }
6179
6180   // fold (bitconvert (fcopysign cst, x)) ->
6181   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6182   // Note that we don't handle (copysign x, cst) because this can always be
6183   // folded to an fneg or fabs.
6184   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6185       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6186       VT.isInteger() && !VT.isVector()) {
6187     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6188     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6189     if (isTypeLegal(IntXVT)) {
6190       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6191                               IntXVT, N0.getOperand(1));
6192       AddToWorkList(X.getNode());
6193
6194       // If X has a different width than the result/lhs, sext it or truncate it.
6195       unsigned VTWidth = VT.getSizeInBits();
6196       if (OrigXWidth < VTWidth) {
6197         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6198         AddToWorkList(X.getNode());
6199       } else if (OrigXWidth > VTWidth) {
6200         // To get the sign bit in the right place, we have to shift it right
6201         // before truncating.
6202         X = DAG.getNode(ISD::SRL, SDLoc(X),
6203                         X.getValueType(), X,
6204                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6205         AddToWorkList(X.getNode());
6206         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6207         AddToWorkList(X.getNode());
6208       }
6209
6210       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6211       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6212                       X, DAG.getConstant(SignBit, VT));
6213       AddToWorkList(X.getNode());
6214
6215       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6216                                 VT, N0.getOperand(0));
6217       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6218                         Cst, DAG.getConstant(~SignBit, VT));
6219       AddToWorkList(Cst.getNode());
6220
6221       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6222     }
6223   }
6224
6225   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6226   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6227     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6228     if (CombineLD.getNode())
6229       return CombineLD;
6230   }
6231
6232   return SDValue();
6233 }
6234
6235 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6236   EVT VT = N->getValueType(0);
6237   return CombineConsecutiveLoads(N, VT);
6238 }
6239
6240 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6241 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6242 /// destination element value type.
6243 SDValue DAGCombiner::
6244 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6245   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6246
6247   // If this is already the right type, we're done.
6248   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6249
6250   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6251   unsigned DstBitSize = DstEltVT.getSizeInBits();
6252
6253   // If this is a conversion of N elements of one type to N elements of another
6254   // type, convert each element.  This handles FP<->INT cases.
6255   if (SrcBitSize == DstBitSize) {
6256     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6257                               BV->getValueType(0).getVectorNumElements());
6258
6259     // Due to the FP element handling below calling this routine recursively,
6260     // we can end up with a scalar-to-vector node here.
6261     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6262       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6263                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6264                                      DstEltVT, BV->getOperand(0)));
6265
6266     SmallVector<SDValue, 8> Ops;
6267     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6268       SDValue Op = BV->getOperand(i);
6269       // If the vector element type is not legal, the BUILD_VECTOR operands
6270       // are promoted and implicitly truncated.  Make that explicit here.
6271       if (Op.getValueType() != SrcEltVT)
6272         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6273       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6274                                 DstEltVT, Op));
6275       AddToWorkList(Ops.back().getNode());
6276     }
6277     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6278   }
6279
6280   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6281   // handle annoying details of growing/shrinking FP values, we convert them to
6282   // int first.
6283   if (SrcEltVT.isFloatingPoint()) {
6284     // Convert the input float vector to a int vector where the elements are the
6285     // same sizes.
6286     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6287     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6288     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6289     SrcEltVT = IntVT;
6290   }
6291
6292   // Now we know the input is an integer vector.  If the output is a FP type,
6293   // convert to integer first, then to FP of the right size.
6294   if (DstEltVT.isFloatingPoint()) {
6295     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6296     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6297     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6298
6299     // Next, convert to FP elements of the same size.
6300     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6301   }
6302
6303   // Okay, we know the src/dst types are both integers of differing types.
6304   // Handling growing first.
6305   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6306   if (SrcBitSize < DstBitSize) {
6307     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6308
6309     SmallVector<SDValue, 8> Ops;
6310     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6311          i += NumInputsPerOutput) {
6312       bool isLE = TLI.isLittleEndian();
6313       APInt NewBits = APInt(DstBitSize, 0);
6314       bool EltIsUndef = true;
6315       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6316         // Shift the previously computed bits over.
6317         NewBits <<= SrcBitSize;
6318         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6319         if (Op.getOpcode() == ISD::UNDEF) continue;
6320         EltIsUndef = false;
6321
6322         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6323                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6324       }
6325
6326       if (EltIsUndef)
6327         Ops.push_back(DAG.getUNDEF(DstEltVT));
6328       else
6329         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6330     }
6331
6332     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6333     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6334   }
6335
6336   // Finally, this must be the case where we are shrinking elements: each input
6337   // turns into multiple outputs.
6338   bool isS2V = ISD::isScalarToVector(BV);
6339   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6340   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6341                             NumOutputsPerInput*BV->getNumOperands());
6342   SmallVector<SDValue, 8> Ops;
6343
6344   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6345     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6346       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6347         Ops.push_back(DAG.getUNDEF(DstEltVT));
6348       continue;
6349     }
6350
6351     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6352                   getAPIntValue().zextOrTrunc(SrcBitSize);
6353
6354     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6355       APInt ThisVal = OpVal.trunc(DstBitSize);
6356       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6357       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6358         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6359         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6360                            Ops[0]);
6361       OpVal = OpVal.lshr(DstBitSize);
6362     }
6363
6364     // For big endian targets, swap the order of the pieces of each element.
6365     if (TLI.isBigEndian())
6366       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6367   }
6368
6369   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6370 }
6371
6372 SDValue DAGCombiner::visitFADD(SDNode *N) {
6373   SDValue N0 = N->getOperand(0);
6374   SDValue N1 = N->getOperand(1);
6375   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6376   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6377   EVT VT = N->getValueType(0);
6378
6379   // fold vector ops
6380   if (VT.isVector()) {
6381     SDValue FoldedVOp = SimplifyVBinOp(N);
6382     if (FoldedVOp.getNode()) return FoldedVOp;
6383   }
6384
6385   // fold (fadd c1, c2) -> c1 + c2
6386   if (N0CFP && N1CFP)
6387     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6388   // canonicalize constant to RHS
6389   if (N0CFP && !N1CFP)
6390     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6391   // fold (fadd A, 0) -> A
6392   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6393       N1CFP->getValueAPF().isZero())
6394     return N0;
6395   // fold (fadd A, (fneg B)) -> (fsub A, B)
6396   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6397     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6398     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6399                        GetNegatedExpression(N1, DAG, LegalOperations));
6400   // fold (fadd (fneg A), B) -> (fsub B, A)
6401   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6402     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6403     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6404                        GetNegatedExpression(N0, DAG, LegalOperations));
6405
6406   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6407   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6408       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6409       isa<ConstantFPSDNode>(N0.getOperand(1)))
6410     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6411                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6412                                    N0.getOperand(1), N1));
6413
6414   // No FP constant should be created after legalization as Instruction
6415   // Selection pass has hard time in dealing with FP constant.
6416   //
6417   // We don't need test this condition for transformation like following, as
6418   // the DAG being transformed implies it is legal to take FP constant as
6419   // operand.
6420   //
6421   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6422   //
6423   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6424
6425   // If allow, fold (fadd (fneg x), x) -> 0.0
6426   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6427       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6428     return DAG.getConstantFP(0.0, VT);
6429
6430     // If allow, fold (fadd x, (fneg x)) -> 0.0
6431   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6432       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6433     return DAG.getConstantFP(0.0, VT);
6434
6435   // In unsafe math mode, we can fold chains of FADD's of the same value
6436   // into multiplications.  This transform is not safe in general because
6437   // we are reducing the number of rounding steps.
6438   if (DAG.getTarget().Options.UnsafeFPMath &&
6439       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6440       !N0CFP && !N1CFP) {
6441     if (N0.getOpcode() == ISD::FMUL) {
6442       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6443       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6444
6445       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6446       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6447         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6448                                      SDValue(CFP00, 0),
6449                                      DAG.getConstantFP(1.0, VT));
6450         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6451                            N1, NewCFP);
6452       }
6453
6454       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6455       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6456         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6457                                      SDValue(CFP01, 0),
6458                                      DAG.getConstantFP(1.0, VT));
6459         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6460                            N1, NewCFP);
6461       }
6462
6463       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6464       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6465           N1.getOperand(0) == N1.getOperand(1) &&
6466           N0.getOperand(1) == N1.getOperand(0)) {
6467         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6468                                      SDValue(CFP00, 0),
6469                                      DAG.getConstantFP(2.0, VT));
6470         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6471                            N0.getOperand(1), NewCFP);
6472       }
6473
6474       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6475       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6476           N1.getOperand(0) == N1.getOperand(1) &&
6477           N0.getOperand(0) == N1.getOperand(0)) {
6478         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6479                                      SDValue(CFP01, 0),
6480                                      DAG.getConstantFP(2.0, VT));
6481         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6482                            N0.getOperand(0), NewCFP);
6483       }
6484     }
6485
6486     if (N1.getOpcode() == ISD::FMUL) {
6487       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6488       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6489
6490       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6491       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6492         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6493                                      SDValue(CFP10, 0),
6494                                      DAG.getConstantFP(1.0, VT));
6495         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6496                            N0, NewCFP);
6497       }
6498
6499       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6500       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6501         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6502                                      SDValue(CFP11, 0),
6503                                      DAG.getConstantFP(1.0, VT));
6504         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6505                            N0, NewCFP);
6506       }
6507
6508
6509       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6510       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6511           N0.getOperand(0) == N0.getOperand(1) &&
6512           N1.getOperand(1) == N0.getOperand(0)) {
6513         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6514                                      SDValue(CFP10, 0),
6515                                      DAG.getConstantFP(2.0, VT));
6516         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6517                            N1.getOperand(1), NewCFP);
6518       }
6519
6520       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6521       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6522           N0.getOperand(0) == N0.getOperand(1) &&
6523           N1.getOperand(0) == N0.getOperand(0)) {
6524         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6525                                      SDValue(CFP11, 0),
6526                                      DAG.getConstantFP(2.0, VT));
6527         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6528                            N1.getOperand(0), NewCFP);
6529       }
6530     }
6531
6532     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6533       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6534       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6535       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6536           (N0.getOperand(0) == N1))
6537         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538                            N1, DAG.getConstantFP(3.0, VT));
6539     }
6540
6541     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6542       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6543       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6544       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6545           N1.getOperand(0) == N0)
6546         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6547                            N0, DAG.getConstantFP(3.0, VT));
6548     }
6549
6550     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6551     if (AllowNewFpConst &&
6552         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6553         N0.getOperand(0) == N0.getOperand(1) &&
6554         N1.getOperand(0) == N1.getOperand(1) &&
6555         N0.getOperand(0) == N1.getOperand(0))
6556       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6557                          N0.getOperand(0),
6558                          DAG.getConstantFP(4.0, VT));
6559   }
6560
6561   // FADD -> FMA combines:
6562   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6563        DAG.getTarget().Options.UnsafeFPMath) &&
6564       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6565       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6566
6567     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6568     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6569       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6570                          N0.getOperand(0), N0.getOperand(1), N1);
6571
6572     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6573     // Note: Commutes FADD operands.
6574     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6575       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6576                          N1.getOperand(0), N1.getOperand(1), N0);
6577   }
6578
6579   return SDValue();
6580 }
6581
6582 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6583   SDValue N0 = N->getOperand(0);
6584   SDValue N1 = N->getOperand(1);
6585   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6586   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6587   EVT VT = N->getValueType(0);
6588   SDLoc dl(N);
6589
6590   // fold vector ops
6591   if (VT.isVector()) {
6592     SDValue FoldedVOp = SimplifyVBinOp(N);
6593     if (FoldedVOp.getNode()) return FoldedVOp;
6594   }
6595
6596   // fold (fsub c1, c2) -> c1-c2
6597   if (N0CFP && N1CFP)
6598     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6599   // fold (fsub A, 0) -> A
6600   if (DAG.getTarget().Options.UnsafeFPMath &&
6601       N1CFP && N1CFP->getValueAPF().isZero())
6602     return N0;
6603   // fold (fsub 0, B) -> -B
6604   if (DAG.getTarget().Options.UnsafeFPMath &&
6605       N0CFP && N0CFP->getValueAPF().isZero()) {
6606     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6607       return GetNegatedExpression(N1, DAG, LegalOperations);
6608     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6609       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6610   }
6611   // fold (fsub A, (fneg B)) -> (fadd A, B)
6612   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6613     return DAG.getNode(ISD::FADD, dl, VT, N0,
6614                        GetNegatedExpression(N1, DAG, LegalOperations));
6615
6616   // If 'unsafe math' is enabled, fold
6617   //    (fsub x, x) -> 0.0 &
6618   //    (fsub x, (fadd x, y)) -> (fneg y) &
6619   //    (fsub x, (fadd y, x)) -> (fneg y)
6620   if (DAG.getTarget().Options.UnsafeFPMath) {
6621     if (N0 == N1)
6622       return DAG.getConstantFP(0.0f, VT);
6623
6624     if (N1.getOpcode() == ISD::FADD) {
6625       SDValue N10 = N1->getOperand(0);
6626       SDValue N11 = N1->getOperand(1);
6627
6628       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6629                                           &DAG.getTarget().Options))
6630         return GetNegatedExpression(N11, DAG, LegalOperations);
6631
6632       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6633                                           &DAG.getTarget().Options))
6634         return GetNegatedExpression(N10, DAG, LegalOperations);
6635     }
6636   }
6637
6638   // FSUB -> FMA combines:
6639   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6640        DAG.getTarget().Options.UnsafeFPMath) &&
6641       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6642       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6643
6644     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6645     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6646       return DAG.getNode(ISD::FMA, dl, VT,
6647                          N0.getOperand(0), N0.getOperand(1),
6648                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6649
6650     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6651     // Note: Commutes FSUB operands.
6652     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6653       return DAG.getNode(ISD::FMA, dl, VT,
6654                          DAG.getNode(ISD::FNEG, dl, VT,
6655                          N1.getOperand(0)),
6656                          N1.getOperand(1), N0);
6657
6658     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6659     if (N0.getOpcode() == ISD::FNEG &&
6660         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6661         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6662       SDValue N00 = N0.getOperand(0).getOperand(0);
6663       SDValue N01 = N0.getOperand(0).getOperand(1);
6664       return DAG.getNode(ISD::FMA, dl, VT,
6665                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6666                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6667     }
6668   }
6669
6670   return SDValue();
6671 }
6672
6673 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6674   SDValue N0 = N->getOperand(0);
6675   SDValue N1 = N->getOperand(1);
6676   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6677   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6678   EVT VT = N->getValueType(0);
6679   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6680
6681   // fold vector ops
6682   if (VT.isVector()) {
6683     SDValue FoldedVOp = SimplifyVBinOp(N);
6684     if (FoldedVOp.getNode()) return FoldedVOp;
6685   }
6686
6687   // fold (fmul c1, c2) -> c1*c2
6688   if (N0CFP && N1CFP)
6689     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6690   // canonicalize constant to RHS
6691   if (N0CFP && !N1CFP)
6692     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6693   // fold (fmul A, 0) -> 0
6694   if (DAG.getTarget().Options.UnsafeFPMath &&
6695       N1CFP && N1CFP->getValueAPF().isZero())
6696     return N1;
6697   // fold (fmul A, 0) -> 0, vector edition.
6698   if (DAG.getTarget().Options.UnsafeFPMath &&
6699       ISD::isBuildVectorAllZeros(N1.getNode()))
6700     return N1;
6701   // fold (fmul A, 1.0) -> A
6702   if (N1CFP && N1CFP->isExactlyValue(1.0))
6703     return N0;
6704   // fold (fmul X, 2.0) -> (fadd X, X)
6705   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6706     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6707   // fold (fmul X, -1.0) -> (fneg X)
6708   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6709     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6710       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6711
6712   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6713   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6714                                        &DAG.getTarget().Options)) {
6715     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6716                                          &DAG.getTarget().Options)) {
6717       // Both can be negated for free, check to see if at least one is cheaper
6718       // negated.
6719       if (LHSNeg == 2 || RHSNeg == 2)
6720         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6721                            GetNegatedExpression(N0, DAG, LegalOperations),
6722                            GetNegatedExpression(N1, DAG, LegalOperations));
6723     }
6724   }
6725
6726   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6727   if (DAG.getTarget().Options.UnsafeFPMath &&
6728       N1CFP && N0.getOpcode() == ISD::FMUL &&
6729       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6730     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6731                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6732                                    N0.getOperand(1), N1));
6733
6734   return SDValue();
6735 }
6736
6737 SDValue DAGCombiner::visitFMA(SDNode *N) {
6738   SDValue N0 = N->getOperand(0);
6739   SDValue N1 = N->getOperand(1);
6740   SDValue N2 = N->getOperand(2);
6741   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6742   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6743   EVT VT = N->getValueType(0);
6744   SDLoc dl(N);
6745
6746   if (DAG.getTarget().Options.UnsafeFPMath) {
6747     if (N0CFP && N0CFP->isZero())
6748       return N2;
6749     if (N1CFP && N1CFP->isZero())
6750       return N2;
6751   }
6752   if (N0CFP && N0CFP->isExactlyValue(1.0))
6753     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6754   if (N1CFP && N1CFP->isExactlyValue(1.0))
6755     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6756
6757   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6758   if (N0CFP && !N1CFP)
6759     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6760
6761   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6762   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6763       N2.getOpcode() == ISD::FMUL &&
6764       N0 == N2.getOperand(0) &&
6765       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6766     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6767                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6768   }
6769
6770
6771   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6772   if (DAG.getTarget().Options.UnsafeFPMath &&
6773       N0.getOpcode() == ISD::FMUL && N1CFP &&
6774       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6775     return DAG.getNode(ISD::FMA, dl, VT,
6776                        N0.getOperand(0),
6777                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6778                        N2);
6779   }
6780
6781   // (fma x, 1, y) -> (fadd x, y)
6782   // (fma x, -1, y) -> (fadd (fneg x), y)
6783   if (N1CFP) {
6784     if (N1CFP->isExactlyValue(1.0))
6785       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6786
6787     if (N1CFP->isExactlyValue(-1.0) &&
6788         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6789       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6790       AddToWorkList(RHSNeg.getNode());
6791       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6792     }
6793   }
6794
6795   // (fma x, c, x) -> (fmul x, (c+1))
6796   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6797     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6798                        DAG.getNode(ISD::FADD, dl, VT,
6799                                    N1, DAG.getConstantFP(1.0, VT)));
6800
6801   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6802   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6803       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6804     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6805                        DAG.getNode(ISD::FADD, dl, VT,
6806                                    N1, DAG.getConstantFP(-1.0, VT)));
6807
6808
6809   return SDValue();
6810 }
6811
6812 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6813   SDValue N0 = N->getOperand(0);
6814   SDValue N1 = N->getOperand(1);
6815   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6816   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6817   EVT VT = N->getValueType(0);
6818   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6819
6820   // fold vector ops
6821   if (VT.isVector()) {
6822     SDValue FoldedVOp = SimplifyVBinOp(N);
6823     if (FoldedVOp.getNode()) return FoldedVOp;
6824   }
6825
6826   // fold (fdiv c1, c2) -> c1/c2
6827   if (N0CFP && N1CFP)
6828     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6829
6830   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6831   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6832     // Compute the reciprocal 1.0 / c2.
6833     APFloat N1APF = N1CFP->getValueAPF();
6834     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6835     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6836     // Only do the transform if the reciprocal is a legal fp immediate that
6837     // isn't too nasty (eg NaN, denormal, ...).
6838     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6839         (!LegalOperations ||
6840          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6841          // backend)... we should handle this gracefully after Legalize.
6842          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6843          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6844          TLI.isFPImmLegal(Recip, VT)))
6845       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6846                          DAG.getConstantFP(Recip, VT));
6847   }
6848
6849   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6850   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6851                                        &DAG.getTarget().Options)) {
6852     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6853                                          &DAG.getTarget().Options)) {
6854       // Both can be negated for free, check to see if at least one is cheaper
6855       // negated.
6856       if (LHSNeg == 2 || RHSNeg == 2)
6857         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6858                            GetNegatedExpression(N0, DAG, LegalOperations),
6859                            GetNegatedExpression(N1, DAG, LegalOperations));
6860     }
6861   }
6862
6863   return SDValue();
6864 }
6865
6866 SDValue DAGCombiner::visitFREM(SDNode *N) {
6867   SDValue N0 = N->getOperand(0);
6868   SDValue N1 = N->getOperand(1);
6869   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6870   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6871   EVT VT = N->getValueType(0);
6872
6873   // fold (frem c1, c2) -> fmod(c1,c2)
6874   if (N0CFP && N1CFP)
6875     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6876
6877   return SDValue();
6878 }
6879
6880 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6881   SDValue N0 = N->getOperand(0);
6882   SDValue N1 = N->getOperand(1);
6883   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6884   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6885   EVT VT = N->getValueType(0);
6886
6887   if (N0CFP && N1CFP)  // Constant fold
6888     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6889
6890   if (N1CFP) {
6891     const APFloat& V = N1CFP->getValueAPF();
6892     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6893     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6894     if (!V.isNegative()) {
6895       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6896         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6897     } else {
6898       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6899         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6900                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6901     }
6902   }
6903
6904   // copysign(fabs(x), y) -> copysign(x, y)
6905   // copysign(fneg(x), y) -> copysign(x, y)
6906   // copysign(copysign(x,z), y) -> copysign(x, y)
6907   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6908       N0.getOpcode() == ISD::FCOPYSIGN)
6909     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6910                        N0.getOperand(0), N1);
6911
6912   // copysign(x, abs(y)) -> abs(x)
6913   if (N1.getOpcode() == ISD::FABS)
6914     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6915
6916   // copysign(x, copysign(y,z)) -> copysign(x, z)
6917   if (N1.getOpcode() == ISD::FCOPYSIGN)
6918     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6919                        N0, N1.getOperand(1));
6920
6921   // copysign(x, fp_extend(y)) -> copysign(x, y)
6922   // copysign(x, fp_round(y)) -> copysign(x, y)
6923   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6924     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6925                        N0, N1.getOperand(0));
6926
6927   return SDValue();
6928 }
6929
6930 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6931   SDValue N0 = N->getOperand(0);
6932   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6933   EVT VT = N->getValueType(0);
6934   EVT OpVT = N0.getValueType();
6935
6936   // fold (sint_to_fp c1) -> c1fp
6937   if (N0C &&
6938       // ...but only if the target supports immediate floating-point values
6939       (!LegalOperations ||
6940        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6941     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6942
6943   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6944   // but UINT_TO_FP is legal on this target, try to convert.
6945   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6946       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6947     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6948     if (DAG.SignBitIsZero(N0))
6949       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6950   }
6951
6952   // The next optimizations are desirable only if SELECT_CC can be lowered.
6953   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6954   // having to say they don't support SELECT_CC on every type the DAG knows
6955   // about, since there is no way to mark an opcode illegal at all value types
6956   // (See also visitSELECT)
6957   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6958     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6959     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6960         !VT.isVector() &&
6961         (!LegalOperations ||
6962          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6963       SDValue Ops[] =
6964         { N0.getOperand(0), N0.getOperand(1),
6965           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6966           N0.getOperand(2) };
6967       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6968     }
6969
6970     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6971     //      (select_cc x, y, 1.0, 0.0,, cc)
6972     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6973         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6974         (!LegalOperations ||
6975          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6976       SDValue Ops[] =
6977         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6978           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6979           N0.getOperand(0).getOperand(2) };
6980       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
6981     }
6982   }
6983
6984   return SDValue();
6985 }
6986
6987 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6988   SDValue N0 = N->getOperand(0);
6989   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6990   EVT VT = N->getValueType(0);
6991   EVT OpVT = N0.getValueType();
6992
6993   // fold (uint_to_fp c1) -> c1fp
6994   if (N0C &&
6995       // ...but only if the target supports immediate floating-point values
6996       (!LegalOperations ||
6997        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6998     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6999
7000   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7001   // but SINT_TO_FP is legal on this target, try to convert.
7002   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7003       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7004     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7005     if (DAG.SignBitIsZero(N0))
7006       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7007   }
7008
7009   // The next optimizations are desirable only if SELECT_CC can be lowered.
7010   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7011   // having to say they don't support SELECT_CC on every type the DAG knows
7012   // about, since there is no way to mark an opcode illegal at all value types
7013   // (See also visitSELECT)
7014   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7015     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7016
7017     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7018         (!LegalOperations ||
7019          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7020       SDValue Ops[] =
7021         { N0.getOperand(0), N0.getOperand(1),
7022           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7023           N0.getOperand(2) };
7024       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7025     }
7026   }
7027
7028   return SDValue();
7029 }
7030
7031 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7032   SDValue N0 = N->getOperand(0);
7033   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7034   EVT VT = N->getValueType(0);
7035
7036   // fold (fp_to_sint c1fp) -> c1
7037   if (N0CFP)
7038     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7039
7040   return SDValue();
7041 }
7042
7043 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7044   SDValue N0 = N->getOperand(0);
7045   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7046   EVT VT = N->getValueType(0);
7047
7048   // fold (fp_to_uint c1fp) -> c1
7049   if (N0CFP)
7050     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7051
7052   return SDValue();
7053 }
7054
7055 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7056   SDValue N0 = N->getOperand(0);
7057   SDValue N1 = N->getOperand(1);
7058   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7059   EVT VT = N->getValueType(0);
7060
7061   // fold (fp_round c1fp) -> c1fp
7062   if (N0CFP)
7063     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7064
7065   // fold (fp_round (fp_extend x)) -> x
7066   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7067     return N0.getOperand(0);
7068
7069   // fold (fp_round (fp_round x)) -> (fp_round x)
7070   if (N0.getOpcode() == ISD::FP_ROUND) {
7071     // This is a value preserving truncation if both round's are.
7072     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7073                    N0.getNode()->getConstantOperandVal(1) == 1;
7074     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7075                        DAG.getIntPtrConstant(IsTrunc));
7076   }
7077
7078   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7079   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7080     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7081                               N0.getOperand(0), N1);
7082     AddToWorkList(Tmp.getNode());
7083     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7084                        Tmp, N0.getOperand(1));
7085   }
7086
7087   return SDValue();
7088 }
7089
7090 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7091   SDValue N0 = N->getOperand(0);
7092   EVT VT = N->getValueType(0);
7093   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7094   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7095
7096   // fold (fp_round_inreg c1fp) -> c1fp
7097   if (N0CFP && isTypeLegal(EVT)) {
7098     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7099     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7100   }
7101
7102   return SDValue();
7103 }
7104
7105 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7106   SDValue N0 = N->getOperand(0);
7107   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7108   EVT VT = N->getValueType(0);
7109
7110   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7111   if (N->hasOneUse() &&
7112       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7113     return SDValue();
7114
7115   // fold (fp_extend c1fp) -> c1fp
7116   if (N0CFP)
7117     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7118
7119   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7120   // value of X.
7121   if (N0.getOpcode() == ISD::FP_ROUND
7122       && N0.getNode()->getConstantOperandVal(1) == 1) {
7123     SDValue In = N0.getOperand(0);
7124     if (In.getValueType() == VT) return In;
7125     if (VT.bitsLT(In.getValueType()))
7126       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7127                          In, N0.getOperand(1));
7128     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7129   }
7130
7131   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7132   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7133       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7134        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7135     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7136     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7137                                      LN0->getChain(),
7138                                      LN0->getBasePtr(), N0.getValueType(),
7139                                      LN0->getMemOperand());
7140     CombineTo(N, ExtLoad);
7141     CombineTo(N0.getNode(),
7142               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7143                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7144               ExtLoad.getValue(1));
7145     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7146   }
7147
7148   return SDValue();
7149 }
7150
7151 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7152   SDValue N0 = N->getOperand(0);
7153   EVT VT = N->getValueType(0);
7154
7155   if (VT.isVector()) {
7156     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7157     if (FoldedVOp.getNode()) return FoldedVOp;
7158   }
7159
7160   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7161                          &DAG.getTarget().Options))
7162     return GetNegatedExpression(N0, DAG, LegalOperations);
7163
7164   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7165   // constant pool values.
7166   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7167       !VT.isVector() &&
7168       N0.getNode()->hasOneUse() &&
7169       N0.getOperand(0).getValueType().isInteger()) {
7170     SDValue Int = N0.getOperand(0);
7171     EVT IntVT = Int.getValueType();
7172     if (IntVT.isInteger() && !IntVT.isVector()) {
7173       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7174               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7175       AddToWorkList(Int.getNode());
7176       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7177                          VT, Int);
7178     }
7179   }
7180
7181   // (fneg (fmul c, x)) -> (fmul -c, x)
7182   if (N0.getOpcode() == ISD::FMUL) {
7183     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7184     if (CFP1)
7185       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7186                          N0.getOperand(0),
7187                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7188                                      N0.getOperand(1)));
7189   }
7190
7191   return SDValue();
7192 }
7193
7194 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7195   SDValue N0 = N->getOperand(0);
7196   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7197   EVT VT = N->getValueType(0);
7198
7199   // fold (fceil c1) -> fceil(c1)
7200   if (N0CFP)
7201     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7202
7203   return SDValue();
7204 }
7205
7206 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7207   SDValue N0 = N->getOperand(0);
7208   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7209   EVT VT = N->getValueType(0);
7210
7211   // fold (ftrunc c1) -> ftrunc(c1)
7212   if (N0CFP)
7213     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7214
7215   return SDValue();
7216 }
7217
7218 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7219   SDValue N0 = N->getOperand(0);
7220   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7221   EVT VT = N->getValueType(0);
7222
7223   // fold (ffloor c1) -> ffloor(c1)
7224   if (N0CFP)
7225     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7226
7227   return SDValue();
7228 }
7229
7230 SDValue DAGCombiner::visitFABS(SDNode *N) {
7231   SDValue N0 = N->getOperand(0);
7232   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7233   EVT VT = N->getValueType(0);
7234
7235   if (VT.isVector()) {
7236     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7237     if (FoldedVOp.getNode()) return FoldedVOp;
7238   }
7239
7240   // fold (fabs c1) -> fabs(c1)
7241   if (N0CFP)
7242     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7243   // fold (fabs (fabs x)) -> (fabs x)
7244   if (N0.getOpcode() == ISD::FABS)
7245     return N->getOperand(0);
7246   // fold (fabs (fneg x)) -> (fabs x)
7247   // fold (fabs (fcopysign x, y)) -> (fabs x)
7248   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7249     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7250
7251   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7252   // constant pool values.
7253   if (!TLI.isFAbsFree(VT) &&
7254       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7255       N0.getOperand(0).getValueType().isInteger() &&
7256       !N0.getOperand(0).getValueType().isVector()) {
7257     SDValue Int = N0.getOperand(0);
7258     EVT IntVT = Int.getValueType();
7259     if (IntVT.isInteger() && !IntVT.isVector()) {
7260       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7261              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7262       AddToWorkList(Int.getNode());
7263       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7264                          N->getValueType(0), Int);
7265     }
7266   }
7267
7268   return SDValue();
7269 }
7270
7271 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7272   SDValue Chain = N->getOperand(0);
7273   SDValue N1 = N->getOperand(1);
7274   SDValue N2 = N->getOperand(2);
7275
7276   // If N is a constant we could fold this into a fallthrough or unconditional
7277   // branch. However that doesn't happen very often in normal code, because
7278   // Instcombine/SimplifyCFG should have handled the available opportunities.
7279   // If we did this folding here, it would be necessary to update the
7280   // MachineBasicBlock CFG, which is awkward.
7281
7282   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7283   // on the target.
7284   if (N1.getOpcode() == ISD::SETCC &&
7285       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7286                                    N1.getOperand(0).getValueType())) {
7287     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7288                        Chain, N1.getOperand(2),
7289                        N1.getOperand(0), N1.getOperand(1), N2);
7290   }
7291
7292   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7293       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7294        (N1.getOperand(0).hasOneUse() &&
7295         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7296     SDNode *Trunc = nullptr;
7297     if (N1.getOpcode() == ISD::TRUNCATE) {
7298       // Look pass the truncate.
7299       Trunc = N1.getNode();
7300       N1 = N1.getOperand(0);
7301     }
7302
7303     // Match this pattern so that we can generate simpler code:
7304     //
7305     //   %a = ...
7306     //   %b = and i32 %a, 2
7307     //   %c = srl i32 %b, 1
7308     //   brcond i32 %c ...
7309     //
7310     // into
7311     //
7312     //   %a = ...
7313     //   %b = and i32 %a, 2
7314     //   %c = setcc eq %b, 0
7315     //   brcond %c ...
7316     //
7317     // This applies only when the AND constant value has one bit set and the
7318     // SRL constant is equal to the log2 of the AND constant. The back-end is
7319     // smart enough to convert the result into a TEST/JMP sequence.
7320     SDValue Op0 = N1.getOperand(0);
7321     SDValue Op1 = N1.getOperand(1);
7322
7323     if (Op0.getOpcode() == ISD::AND &&
7324         Op1.getOpcode() == ISD::Constant) {
7325       SDValue AndOp1 = Op0.getOperand(1);
7326
7327       if (AndOp1.getOpcode() == ISD::Constant) {
7328         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7329
7330         if (AndConst.isPowerOf2() &&
7331             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7332           SDValue SetCC =
7333             DAG.getSetCC(SDLoc(N),
7334                          getSetCCResultType(Op0.getValueType()),
7335                          Op0, DAG.getConstant(0, Op0.getValueType()),
7336                          ISD::SETNE);
7337
7338           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7339                                           MVT::Other, Chain, SetCC, N2);
7340           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7341           // will convert it back to (X & C1) >> C2.
7342           CombineTo(N, NewBRCond, false);
7343           // Truncate is dead.
7344           if (Trunc) {
7345             removeFromWorkList(Trunc);
7346             DAG.DeleteNode(Trunc);
7347           }
7348           // Replace the uses of SRL with SETCC
7349           WorkListRemover DeadNodes(*this);
7350           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7351           removeFromWorkList(N1.getNode());
7352           DAG.DeleteNode(N1.getNode());
7353           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7354         }
7355       }
7356     }
7357
7358     if (Trunc)
7359       // Restore N1 if the above transformation doesn't match.
7360       N1 = N->getOperand(1);
7361   }
7362
7363   // Transform br(xor(x, y)) -> br(x != y)
7364   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7365   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7366     SDNode *TheXor = N1.getNode();
7367     SDValue Op0 = TheXor->getOperand(0);
7368     SDValue Op1 = TheXor->getOperand(1);
7369     if (Op0.getOpcode() == Op1.getOpcode()) {
7370       // Avoid missing important xor optimizations.
7371       SDValue Tmp = visitXOR(TheXor);
7372       if (Tmp.getNode()) {
7373         if (Tmp.getNode() != TheXor) {
7374           DEBUG(dbgs() << "\nReplacing.8 ";
7375                 TheXor->dump(&DAG);
7376                 dbgs() << "\nWith: ";
7377                 Tmp.getNode()->dump(&DAG);
7378                 dbgs() << '\n');
7379           WorkListRemover DeadNodes(*this);
7380           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7381           removeFromWorkList(TheXor);
7382           DAG.DeleteNode(TheXor);
7383           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7384                              MVT::Other, Chain, Tmp, N2);
7385         }
7386
7387         // visitXOR has changed XOR's operands or replaced the XOR completely,
7388         // bail out.
7389         return SDValue(N, 0);
7390       }
7391     }
7392
7393     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7394       bool Equal = false;
7395       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7396         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7397             Op0.getOpcode() == ISD::XOR) {
7398           TheXor = Op0.getNode();
7399           Equal = true;
7400         }
7401
7402       EVT SetCCVT = N1.getValueType();
7403       if (LegalTypes)
7404         SetCCVT = getSetCCResultType(SetCCVT);
7405       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7406                                    SetCCVT,
7407                                    Op0, Op1,
7408                                    Equal ? ISD::SETEQ : ISD::SETNE);
7409       // Replace the uses of XOR with SETCC
7410       WorkListRemover DeadNodes(*this);
7411       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7412       removeFromWorkList(N1.getNode());
7413       DAG.DeleteNode(N1.getNode());
7414       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7415                          MVT::Other, Chain, SetCC, N2);
7416     }
7417   }
7418
7419   return SDValue();
7420 }
7421
7422 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7423 //
7424 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7425   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7426   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7427
7428   // If N is a constant we could fold this into a fallthrough or unconditional
7429   // branch. However that doesn't happen very often in normal code, because
7430   // Instcombine/SimplifyCFG should have handled the available opportunities.
7431   // If we did this folding here, it would be necessary to update the
7432   // MachineBasicBlock CFG, which is awkward.
7433
7434   // Use SimplifySetCC to simplify SETCC's.
7435   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7436                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7437                                false);
7438   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7439
7440   // fold to a simpler setcc
7441   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7442     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7443                        N->getOperand(0), Simp.getOperand(2),
7444                        Simp.getOperand(0), Simp.getOperand(1),
7445                        N->getOperand(4));
7446
7447   return SDValue();
7448 }
7449
7450 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7451 /// uses N as its base pointer and that N may be folded in the load / store
7452 /// addressing mode.
7453 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7454                                     SelectionDAG &DAG,
7455                                     const TargetLowering &TLI) {
7456   EVT VT;
7457   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7458     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7459       return false;
7460     VT = Use->getValueType(0);
7461   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7462     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7463       return false;
7464     VT = ST->getValue().getValueType();
7465   } else
7466     return false;
7467
7468   TargetLowering::AddrMode AM;
7469   if (N->getOpcode() == ISD::ADD) {
7470     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7471     if (Offset)
7472       // [reg +/- imm]
7473       AM.BaseOffs = Offset->getSExtValue();
7474     else
7475       // [reg +/- reg]
7476       AM.Scale = 1;
7477   } else if (N->getOpcode() == ISD::SUB) {
7478     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7479     if (Offset)
7480       // [reg +/- imm]
7481       AM.BaseOffs = -Offset->getSExtValue();
7482     else
7483       // [reg +/- reg]
7484       AM.Scale = 1;
7485   } else
7486     return false;
7487
7488   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7489 }
7490
7491 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7492 /// pre-indexed load / store when the base pointer is an add or subtract
7493 /// and it has other uses besides the load / store. After the
7494 /// transformation, the new indexed load / store has effectively folded
7495 /// the add / subtract in and all of its other uses are redirected to the
7496 /// new load / store.
7497 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7498   if (Level < AfterLegalizeDAG)
7499     return false;
7500
7501   bool isLoad = true;
7502   SDValue Ptr;
7503   EVT VT;
7504   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7505     if (LD->isIndexed())
7506       return false;
7507     VT = LD->getMemoryVT();
7508     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7509         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7510       return false;
7511     Ptr = LD->getBasePtr();
7512   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7513     if (ST->isIndexed())
7514       return false;
7515     VT = ST->getMemoryVT();
7516     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7517         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7518       return false;
7519     Ptr = ST->getBasePtr();
7520     isLoad = false;
7521   } else {
7522     return false;
7523   }
7524
7525   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7526   // out.  There is no reason to make this a preinc/predec.
7527   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7528       Ptr.getNode()->hasOneUse())
7529     return false;
7530
7531   // Ask the target to do addressing mode selection.
7532   SDValue BasePtr;
7533   SDValue Offset;
7534   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7535   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7536     return false;
7537
7538   // Backends without true r+i pre-indexed forms may need to pass a
7539   // constant base with a variable offset so that constant coercion
7540   // will work with the patterns in canonical form.
7541   bool Swapped = false;
7542   if (isa<ConstantSDNode>(BasePtr)) {
7543     std::swap(BasePtr, Offset);
7544     Swapped = true;
7545   }
7546
7547   // Don't create a indexed load / store with zero offset.
7548   if (isa<ConstantSDNode>(Offset) &&
7549       cast<ConstantSDNode>(Offset)->isNullValue())
7550     return false;
7551
7552   // Try turning it into a pre-indexed load / store except when:
7553   // 1) The new base ptr is a frame index.
7554   // 2) If N is a store and the new base ptr is either the same as or is a
7555   //    predecessor of the value being stored.
7556   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7557   //    that would create a cycle.
7558   // 4) All uses are load / store ops that use it as old base ptr.
7559
7560   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7561   // (plus the implicit offset) to a register to preinc anyway.
7562   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7563     return false;
7564
7565   // Check #2.
7566   if (!isLoad) {
7567     SDValue Val = cast<StoreSDNode>(N)->getValue();
7568     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7569       return false;
7570   }
7571
7572   // If the offset is a constant, there may be other adds of constants that
7573   // can be folded with this one. We should do this to avoid having to keep
7574   // a copy of the original base pointer.
7575   SmallVector<SDNode *, 16> OtherUses;
7576   if (isa<ConstantSDNode>(Offset))
7577     for (SDNode *Use : BasePtr.getNode()->uses()) {
7578       if (Use == Ptr.getNode())
7579         continue;
7580
7581       if (Use->isPredecessorOf(N))
7582         continue;
7583
7584       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7585         OtherUses.clear();
7586         break;
7587       }
7588
7589       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7590       if (Op1.getNode() == BasePtr.getNode())
7591         std::swap(Op0, Op1);
7592       assert(Op0.getNode() == BasePtr.getNode() &&
7593              "Use of ADD/SUB but not an operand");
7594
7595       if (!isa<ConstantSDNode>(Op1)) {
7596         OtherUses.clear();
7597         break;
7598       }
7599
7600       // FIXME: In some cases, we can be smarter about this.
7601       if (Op1.getValueType() != Offset.getValueType()) {
7602         OtherUses.clear();
7603         break;
7604       }
7605
7606       OtherUses.push_back(Use);
7607     }
7608
7609   if (Swapped)
7610     std::swap(BasePtr, Offset);
7611
7612   // Now check for #3 and #4.
7613   bool RealUse = false;
7614
7615   // Caches for hasPredecessorHelper
7616   SmallPtrSet<const SDNode *, 32> Visited;
7617   SmallVector<const SDNode *, 16> Worklist;
7618
7619   for (SDNode *Use : Ptr.getNode()->uses()) {
7620     if (Use == N)
7621       continue;
7622     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7623       return false;
7624
7625     // If Ptr may be folded in addressing mode of other use, then it's
7626     // not profitable to do this transformation.
7627     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7628       RealUse = true;
7629   }
7630
7631   if (!RealUse)
7632     return false;
7633
7634   SDValue Result;
7635   if (isLoad)
7636     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7637                                 BasePtr, Offset, AM);
7638   else
7639     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7640                                  BasePtr, Offset, AM);
7641   ++PreIndexedNodes;
7642   ++NodesCombined;
7643   DEBUG(dbgs() << "\nReplacing.4 ";
7644         N->dump(&DAG);
7645         dbgs() << "\nWith: ";
7646         Result.getNode()->dump(&DAG);
7647         dbgs() << '\n');
7648   WorkListRemover DeadNodes(*this);
7649   if (isLoad) {
7650     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7651     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7652   } else {
7653     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7654   }
7655
7656   // Finally, since the node is now dead, remove it from the graph.
7657   DAG.DeleteNode(N);
7658
7659   if (Swapped)
7660     std::swap(BasePtr, Offset);
7661
7662   // Replace other uses of BasePtr that can be updated to use Ptr
7663   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7664     unsigned OffsetIdx = 1;
7665     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7666       OffsetIdx = 0;
7667     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7668            BasePtr.getNode() && "Expected BasePtr operand");
7669
7670     // We need to replace ptr0 in the following expression:
7671     //   x0 * offset0 + y0 * ptr0 = t0
7672     // knowing that
7673     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7674     //
7675     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7676     // indexed load/store and the expresion that needs to be re-written.
7677     //
7678     // Therefore, we have:
7679     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7680
7681     ConstantSDNode *CN =
7682       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7683     int X0, X1, Y0, Y1;
7684     APInt Offset0 = CN->getAPIntValue();
7685     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7686
7687     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7688     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7689     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7690     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7691
7692     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7693
7694     APInt CNV = Offset0;
7695     if (X0 < 0) CNV = -CNV;
7696     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7697     else CNV = CNV - Offset1;
7698
7699     // We can now generate the new expression.
7700     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7701     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7702
7703     SDValue NewUse = DAG.getNode(Opcode,
7704                                  SDLoc(OtherUses[i]),
7705                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7706     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7707     removeFromWorkList(OtherUses[i]);
7708     DAG.DeleteNode(OtherUses[i]);
7709   }
7710
7711   // Replace the uses of Ptr with uses of the updated base value.
7712   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7713   removeFromWorkList(Ptr.getNode());
7714   DAG.DeleteNode(Ptr.getNode());
7715
7716   return true;
7717 }
7718
7719 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7720 /// add / sub of the base pointer node into a post-indexed load / store.
7721 /// The transformation folded the add / subtract into the new indexed
7722 /// load / store effectively and all of its uses are redirected to the
7723 /// new load / store.
7724 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7725   if (Level < AfterLegalizeDAG)
7726     return false;
7727
7728   bool isLoad = true;
7729   SDValue Ptr;
7730   EVT VT;
7731   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7732     if (LD->isIndexed())
7733       return false;
7734     VT = LD->getMemoryVT();
7735     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7736         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7737       return false;
7738     Ptr = LD->getBasePtr();
7739   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7740     if (ST->isIndexed())
7741       return false;
7742     VT = ST->getMemoryVT();
7743     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7744         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7745       return false;
7746     Ptr = ST->getBasePtr();
7747     isLoad = false;
7748   } else {
7749     return false;
7750   }
7751
7752   if (Ptr.getNode()->hasOneUse())
7753     return false;
7754
7755   for (SDNode *Op : Ptr.getNode()->uses()) {
7756     if (Op == N ||
7757         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7758       continue;
7759
7760     SDValue BasePtr;
7761     SDValue Offset;
7762     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7763     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7764       // Don't create a indexed load / store with zero offset.
7765       if (isa<ConstantSDNode>(Offset) &&
7766           cast<ConstantSDNode>(Offset)->isNullValue())
7767         continue;
7768
7769       // Try turning it into a post-indexed load / store except when
7770       // 1) All uses are load / store ops that use it as base ptr (and
7771       //    it may be folded as addressing mmode).
7772       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7773       //    nor a successor of N. Otherwise, if Op is folded that would
7774       //    create a cycle.
7775
7776       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7777         continue;
7778
7779       // Check for #1.
7780       bool TryNext = false;
7781       for (SDNode *Use : BasePtr.getNode()->uses()) {
7782         if (Use == Ptr.getNode())
7783           continue;
7784
7785         // If all the uses are load / store addresses, then don't do the
7786         // transformation.
7787         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7788           bool RealUse = false;
7789           for (SDNode *UseUse : Use->uses()) {
7790             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7791               RealUse = true;
7792           }
7793
7794           if (!RealUse) {
7795             TryNext = true;
7796             break;
7797           }
7798         }
7799       }
7800
7801       if (TryNext)
7802         continue;
7803
7804       // Check for #2
7805       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7806         SDValue Result = isLoad
7807           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7808                                BasePtr, Offset, AM)
7809           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7810                                 BasePtr, Offset, AM);
7811         ++PostIndexedNodes;
7812         ++NodesCombined;
7813         DEBUG(dbgs() << "\nReplacing.5 ";
7814               N->dump(&DAG);
7815               dbgs() << "\nWith: ";
7816               Result.getNode()->dump(&DAG);
7817               dbgs() << '\n');
7818         WorkListRemover DeadNodes(*this);
7819         if (isLoad) {
7820           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7821           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7822         } else {
7823           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7824         }
7825
7826         // Finally, since the node is now dead, remove it from the graph.
7827         DAG.DeleteNode(N);
7828
7829         // Replace the uses of Use with uses of the updated base value.
7830         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7831                                       Result.getValue(isLoad ? 1 : 0));
7832         removeFromWorkList(Op);
7833         DAG.DeleteNode(Op);
7834         return true;
7835       }
7836     }
7837   }
7838
7839   return false;
7840 }
7841
7842 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7843   LoadSDNode *LD  = cast<LoadSDNode>(N);
7844   SDValue Chain = LD->getChain();
7845   SDValue Ptr   = LD->getBasePtr();
7846
7847   // If load is not volatile and there are no uses of the loaded value (and
7848   // the updated indexed value in case of indexed loads), change uses of the
7849   // chain value into uses of the chain input (i.e. delete the dead load).
7850   if (!LD->isVolatile()) {
7851     if (N->getValueType(1) == MVT::Other) {
7852       // Unindexed loads.
7853       if (!N->hasAnyUseOfValue(0)) {
7854         // It's not safe to use the two value CombineTo variant here. e.g.
7855         // v1, chain2 = load chain1, loc
7856         // v2, chain3 = load chain2, loc
7857         // v3         = add v2, c
7858         // Now we replace use of chain2 with chain1.  This makes the second load
7859         // isomorphic to the one we are deleting, and thus makes this load live.
7860         DEBUG(dbgs() << "\nReplacing.6 ";
7861               N->dump(&DAG);
7862               dbgs() << "\nWith chain: ";
7863               Chain.getNode()->dump(&DAG);
7864               dbgs() << "\n");
7865         WorkListRemover DeadNodes(*this);
7866         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7867
7868         if (N->use_empty()) {
7869           removeFromWorkList(N);
7870           DAG.DeleteNode(N);
7871         }
7872
7873         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7874       }
7875     } else {
7876       // Indexed loads.
7877       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7878       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7879         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7880         DEBUG(dbgs() << "\nReplacing.7 ";
7881               N->dump(&DAG);
7882               dbgs() << "\nWith: ";
7883               Undef.getNode()->dump(&DAG);
7884               dbgs() << " and 2 other values\n");
7885         WorkListRemover DeadNodes(*this);
7886         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7887         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7888                                       DAG.getUNDEF(N->getValueType(1)));
7889         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7890         removeFromWorkList(N);
7891         DAG.DeleteNode(N);
7892         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7893       }
7894     }
7895   }
7896
7897   // If this load is directly stored, replace the load value with the stored
7898   // value.
7899   // TODO: Handle store large -> read small portion.
7900   // TODO: Handle TRUNCSTORE/LOADEXT
7901   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7902     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7903       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7904       if (PrevST->getBasePtr() == Ptr &&
7905           PrevST->getValue().getValueType() == N->getValueType(0))
7906       return CombineTo(N, Chain.getOperand(1), Chain);
7907     }
7908   }
7909
7910   // Try to infer better alignment information than the load already has.
7911   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7912     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7913       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7914         SDValue NewLoad =
7915                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7916                               LD->getValueType(0),
7917                               Chain, Ptr, LD->getPointerInfo(),
7918                               LD->getMemoryVT(),
7919                               LD->isVolatile(), LD->isNonTemporal(), Align,
7920                               LD->getTBAAInfo());
7921         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7922       }
7923     }
7924   }
7925
7926   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7927     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7928 #ifndef NDEBUG
7929   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7930       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7931     UseAA = false;
7932 #endif
7933   if (UseAA && LD->isUnindexed()) {
7934     // Walk up chain skipping non-aliasing memory nodes.
7935     SDValue BetterChain = FindBetterChain(N, Chain);
7936
7937     // If there is a better chain.
7938     if (Chain != BetterChain) {
7939       SDValue ReplLoad;
7940
7941       // Replace the chain to void dependency.
7942       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7943         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7944                                BetterChain, Ptr, LD->getMemOperand());
7945       } else {
7946         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7947                                   LD->getValueType(0),
7948                                   BetterChain, Ptr, LD->getMemoryVT(),
7949                                   LD->getMemOperand());
7950       }
7951
7952       // Create token factor to keep old chain connected.
7953       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7954                                   MVT::Other, Chain, ReplLoad.getValue(1));
7955
7956       // Make sure the new and old chains are cleaned up.
7957       AddToWorkList(Token.getNode());
7958
7959       // Replace uses with load result and token factor. Don't add users
7960       // to work list.
7961       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7962     }
7963   }
7964
7965   // Try transforming N to an indexed load.
7966   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7967     return SDValue(N, 0);
7968
7969   // Try to slice up N to more direct loads if the slices are mapped to
7970   // different register banks or pairing can take place.
7971   if (SliceUpLoad(N))
7972     return SDValue(N, 0);
7973
7974   return SDValue();
7975 }
7976
7977 namespace {
7978 /// \brief Helper structure used to slice a load in smaller loads.
7979 /// Basically a slice is obtained from the following sequence:
7980 /// Origin = load Ty1, Base
7981 /// Shift = srl Ty1 Origin, CstTy Amount
7982 /// Inst = trunc Shift to Ty2
7983 ///
7984 /// Then, it will be rewriten into:
7985 /// Slice = load SliceTy, Base + SliceOffset
7986 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7987 ///
7988 /// SliceTy is deduced from the number of bits that are actually used to
7989 /// build Inst.
7990 struct LoadedSlice {
7991   /// \brief Helper structure used to compute the cost of a slice.
7992   struct Cost {
7993     /// Are we optimizing for code size.
7994     bool ForCodeSize;
7995     /// Various cost.
7996     unsigned Loads;
7997     unsigned Truncates;
7998     unsigned CrossRegisterBanksCopies;
7999     unsigned ZExts;
8000     unsigned Shift;
8001
8002     Cost(bool ForCodeSize = false)
8003         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8004           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8005
8006     /// \brief Get the cost of one isolated slice.
8007     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8008         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8009           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8010       EVT TruncType = LS.Inst->getValueType(0);
8011       EVT LoadedType = LS.getLoadedType();
8012       if (TruncType != LoadedType &&
8013           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8014         ZExts = 1;
8015     }
8016
8017     /// \brief Account for slicing gain in the current cost.
8018     /// Slicing provide a few gains like removing a shift or a
8019     /// truncate. This method allows to grow the cost of the original
8020     /// load with the gain from this slice.
8021     void addSliceGain(const LoadedSlice &LS) {
8022       // Each slice saves a truncate.
8023       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8024       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8025                               LS.Inst->getOperand(0).getValueType()))
8026         ++Truncates;
8027       // If there is a shift amount, this slice gets rid of it.
8028       if (LS.Shift)
8029         ++Shift;
8030       // If this slice can merge a cross register bank copy, account for it.
8031       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8032         ++CrossRegisterBanksCopies;
8033     }
8034
8035     Cost &operator+=(const Cost &RHS) {
8036       Loads += RHS.Loads;
8037       Truncates += RHS.Truncates;
8038       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8039       ZExts += RHS.ZExts;
8040       Shift += RHS.Shift;
8041       return *this;
8042     }
8043
8044     bool operator==(const Cost &RHS) const {
8045       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8046              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8047              ZExts == RHS.ZExts && Shift == RHS.Shift;
8048     }
8049
8050     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8051
8052     bool operator<(const Cost &RHS) const {
8053       // Assume cross register banks copies are as expensive as loads.
8054       // FIXME: Do we want some more target hooks?
8055       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8056       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8057       // Unless we are optimizing for code size, consider the
8058       // expensive operation first.
8059       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8060         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8061       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8062              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8063     }
8064
8065     bool operator>(const Cost &RHS) const { return RHS < *this; }
8066
8067     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8068
8069     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8070   };
8071   // The last instruction that represent the slice. This should be a
8072   // truncate instruction.
8073   SDNode *Inst;
8074   // The original load instruction.
8075   LoadSDNode *Origin;
8076   // The right shift amount in bits from the original load.
8077   unsigned Shift;
8078   // The DAG from which Origin came from.
8079   // This is used to get some contextual information about legal types, etc.
8080   SelectionDAG *DAG;
8081
8082   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8083               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8084       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8085
8086   LoadedSlice(const LoadedSlice &LS)
8087       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8088
8089   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8090   /// \return Result is \p BitWidth and has used bits set to 1 and
8091   ///         not used bits set to 0.
8092   APInt getUsedBits() const {
8093     // Reproduce the trunc(lshr) sequence:
8094     // - Start from the truncated value.
8095     // - Zero extend to the desired bit width.
8096     // - Shift left.
8097     assert(Origin && "No original load to compare against.");
8098     unsigned BitWidth = Origin->getValueSizeInBits(0);
8099     assert(Inst && "This slice is not bound to an instruction");
8100     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8101            "Extracted slice is bigger than the whole type!");
8102     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8103     UsedBits.setAllBits();
8104     UsedBits = UsedBits.zext(BitWidth);
8105     UsedBits <<= Shift;
8106     return UsedBits;
8107   }
8108
8109   /// \brief Get the size of the slice to be loaded in bytes.
8110   unsigned getLoadedSize() const {
8111     unsigned SliceSize = getUsedBits().countPopulation();
8112     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8113     return SliceSize / 8;
8114   }
8115
8116   /// \brief Get the type that will be loaded for this slice.
8117   /// Note: This may not be the final type for the slice.
8118   EVT getLoadedType() const {
8119     assert(DAG && "Missing context");
8120     LLVMContext &Ctxt = *DAG->getContext();
8121     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8122   }
8123
8124   /// \brief Get the alignment of the load used for this slice.
8125   unsigned getAlignment() const {
8126     unsigned Alignment = Origin->getAlignment();
8127     unsigned Offset = getOffsetFromBase();
8128     if (Offset != 0)
8129       Alignment = MinAlign(Alignment, Alignment + Offset);
8130     return Alignment;
8131   }
8132
8133   /// \brief Check if this slice can be rewritten with legal operations.
8134   bool isLegal() const {
8135     // An invalid slice is not legal.
8136     if (!Origin || !Inst || !DAG)
8137       return false;
8138
8139     // Offsets are for indexed load only, we do not handle that.
8140     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8141       return false;
8142
8143     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8144
8145     // Check that the type is legal.
8146     EVT SliceType = getLoadedType();
8147     if (!TLI.isTypeLegal(SliceType))
8148       return false;
8149
8150     // Check that the load is legal for this type.
8151     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8152       return false;
8153
8154     // Check that the offset can be computed.
8155     // 1. Check its type.
8156     EVT PtrType = Origin->getBasePtr().getValueType();
8157     if (PtrType == MVT::Untyped || PtrType.isExtended())
8158       return false;
8159
8160     // 2. Check that it fits in the immediate.
8161     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8162       return false;
8163
8164     // 3. Check that the computation is legal.
8165     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8166       return false;
8167
8168     // Check that the zext is legal if it needs one.
8169     EVT TruncateType = Inst->getValueType(0);
8170     if (TruncateType != SliceType &&
8171         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8172       return false;
8173
8174     return true;
8175   }
8176
8177   /// \brief Get the offset in bytes of this slice in the original chunk of
8178   /// bits.
8179   /// \pre DAG != nullptr.
8180   uint64_t getOffsetFromBase() const {
8181     assert(DAG && "Missing context.");
8182     bool IsBigEndian =
8183         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8184     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8185     uint64_t Offset = Shift / 8;
8186     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8187     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8188            "The size of the original loaded type is not a multiple of a"
8189            " byte.");
8190     // If Offset is bigger than TySizeInBytes, it means we are loading all
8191     // zeros. This should have been optimized before in the process.
8192     assert(TySizeInBytes > Offset &&
8193            "Invalid shift amount for given loaded size");
8194     if (IsBigEndian)
8195       Offset = TySizeInBytes - Offset - getLoadedSize();
8196     return Offset;
8197   }
8198
8199   /// \brief Generate the sequence of instructions to load the slice
8200   /// represented by this object and redirect the uses of this slice to
8201   /// this new sequence of instructions.
8202   /// \pre this->Inst && this->Origin are valid Instructions and this
8203   /// object passed the legal check: LoadedSlice::isLegal returned true.
8204   /// \return The last instruction of the sequence used to load the slice.
8205   SDValue loadSlice() const {
8206     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8207     const SDValue &OldBaseAddr = Origin->getBasePtr();
8208     SDValue BaseAddr = OldBaseAddr;
8209     // Get the offset in that chunk of bytes w.r.t. the endianess.
8210     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8211     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8212     if (Offset) {
8213       // BaseAddr = BaseAddr + Offset.
8214       EVT ArithType = BaseAddr.getValueType();
8215       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8216                               DAG->getConstant(Offset, ArithType));
8217     }
8218
8219     // Create the type of the loaded slice according to its size.
8220     EVT SliceType = getLoadedType();
8221
8222     // Create the load for the slice.
8223     SDValue LastInst = DAG->getLoad(
8224         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8225         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8226         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8227     // If the final type is not the same as the loaded type, this means that
8228     // we have to pad with zero. Create a zero extend for that.
8229     EVT FinalType = Inst->getValueType(0);
8230     if (SliceType != FinalType)
8231       LastInst =
8232           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8233     return LastInst;
8234   }
8235
8236   /// \brief Check if this slice can be merged with an expensive cross register
8237   /// bank copy. E.g.,
8238   /// i = load i32
8239   /// f = bitcast i32 i to float
8240   bool canMergeExpensiveCrossRegisterBankCopy() const {
8241     if (!Inst || !Inst->hasOneUse())
8242       return false;
8243     SDNode *Use = *Inst->use_begin();
8244     if (Use->getOpcode() != ISD::BITCAST)
8245       return false;
8246     assert(DAG && "Missing context");
8247     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8248     EVT ResVT = Use->getValueType(0);
8249     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8250     const TargetRegisterClass *ArgRC =
8251         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8252     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8253       return false;
8254
8255     // At this point, we know that we perform a cross-register-bank copy.
8256     // Check if it is expensive.
8257     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8258     // Assume bitcasts are cheap, unless both register classes do not
8259     // explicitly share a common sub class.
8260     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8261       return false;
8262
8263     // Check if it will be merged with the load.
8264     // 1. Check the alignment constraint.
8265     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8266         ResVT.getTypeForEVT(*DAG->getContext()));
8267
8268     if (RequiredAlignment > getAlignment())
8269       return false;
8270
8271     // 2. Check that the load is a legal operation for that type.
8272     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8273       return false;
8274
8275     // 3. Check that we do not have a zext in the way.
8276     if (Inst->getValueType(0) != getLoadedType())
8277       return false;
8278
8279     return true;
8280   }
8281 };
8282 }
8283
8284 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8285 /// \p UsedBits looks like 0..0 1..1 0..0.
8286 static bool areUsedBitsDense(const APInt &UsedBits) {
8287   // If all the bits are one, this is dense!
8288   if (UsedBits.isAllOnesValue())
8289     return true;
8290
8291   // Get rid of the unused bits on the right.
8292   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8293   // Get rid of the unused bits on the left.
8294   if (NarrowedUsedBits.countLeadingZeros())
8295     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8296   // Check that the chunk of bits is completely used.
8297   return NarrowedUsedBits.isAllOnesValue();
8298 }
8299
8300 /// \brief Check whether or not \p First and \p Second are next to each other
8301 /// in memory. This means that there is no hole between the bits loaded
8302 /// by \p First and the bits loaded by \p Second.
8303 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8304                                      const LoadedSlice &Second) {
8305   assert(First.Origin == Second.Origin && First.Origin &&
8306          "Unable to match different memory origins.");
8307   APInt UsedBits = First.getUsedBits();
8308   assert((UsedBits & Second.getUsedBits()) == 0 &&
8309          "Slices are not supposed to overlap.");
8310   UsedBits |= Second.getUsedBits();
8311   return areUsedBitsDense(UsedBits);
8312 }
8313
8314 /// \brief Adjust the \p GlobalLSCost according to the target
8315 /// paring capabilities and the layout of the slices.
8316 /// \pre \p GlobalLSCost should account for at least as many loads as
8317 /// there is in the slices in \p LoadedSlices.
8318 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8319                                  LoadedSlice::Cost &GlobalLSCost) {
8320   unsigned NumberOfSlices = LoadedSlices.size();
8321   // If there is less than 2 elements, no pairing is possible.
8322   if (NumberOfSlices < 2)
8323     return;
8324
8325   // Sort the slices so that elements that are likely to be next to each
8326   // other in memory are next to each other in the list.
8327   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8328             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8329     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8330     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8331   });
8332   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8333   // First (resp. Second) is the first (resp. Second) potentially candidate
8334   // to be placed in a paired load.
8335   const LoadedSlice *First = nullptr;
8336   const LoadedSlice *Second = nullptr;
8337   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8338                 // Set the beginning of the pair.
8339                                                            First = Second) {
8340
8341     Second = &LoadedSlices[CurrSlice];
8342
8343     // If First is NULL, it means we start a new pair.
8344     // Get to the next slice.
8345     if (!First)
8346       continue;
8347
8348     EVT LoadedType = First->getLoadedType();
8349
8350     // If the types of the slices are different, we cannot pair them.
8351     if (LoadedType != Second->getLoadedType())
8352       continue;
8353
8354     // Check if the target supplies paired loads for this type.
8355     unsigned RequiredAlignment = 0;
8356     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8357       // move to the next pair, this type is hopeless.
8358       Second = nullptr;
8359       continue;
8360     }
8361     // Check if we meet the alignment requirement.
8362     if (RequiredAlignment > First->getAlignment())
8363       continue;
8364
8365     // Check that both loads are next to each other in memory.
8366     if (!areSlicesNextToEachOther(*First, *Second))
8367       continue;
8368
8369     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8370     --GlobalLSCost.Loads;
8371     // Move to the next pair.
8372     Second = nullptr;
8373   }
8374 }
8375
8376 /// \brief Check the profitability of all involved LoadedSlice.
8377 /// Currently, it is considered profitable if there is exactly two
8378 /// involved slices (1) which are (2) next to each other in memory, and
8379 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8380 ///
8381 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8382 /// the elements themselves.
8383 ///
8384 /// FIXME: When the cost model will be mature enough, we can relax
8385 /// constraints (1) and (2).
8386 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8387                                 const APInt &UsedBits, bool ForCodeSize) {
8388   unsigned NumberOfSlices = LoadedSlices.size();
8389   if (StressLoadSlicing)
8390     return NumberOfSlices > 1;
8391
8392   // Check (1).
8393   if (NumberOfSlices != 2)
8394     return false;
8395
8396   // Check (2).
8397   if (!areUsedBitsDense(UsedBits))
8398     return false;
8399
8400   // Check (3).
8401   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8402   // The original code has one big load.
8403   OrigCost.Loads = 1;
8404   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8405     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8406     // Accumulate the cost of all the slices.
8407     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8408     GlobalSlicingCost += SliceCost;
8409
8410     // Account as cost in the original configuration the gain obtained
8411     // with the current slices.
8412     OrigCost.addSliceGain(LS);
8413   }
8414
8415   // If the target supports paired load, adjust the cost accordingly.
8416   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8417   return OrigCost > GlobalSlicingCost;
8418 }
8419
8420 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8421 /// operations, split it in the various pieces being extracted.
8422 ///
8423 /// This sort of thing is introduced by SROA.
8424 /// This slicing takes care not to insert overlapping loads.
8425 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8426 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8427   if (Level < AfterLegalizeDAG)
8428     return false;
8429
8430   LoadSDNode *LD = cast<LoadSDNode>(N);
8431   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8432       !LD->getValueType(0).isInteger())
8433     return false;
8434
8435   // Keep track of already used bits to detect overlapping values.
8436   // In that case, we will just abort the transformation.
8437   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8438
8439   SmallVector<LoadedSlice, 4> LoadedSlices;
8440
8441   // Check if this load is used as several smaller chunks of bits.
8442   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8443   // of computation for each trunc.
8444   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8445        UI != UIEnd; ++UI) {
8446     // Skip the uses of the chain.
8447     if (UI.getUse().getResNo() != 0)
8448       continue;
8449
8450     SDNode *User = *UI;
8451     unsigned Shift = 0;
8452
8453     // Check if this is a trunc(lshr).
8454     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8455         isa<ConstantSDNode>(User->getOperand(1))) {
8456       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8457       User = *User->use_begin();
8458     }
8459
8460     // At this point, User is a Truncate, iff we encountered, trunc or
8461     // trunc(lshr).
8462     if (User->getOpcode() != ISD::TRUNCATE)
8463       return false;
8464
8465     // The width of the type must be a power of 2 and greater than 8-bits.
8466     // Otherwise the load cannot be represented in LLVM IR.
8467     // Moreover, if we shifted with a non-8-bits multiple, the slice
8468     // will be across several bytes. We do not support that.
8469     unsigned Width = User->getValueSizeInBits(0);
8470     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8471       return 0;
8472
8473     // Build the slice for this chain of computations.
8474     LoadedSlice LS(User, LD, Shift, &DAG);
8475     APInt CurrentUsedBits = LS.getUsedBits();
8476
8477     // Check if this slice overlaps with another.
8478     if ((CurrentUsedBits & UsedBits) != 0)
8479       return false;
8480     // Update the bits used globally.
8481     UsedBits |= CurrentUsedBits;
8482
8483     // Check if the new slice would be legal.
8484     if (!LS.isLegal())
8485       return false;
8486
8487     // Record the slice.
8488     LoadedSlices.push_back(LS);
8489   }
8490
8491   // Abort slicing if it does not seem to be profitable.
8492   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8493     return false;
8494
8495   ++SlicedLoads;
8496
8497   // Rewrite each chain to use an independent load.
8498   // By construction, each chain can be represented by a unique load.
8499
8500   // Prepare the argument for the new token factor for all the slices.
8501   SmallVector<SDValue, 8> ArgChains;
8502   for (SmallVectorImpl<LoadedSlice>::const_iterator
8503            LSIt = LoadedSlices.begin(),
8504            LSItEnd = LoadedSlices.end();
8505        LSIt != LSItEnd; ++LSIt) {
8506     SDValue SliceInst = LSIt->loadSlice();
8507     CombineTo(LSIt->Inst, SliceInst, true);
8508     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8509       SliceInst = SliceInst.getOperand(0);
8510     assert(SliceInst->getOpcode() == ISD::LOAD &&
8511            "It takes more than a zext to get to the loaded slice!!");
8512     ArgChains.push_back(SliceInst.getValue(1));
8513   }
8514
8515   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8516                               ArgChains);
8517   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8518   return true;
8519 }
8520
8521 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8522 /// load is having specific bytes cleared out.  If so, return the byte size
8523 /// being masked out and the shift amount.
8524 static std::pair<unsigned, unsigned>
8525 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8526   std::pair<unsigned, unsigned> Result(0, 0);
8527
8528   // Check for the structure we're looking for.
8529   if (V->getOpcode() != ISD::AND ||
8530       !isa<ConstantSDNode>(V->getOperand(1)) ||
8531       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8532     return Result;
8533
8534   // Check the chain and pointer.
8535   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8536   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8537
8538   // The store should be chained directly to the load or be an operand of a
8539   // tokenfactor.
8540   if (LD == Chain.getNode())
8541     ; // ok.
8542   else if (Chain->getOpcode() != ISD::TokenFactor)
8543     return Result; // Fail.
8544   else {
8545     bool isOk = false;
8546     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8547       if (Chain->getOperand(i).getNode() == LD) {
8548         isOk = true;
8549         break;
8550       }
8551     if (!isOk) return Result;
8552   }
8553
8554   // This only handles simple types.
8555   if (V.getValueType() != MVT::i16 &&
8556       V.getValueType() != MVT::i32 &&
8557       V.getValueType() != MVT::i64)
8558     return Result;
8559
8560   // Check the constant mask.  Invert it so that the bits being masked out are
8561   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8562   // follow the sign bit for uniformity.
8563   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8564   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8565   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8566   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8567   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8568   if (NotMaskLZ == 64) return Result;  // All zero mask.
8569
8570   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8571   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8572     return Result;
8573
8574   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8575   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8576     NotMaskLZ -= 64-V.getValueSizeInBits();
8577
8578   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8579   switch (MaskedBytes) {
8580   case 1:
8581   case 2:
8582   case 4: break;
8583   default: return Result; // All one mask, or 5-byte mask.
8584   }
8585
8586   // Verify that the first bit starts at a multiple of mask so that the access
8587   // is aligned the same as the access width.
8588   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8589
8590   Result.first = MaskedBytes;
8591   Result.second = NotMaskTZ/8;
8592   return Result;
8593 }
8594
8595
8596 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8597 /// provides a value as specified by MaskInfo.  If so, replace the specified
8598 /// store with a narrower store of truncated IVal.
8599 static SDNode *
8600 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8601                                 SDValue IVal, StoreSDNode *St,
8602                                 DAGCombiner *DC) {
8603   unsigned NumBytes = MaskInfo.first;
8604   unsigned ByteShift = MaskInfo.second;
8605   SelectionDAG &DAG = DC->getDAG();
8606
8607   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8608   // that uses this.  If not, this is not a replacement.
8609   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8610                                   ByteShift*8, (ByteShift+NumBytes)*8);
8611   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8612
8613   // Check that it is legal on the target to do this.  It is legal if the new
8614   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8615   // legalization.
8616   MVT VT = MVT::getIntegerVT(NumBytes*8);
8617   if (!DC->isTypeLegal(VT))
8618     return nullptr;
8619
8620   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8621   // shifted by ByteShift and truncated down to NumBytes.
8622   if (ByteShift)
8623     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8624                        DAG.getConstant(ByteShift*8,
8625                                     DC->getShiftAmountTy(IVal.getValueType())));
8626
8627   // Figure out the offset for the store and the alignment of the access.
8628   unsigned StOffset;
8629   unsigned NewAlign = St->getAlignment();
8630
8631   if (DAG.getTargetLoweringInfo().isLittleEndian())
8632     StOffset = ByteShift;
8633   else
8634     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8635
8636   SDValue Ptr = St->getBasePtr();
8637   if (StOffset) {
8638     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8639                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8640     NewAlign = MinAlign(NewAlign, StOffset);
8641   }
8642
8643   // Truncate down to the new size.
8644   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8645
8646   ++OpsNarrowed;
8647   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8648                       St->getPointerInfo().getWithOffset(StOffset),
8649                       false, false, NewAlign).getNode();
8650 }
8651
8652
8653 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8654 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8655 /// of the loaded bits, try narrowing the load and store if it would end up
8656 /// being a win for performance or code size.
8657 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8658   StoreSDNode *ST  = cast<StoreSDNode>(N);
8659   if (ST->isVolatile())
8660     return SDValue();
8661
8662   SDValue Chain = ST->getChain();
8663   SDValue Value = ST->getValue();
8664   SDValue Ptr   = ST->getBasePtr();
8665   EVT VT = Value.getValueType();
8666
8667   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8668     return SDValue();
8669
8670   unsigned Opc = Value.getOpcode();
8671
8672   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8673   // is a byte mask indicating a consecutive number of bytes, check to see if
8674   // Y is known to provide just those bytes.  If so, we try to replace the
8675   // load + replace + store sequence with a single (narrower) store, which makes
8676   // the load dead.
8677   if (Opc == ISD::OR) {
8678     std::pair<unsigned, unsigned> MaskedLoad;
8679     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8680     if (MaskedLoad.first)
8681       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8682                                                   Value.getOperand(1), ST,this))
8683         return SDValue(NewST, 0);
8684
8685     // Or is commutative, so try swapping X and Y.
8686     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8687     if (MaskedLoad.first)
8688       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8689                                                   Value.getOperand(0), ST,this))
8690         return SDValue(NewST, 0);
8691   }
8692
8693   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8694       Value.getOperand(1).getOpcode() != ISD::Constant)
8695     return SDValue();
8696
8697   SDValue N0 = Value.getOperand(0);
8698   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8699       Chain == SDValue(N0.getNode(), 1)) {
8700     LoadSDNode *LD = cast<LoadSDNode>(N0);
8701     if (LD->getBasePtr() != Ptr ||
8702         LD->getPointerInfo().getAddrSpace() !=
8703         ST->getPointerInfo().getAddrSpace())
8704       return SDValue();
8705
8706     // Find the type to narrow it the load / op / store to.
8707     SDValue N1 = Value.getOperand(1);
8708     unsigned BitWidth = N1.getValueSizeInBits();
8709     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8710     if (Opc == ISD::AND)
8711       Imm ^= APInt::getAllOnesValue(BitWidth);
8712     if (Imm == 0 || Imm.isAllOnesValue())
8713       return SDValue();
8714     unsigned ShAmt = Imm.countTrailingZeros();
8715     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8716     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8717     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8718     while (NewBW < BitWidth &&
8719            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8720              TLI.isNarrowingProfitable(VT, NewVT))) {
8721       NewBW = NextPowerOf2(NewBW);
8722       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8723     }
8724     if (NewBW >= BitWidth)
8725       return SDValue();
8726
8727     // If the lsb changed does not start at the type bitwidth boundary,
8728     // start at the previous one.
8729     if (ShAmt % NewBW)
8730       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8731     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8732                                    std::min(BitWidth, ShAmt + NewBW));
8733     if ((Imm & Mask) == Imm) {
8734       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8735       if (Opc == ISD::AND)
8736         NewImm ^= APInt::getAllOnesValue(NewBW);
8737       uint64_t PtrOff = ShAmt / 8;
8738       // For big endian targets, we need to adjust the offset to the pointer to
8739       // load the correct bytes.
8740       if (TLI.isBigEndian())
8741         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8742
8743       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8744       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8745       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8746         return SDValue();
8747
8748       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8749                                    Ptr.getValueType(), Ptr,
8750                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8751       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8752                                   LD->getChain(), NewPtr,
8753                                   LD->getPointerInfo().getWithOffset(PtrOff),
8754                                   LD->isVolatile(), LD->isNonTemporal(),
8755                                   LD->isInvariant(), NewAlign,
8756                                   LD->getTBAAInfo());
8757       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8758                                    DAG.getConstant(NewImm, NewVT));
8759       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8760                                    NewVal, NewPtr,
8761                                    ST->getPointerInfo().getWithOffset(PtrOff),
8762                                    false, false, NewAlign);
8763
8764       AddToWorkList(NewPtr.getNode());
8765       AddToWorkList(NewLD.getNode());
8766       AddToWorkList(NewVal.getNode());
8767       WorkListRemover DeadNodes(*this);
8768       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8769       ++OpsNarrowed;
8770       return NewST;
8771     }
8772   }
8773
8774   return SDValue();
8775 }
8776
8777 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8778 /// if the load value isn't used by any other operations, then consider
8779 /// transforming the pair to integer load / store operations if the target
8780 /// deems the transformation profitable.
8781 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8782   StoreSDNode *ST  = cast<StoreSDNode>(N);
8783   SDValue Chain = ST->getChain();
8784   SDValue Value = ST->getValue();
8785   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8786       Value.hasOneUse() &&
8787       Chain == SDValue(Value.getNode(), 1)) {
8788     LoadSDNode *LD = cast<LoadSDNode>(Value);
8789     EVT VT = LD->getMemoryVT();
8790     if (!VT.isFloatingPoint() ||
8791         VT != ST->getMemoryVT() ||
8792         LD->isNonTemporal() ||
8793         ST->isNonTemporal() ||
8794         LD->getPointerInfo().getAddrSpace() != 0 ||
8795         ST->getPointerInfo().getAddrSpace() != 0)
8796       return SDValue();
8797
8798     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8799     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8800         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8801         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8802         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8803       return SDValue();
8804
8805     unsigned LDAlign = LD->getAlignment();
8806     unsigned STAlign = ST->getAlignment();
8807     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8808     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8809     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8810       return SDValue();
8811
8812     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8813                                 LD->getChain(), LD->getBasePtr(),
8814                                 LD->getPointerInfo(),
8815                                 false, false, false, LDAlign);
8816
8817     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8818                                  NewLD, ST->getBasePtr(),
8819                                  ST->getPointerInfo(),
8820                                  false, false, STAlign);
8821
8822     AddToWorkList(NewLD.getNode());
8823     AddToWorkList(NewST.getNode());
8824     WorkListRemover DeadNodes(*this);
8825     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8826     ++LdStFP2Int;
8827     return NewST;
8828   }
8829
8830   return SDValue();
8831 }
8832
8833 /// Helper struct to parse and store a memory address as base + index + offset.
8834 /// We ignore sign extensions when it is safe to do so.
8835 /// The following two expressions are not equivalent. To differentiate we need
8836 /// to store whether there was a sign extension involved in the index
8837 /// computation.
8838 ///  (load (i64 add (i64 copyfromreg %c)
8839 ///                 (i64 signextend (add (i8 load %index)
8840 ///                                      (i8 1))))
8841 /// vs
8842 ///
8843 /// (load (i64 add (i64 copyfromreg %c)
8844 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8845 ///                                         (i32 1)))))
8846 struct BaseIndexOffset {
8847   SDValue Base;
8848   SDValue Index;
8849   int64_t Offset;
8850   bool IsIndexSignExt;
8851
8852   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8853
8854   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8855                   bool IsIndexSignExt) :
8856     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8857
8858   bool equalBaseIndex(const BaseIndexOffset &Other) {
8859     return Other.Base == Base && Other.Index == Index &&
8860       Other.IsIndexSignExt == IsIndexSignExt;
8861   }
8862
8863   /// Parses tree in Ptr for base, index, offset addresses.
8864   static BaseIndexOffset match(SDValue Ptr) {
8865     bool IsIndexSignExt = false;
8866
8867     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8868     // instruction, then it could be just the BASE or everything else we don't
8869     // know how to handle. Just use Ptr as BASE and give up.
8870     if (Ptr->getOpcode() != ISD::ADD)
8871       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8872
8873     // We know that we have at least an ADD instruction. Try to pattern match
8874     // the simple case of BASE + OFFSET.
8875     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8876       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8877       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8878                               IsIndexSignExt);
8879     }
8880
8881     // Inside a loop the current BASE pointer is calculated using an ADD and a
8882     // MUL instruction. In this case Ptr is the actual BASE pointer.
8883     // (i64 add (i64 %array_ptr)
8884     //          (i64 mul (i64 %induction_var)
8885     //                   (i64 %element_size)))
8886     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8887       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8888
8889     // Look at Base + Index + Offset cases.
8890     SDValue Base = Ptr->getOperand(0);
8891     SDValue IndexOffset = Ptr->getOperand(1);
8892
8893     // Skip signextends.
8894     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8895       IndexOffset = IndexOffset->getOperand(0);
8896       IsIndexSignExt = true;
8897     }
8898
8899     // Either the case of Base + Index (no offset) or something else.
8900     if (IndexOffset->getOpcode() != ISD::ADD)
8901       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8902
8903     // Now we have the case of Base + Index + offset.
8904     SDValue Index = IndexOffset->getOperand(0);
8905     SDValue Offset = IndexOffset->getOperand(1);
8906
8907     if (!isa<ConstantSDNode>(Offset))
8908       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8909
8910     // Ignore signextends.
8911     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8912       Index = Index->getOperand(0);
8913       IsIndexSignExt = true;
8914     } else IsIndexSignExt = false;
8915
8916     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8917     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8918   }
8919 };
8920
8921 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8922 /// is located in a sequence of memory operations connected by a chain.
8923 struct MemOpLink {
8924   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8925     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8926   // Ptr to the mem node.
8927   LSBaseSDNode *MemNode;
8928   // Offset from the base ptr.
8929   int64_t OffsetFromBase;
8930   // What is the sequence number of this mem node.
8931   // Lowest mem operand in the DAG starts at zero.
8932   unsigned SequenceNum;
8933 };
8934
8935 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8936   EVT MemVT = St->getMemoryVT();
8937   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8938   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8939     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8940
8941   // Don't merge vectors into wider inputs.
8942   if (MemVT.isVector() || !MemVT.isSimple())
8943     return false;
8944
8945   // Perform an early exit check. Do not bother looking at stored values that
8946   // are not constants or loads.
8947   SDValue StoredVal = St->getValue();
8948   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8949   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8950       !IsLoadSrc)
8951     return false;
8952
8953   // Only look at ends of store sequences.
8954   SDValue Chain = SDValue(St, 1);
8955   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8956     return false;
8957
8958   // This holds the base pointer, index, and the offset in bytes from the base
8959   // pointer.
8960   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8961
8962   // We must have a base and an offset.
8963   if (!BasePtr.Base.getNode())
8964     return false;
8965
8966   // Do not handle stores to undef base pointers.
8967   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8968     return false;
8969
8970   // Save the LoadSDNodes that we find in the chain.
8971   // We need to make sure that these nodes do not interfere with
8972   // any of the store nodes.
8973   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8974
8975   // Save the StoreSDNodes that we find in the chain.
8976   SmallVector<MemOpLink, 8> StoreNodes;
8977
8978   // Walk up the chain and look for nodes with offsets from the same
8979   // base pointer. Stop when reaching an instruction with a different kind
8980   // or instruction which has a different base pointer.
8981   unsigned Seq = 0;
8982   StoreSDNode *Index = St;
8983   while (Index) {
8984     // If the chain has more than one use, then we can't reorder the mem ops.
8985     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8986       break;
8987
8988     // Find the base pointer and offset for this memory node.
8989     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8990
8991     // Check that the base pointer is the same as the original one.
8992     if (!Ptr.equalBaseIndex(BasePtr))
8993       break;
8994
8995     // Check that the alignment is the same.
8996     if (Index->getAlignment() != St->getAlignment())
8997       break;
8998
8999     // The memory operands must not be volatile.
9000     if (Index->isVolatile() || Index->isIndexed())
9001       break;
9002
9003     // No truncation.
9004     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9005       if (St->isTruncatingStore())
9006         break;
9007
9008     // The stored memory type must be the same.
9009     if (Index->getMemoryVT() != MemVT)
9010       break;
9011
9012     // We do not allow unaligned stores because we want to prevent overriding
9013     // stores.
9014     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9015       break;
9016
9017     // We found a potential memory operand to merge.
9018     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9019
9020     // Find the next memory operand in the chain. If the next operand in the
9021     // chain is a store then move up and continue the scan with the next
9022     // memory operand. If the next operand is a load save it and use alias
9023     // information to check if it interferes with anything.
9024     SDNode *NextInChain = Index->getChain().getNode();
9025     while (1) {
9026       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9027         // We found a store node. Use it for the next iteration.
9028         Index = STn;
9029         break;
9030       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9031         if (Ldn->isVolatile()) {
9032           Index = nullptr;
9033           break;
9034         }
9035
9036         // Save the load node for later. Continue the scan.
9037         AliasLoadNodes.push_back(Ldn);
9038         NextInChain = Ldn->getChain().getNode();
9039         continue;
9040       } else {
9041         Index = nullptr;
9042         break;
9043       }
9044     }
9045   }
9046
9047   // Check if there is anything to merge.
9048   if (StoreNodes.size() < 2)
9049     return false;
9050
9051   // Sort the memory operands according to their distance from the base pointer.
9052   std::sort(StoreNodes.begin(), StoreNodes.end(),
9053             [](MemOpLink LHS, MemOpLink RHS) {
9054     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9055            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9056             LHS.SequenceNum > RHS.SequenceNum);
9057   });
9058
9059   // Scan the memory operations on the chain and find the first non-consecutive
9060   // store memory address.
9061   unsigned LastConsecutiveStore = 0;
9062   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9063   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9064
9065     // Check that the addresses are consecutive starting from the second
9066     // element in the list of stores.
9067     if (i > 0) {
9068       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9069       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9070         break;
9071     }
9072
9073     bool Alias = false;
9074     // Check if this store interferes with any of the loads that we found.
9075     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9076       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9077         Alias = true;
9078         break;
9079       }
9080     // We found a load that alias with this store. Stop the sequence.
9081     if (Alias)
9082       break;
9083
9084     // Mark this node as useful.
9085     LastConsecutiveStore = i;
9086   }
9087
9088   // The node with the lowest store address.
9089   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9090
9091   // Store the constants into memory as one consecutive store.
9092   if (!IsLoadSrc) {
9093     unsigned LastLegalType = 0;
9094     unsigned LastLegalVectorType = 0;
9095     bool NonZero = false;
9096     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9097       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9098       SDValue StoredVal = St->getValue();
9099
9100       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9101         NonZero |= !C->isNullValue();
9102       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9103         NonZero |= !C->getConstantFPValue()->isNullValue();
9104       } else {
9105         // Non-constant.
9106         break;
9107       }
9108
9109       // Find a legal type for the constant store.
9110       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9111       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9112       if (TLI.isTypeLegal(StoreTy))
9113         LastLegalType = i+1;
9114       // Or check whether a truncstore is legal.
9115       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9116                TargetLowering::TypePromoteInteger) {
9117         EVT LegalizedStoredValueTy =
9118           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9119         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9120           LastLegalType = i+1;
9121       }
9122
9123       // Find a legal type for the vector store.
9124       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9125       if (TLI.isTypeLegal(Ty))
9126         LastLegalVectorType = i + 1;
9127     }
9128
9129     // We only use vectors if the constant is known to be zero and the
9130     // function is not marked with the noimplicitfloat attribute.
9131     if (NonZero || NoVectors)
9132       LastLegalVectorType = 0;
9133
9134     // Check if we found a legal integer type to store.
9135     if (LastLegalType == 0 && LastLegalVectorType == 0)
9136       return false;
9137
9138     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9139     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9140
9141     // Make sure we have something to merge.
9142     if (NumElem < 2)
9143       return false;
9144
9145     unsigned EarliestNodeUsed = 0;
9146     for (unsigned i=0; i < NumElem; ++i) {
9147       // Find a chain for the new wide-store operand. Notice that some
9148       // of the store nodes that we found may not be selected for inclusion
9149       // in the wide store. The chain we use needs to be the chain of the
9150       // earliest store node which is *used* and replaced by the wide store.
9151       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9152         EarliestNodeUsed = i;
9153     }
9154
9155     // The earliest Node in the DAG.
9156     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9157     SDLoc DL(StoreNodes[0].MemNode);
9158
9159     SDValue StoredVal;
9160     if (UseVector) {
9161       // Find a legal type for the vector store.
9162       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9163       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9164       StoredVal = DAG.getConstant(0, Ty);
9165     } else {
9166       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9167       APInt StoreInt(StoreBW, 0);
9168
9169       // Construct a single integer constant which is made of the smaller
9170       // constant inputs.
9171       bool IsLE = TLI.isLittleEndian();
9172       for (unsigned i = 0; i < NumElem ; ++i) {
9173         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9174         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9175         SDValue Val = St->getValue();
9176         StoreInt<<=ElementSizeBytes*8;
9177         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9178           StoreInt|=C->getAPIntValue().zext(StoreBW);
9179         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9180           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9181         } else {
9182           assert(false && "Invalid constant element type");
9183         }
9184       }
9185
9186       // Create the new Load and Store operations.
9187       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9188       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9189     }
9190
9191     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9192                                     FirstInChain->getBasePtr(),
9193                                     FirstInChain->getPointerInfo(),
9194                                     false, false,
9195                                     FirstInChain->getAlignment());
9196
9197     // Replace the first store with the new store
9198     CombineTo(EarliestOp, NewStore);
9199     // Erase all other stores.
9200     for (unsigned i = 0; i < NumElem ; ++i) {
9201       if (StoreNodes[i].MemNode == EarliestOp)
9202         continue;
9203       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9204       // ReplaceAllUsesWith will replace all uses that existed when it was
9205       // called, but graph optimizations may cause new ones to appear. For
9206       // example, the case in pr14333 looks like
9207       //
9208       //  St's chain -> St -> another store -> X
9209       //
9210       // And the only difference from St to the other store is the chain.
9211       // When we change it's chain to be St's chain they become identical,
9212       // get CSEed and the net result is that X is now a use of St.
9213       // Since we know that St is redundant, just iterate.
9214       while (!St->use_empty())
9215         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9216       removeFromWorkList(St);
9217       DAG.DeleteNode(St);
9218     }
9219
9220     return true;
9221   }
9222
9223   // Below we handle the case of multiple consecutive stores that
9224   // come from multiple consecutive loads. We merge them into a single
9225   // wide load and a single wide store.
9226
9227   // Look for load nodes which are used by the stored values.
9228   SmallVector<MemOpLink, 8> LoadNodes;
9229
9230   // Find acceptable loads. Loads need to have the same chain (token factor),
9231   // must not be zext, volatile, indexed, and they must be consecutive.
9232   BaseIndexOffset LdBasePtr;
9233   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9234     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9235     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9236     if (!Ld) break;
9237
9238     // Loads must only have one use.
9239     if (!Ld->hasNUsesOfValue(1, 0))
9240       break;
9241
9242     // Check that the alignment is the same as the stores.
9243     if (Ld->getAlignment() != St->getAlignment())
9244       break;
9245
9246     // The memory operands must not be volatile.
9247     if (Ld->isVolatile() || Ld->isIndexed())
9248       break;
9249
9250     // We do not accept ext loads.
9251     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9252       break;
9253
9254     // The stored memory type must be the same.
9255     if (Ld->getMemoryVT() != MemVT)
9256       break;
9257
9258     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9259     // If this is not the first ptr that we check.
9260     if (LdBasePtr.Base.getNode()) {
9261       // The base ptr must be the same.
9262       if (!LdPtr.equalBaseIndex(LdBasePtr))
9263         break;
9264     } else {
9265       // Check that all other base pointers are the same as this one.
9266       LdBasePtr = LdPtr;
9267     }
9268
9269     // We found a potential memory operand to merge.
9270     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9271   }
9272
9273   if (LoadNodes.size() < 2)
9274     return false;
9275
9276   // Scan the memory operations on the chain and find the first non-consecutive
9277   // load memory address. These variables hold the index in the store node
9278   // array.
9279   unsigned LastConsecutiveLoad = 0;
9280   // This variable refers to the size and not index in the array.
9281   unsigned LastLegalVectorType = 0;
9282   unsigned LastLegalIntegerType = 0;
9283   StartAddress = LoadNodes[0].OffsetFromBase;
9284   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9285   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9286     // All loads much share the same chain.
9287     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9288       break;
9289
9290     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9291     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9292       break;
9293     LastConsecutiveLoad = i;
9294
9295     // Find a legal type for the vector store.
9296     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9297     if (TLI.isTypeLegal(StoreTy))
9298       LastLegalVectorType = i + 1;
9299
9300     // Find a legal type for the integer store.
9301     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9302     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9303     if (TLI.isTypeLegal(StoreTy))
9304       LastLegalIntegerType = i + 1;
9305     // Or check whether a truncstore and extload is legal.
9306     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9307              TargetLowering::TypePromoteInteger) {
9308       EVT LegalizedStoredValueTy =
9309         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9310       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9311           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9312           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9313           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9314         LastLegalIntegerType = i+1;
9315     }
9316   }
9317
9318   // Only use vector types if the vector type is larger than the integer type.
9319   // If they are the same, use integers.
9320   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9321   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9322
9323   // We add +1 here because the LastXXX variables refer to location while
9324   // the NumElem refers to array/index size.
9325   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9326   NumElem = std::min(LastLegalType, NumElem);
9327
9328   if (NumElem < 2)
9329     return false;
9330
9331   // The earliest Node in the DAG.
9332   unsigned EarliestNodeUsed = 0;
9333   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9334   for (unsigned i=1; i<NumElem; ++i) {
9335     // Find a chain for the new wide-store operand. Notice that some
9336     // of the store nodes that we found may not be selected for inclusion
9337     // in the wide store. The chain we use needs to be the chain of the
9338     // earliest store node which is *used* and replaced by the wide store.
9339     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9340       EarliestNodeUsed = i;
9341   }
9342
9343   // Find if it is better to use vectors or integers to load and store
9344   // to memory.
9345   EVT JointMemOpVT;
9346   if (UseVectorTy) {
9347     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9348   } else {
9349     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9350     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9351   }
9352
9353   SDLoc LoadDL(LoadNodes[0].MemNode);
9354   SDLoc StoreDL(StoreNodes[0].MemNode);
9355
9356   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9357   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9358                                 FirstLoad->getChain(),
9359                                 FirstLoad->getBasePtr(),
9360                                 FirstLoad->getPointerInfo(),
9361                                 false, false, false,
9362                                 FirstLoad->getAlignment());
9363
9364   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9365                                   FirstInChain->getBasePtr(),
9366                                   FirstInChain->getPointerInfo(), false, false,
9367                                   FirstInChain->getAlignment());
9368
9369   // Replace one of the loads with the new load.
9370   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9371   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9372                                 SDValue(NewLoad.getNode(), 1));
9373
9374   // Remove the rest of the load chains.
9375   for (unsigned i = 1; i < NumElem ; ++i) {
9376     // Replace all chain users of the old load nodes with the chain of the new
9377     // load node.
9378     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9379     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9380   }
9381
9382   // Replace the first store with the new store.
9383   CombineTo(EarliestOp, NewStore);
9384   // Erase all other stores.
9385   for (unsigned i = 0; i < NumElem ; ++i) {
9386     // Remove all Store nodes.
9387     if (StoreNodes[i].MemNode == EarliestOp)
9388       continue;
9389     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9390     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9391     removeFromWorkList(St);
9392     DAG.DeleteNode(St);
9393   }
9394
9395   return true;
9396 }
9397
9398 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9399   StoreSDNode *ST  = cast<StoreSDNode>(N);
9400   SDValue Chain = ST->getChain();
9401   SDValue Value = ST->getValue();
9402   SDValue Ptr   = ST->getBasePtr();
9403
9404   // If this is a store of a bit convert, store the input value if the
9405   // resultant store does not need a higher alignment than the original.
9406   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9407       ST->isUnindexed()) {
9408     unsigned OrigAlign = ST->getAlignment();
9409     EVT SVT = Value.getOperand(0).getValueType();
9410     unsigned Align = TLI.getDataLayout()->
9411       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9412     if (Align <= OrigAlign &&
9413         ((!LegalOperations && !ST->isVolatile()) ||
9414          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9415       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9416                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9417                           ST->isNonTemporal(), OrigAlign,
9418                           ST->getTBAAInfo());
9419   }
9420
9421   // Turn 'store undef, Ptr' -> nothing.
9422   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9423     return Chain;
9424
9425   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9426   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9427     // NOTE: If the original store is volatile, this transform must not increase
9428     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9429     // processor operation but an i64 (which is not legal) requires two.  So the
9430     // transform should not be done in this case.
9431     if (Value.getOpcode() != ISD::TargetConstantFP) {
9432       SDValue Tmp;
9433       switch (CFP->getSimpleValueType(0).SimpleTy) {
9434       default: llvm_unreachable("Unknown FP type");
9435       case MVT::f16:    // We don't do this for these yet.
9436       case MVT::f80:
9437       case MVT::f128:
9438       case MVT::ppcf128:
9439         break;
9440       case MVT::f32:
9441         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9442             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9443           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9444                               bitcastToAPInt().getZExtValue(), MVT::i32);
9445           return DAG.getStore(Chain, SDLoc(N), Tmp,
9446                               Ptr, ST->getMemOperand());
9447         }
9448         break;
9449       case MVT::f64:
9450         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9451              !ST->isVolatile()) ||
9452             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9453           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9454                                 getZExtValue(), MVT::i64);
9455           return DAG.getStore(Chain, SDLoc(N), Tmp,
9456                               Ptr, ST->getMemOperand());
9457         }
9458
9459         if (!ST->isVolatile() &&
9460             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9461           // Many FP stores are not made apparent until after legalize, e.g. for
9462           // argument passing.  Since this is so common, custom legalize the
9463           // 64-bit integer store into two 32-bit stores.
9464           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9465           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9466           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9467           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9468
9469           unsigned Alignment = ST->getAlignment();
9470           bool isVolatile = ST->isVolatile();
9471           bool isNonTemporal = ST->isNonTemporal();
9472           const MDNode *TBAAInfo = ST->getTBAAInfo();
9473
9474           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9475                                      Ptr, ST->getPointerInfo(),
9476                                      isVolatile, isNonTemporal,
9477                                      ST->getAlignment(), TBAAInfo);
9478           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9479                             DAG.getConstant(4, Ptr.getValueType()));
9480           Alignment = MinAlign(Alignment, 4U);
9481           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9482                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9483                                      isVolatile, isNonTemporal,
9484                                      Alignment, TBAAInfo);
9485           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9486                              St0, St1);
9487         }
9488
9489         break;
9490       }
9491     }
9492   }
9493
9494   // Try to infer better alignment information than the store already has.
9495   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9496     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9497       if (Align > ST->getAlignment())
9498         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9499                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9500                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9501                                  ST->getTBAAInfo());
9502     }
9503   }
9504
9505   // Try transforming a pair floating point load / store ops to integer
9506   // load / store ops.
9507   SDValue NewST = TransformFPLoadStorePair(N);
9508   if (NewST.getNode())
9509     return NewST;
9510
9511   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9512     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9513 #ifndef NDEBUG
9514   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9515       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9516     UseAA = false;
9517 #endif
9518   if (UseAA && ST->isUnindexed()) {
9519     // Walk up chain skipping non-aliasing memory nodes.
9520     SDValue BetterChain = FindBetterChain(N, Chain);
9521
9522     // If there is a better chain.
9523     if (Chain != BetterChain) {
9524       SDValue ReplStore;
9525
9526       // Replace the chain to avoid dependency.
9527       if (ST->isTruncatingStore()) {
9528         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9529                                       ST->getMemoryVT(), ST->getMemOperand());
9530       } else {
9531         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9532                                  ST->getMemOperand());
9533       }
9534
9535       // Create token to keep both nodes around.
9536       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9537                                   MVT::Other, Chain, ReplStore);
9538
9539       // Make sure the new and old chains are cleaned up.
9540       AddToWorkList(Token.getNode());
9541
9542       // Don't add users to work list.
9543       return CombineTo(N, Token, false);
9544     }
9545   }
9546
9547   // Try transforming N to an indexed store.
9548   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9549     return SDValue(N, 0);
9550
9551   // FIXME: is there such a thing as a truncating indexed store?
9552   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9553       Value.getValueType().isInteger()) {
9554     // See if we can simplify the input to this truncstore with knowledge that
9555     // only the low bits are being used.  For example:
9556     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9557     SDValue Shorter =
9558       GetDemandedBits(Value,
9559                       APInt::getLowBitsSet(
9560                         Value.getValueType().getScalarType().getSizeInBits(),
9561                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9562     AddToWorkList(Value.getNode());
9563     if (Shorter.getNode())
9564       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9565                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9566
9567     // Otherwise, see if we can simplify the operation with
9568     // SimplifyDemandedBits, which only works if the value has a single use.
9569     if (SimplifyDemandedBits(Value,
9570                         APInt::getLowBitsSet(
9571                           Value.getValueType().getScalarType().getSizeInBits(),
9572                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9573       return SDValue(N, 0);
9574   }
9575
9576   // If this is a load followed by a store to the same location, then the store
9577   // is dead/noop.
9578   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9579     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9580         ST->isUnindexed() && !ST->isVolatile() &&
9581         // There can't be any side effects between the load and store, such as
9582         // a call or store.
9583         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9584       // The store is dead, remove it.
9585       return Chain;
9586     }
9587   }
9588
9589   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9590   // truncating store.  We can do this even if this is already a truncstore.
9591   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9592       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9593       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9594                             ST->getMemoryVT())) {
9595     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9596                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9597   }
9598
9599   // Only perform this optimization before the types are legal, because we
9600   // don't want to perform this optimization on every DAGCombine invocation.
9601   if (!LegalTypes) {
9602     bool EverChanged = false;
9603
9604     do {
9605       // There can be multiple store sequences on the same chain.
9606       // Keep trying to merge store sequences until we are unable to do so
9607       // or until we merge the last store on the chain.
9608       bool Changed = MergeConsecutiveStores(ST);
9609       EverChanged |= Changed;
9610       if (!Changed) break;
9611     } while (ST->getOpcode() != ISD::DELETED_NODE);
9612
9613     if (EverChanged)
9614       return SDValue(N, 0);
9615   }
9616
9617   return ReduceLoadOpStoreWidth(N);
9618 }
9619
9620 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9621   SDValue InVec = N->getOperand(0);
9622   SDValue InVal = N->getOperand(1);
9623   SDValue EltNo = N->getOperand(2);
9624   SDLoc dl(N);
9625
9626   // If the inserted element is an UNDEF, just use the input vector.
9627   if (InVal.getOpcode() == ISD::UNDEF)
9628     return InVec;
9629
9630   EVT VT = InVec.getValueType();
9631
9632   // If we can't generate a legal BUILD_VECTOR, exit
9633   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9634     return SDValue();
9635
9636   // Check that we know which element is being inserted
9637   if (!isa<ConstantSDNode>(EltNo))
9638     return SDValue();
9639   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9640
9641   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9642   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9643   // vector elements.
9644   SmallVector<SDValue, 8> Ops;
9645   // Do not combine these two vectors if the output vector will not replace
9646   // the input vector.
9647   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9648     Ops.append(InVec.getNode()->op_begin(),
9649                InVec.getNode()->op_end());
9650   } else if (InVec.getOpcode() == ISD::UNDEF) {
9651     unsigned NElts = VT.getVectorNumElements();
9652     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9653   } else {
9654     return SDValue();
9655   }
9656
9657   // Insert the element
9658   if (Elt < Ops.size()) {
9659     // All the operands of BUILD_VECTOR must have the same type;
9660     // we enforce that here.
9661     EVT OpVT = Ops[0].getValueType();
9662     if (InVal.getValueType() != OpVT)
9663       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9664                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9665                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9666     Ops[Elt] = InVal;
9667   }
9668
9669   // Return the new vector
9670   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9671 }
9672
9673 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9674   // (vextract (scalar_to_vector val, 0) -> val
9675   SDValue InVec = N->getOperand(0);
9676   EVT VT = InVec.getValueType();
9677   EVT NVT = N->getValueType(0);
9678
9679   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9680     // Check if the result type doesn't match the inserted element type. A
9681     // SCALAR_TO_VECTOR may truncate the inserted element and the
9682     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9683     SDValue InOp = InVec.getOperand(0);
9684     if (InOp.getValueType() != NVT) {
9685       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9686       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9687     }
9688     return InOp;
9689   }
9690
9691   SDValue EltNo = N->getOperand(1);
9692   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9693
9694   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9695   // We only perform this optimization before the op legalization phase because
9696   // we may introduce new vector instructions which are not backed by TD
9697   // patterns. For example on AVX, extracting elements from a wide vector
9698   // without using extract_subvector. However, if we can find an underlying
9699   // scalar value, then we can always use that.
9700   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9701       && ConstEltNo) {
9702     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9703     int NumElem = VT.getVectorNumElements();
9704     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9705     // Find the new index to extract from.
9706     int OrigElt = SVOp->getMaskElt(Elt);
9707
9708     // Extracting an undef index is undef.
9709     if (OrigElt == -1)
9710       return DAG.getUNDEF(NVT);
9711
9712     // Select the right vector half to extract from.
9713     SDValue SVInVec;
9714     if (OrigElt < NumElem) {
9715       SVInVec = InVec->getOperand(0);
9716     } else {
9717       SVInVec = InVec->getOperand(1);
9718       OrigElt -= NumElem;
9719     }
9720
9721     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9722       SDValue InOp = SVInVec.getOperand(OrigElt);
9723       if (InOp.getValueType() != NVT) {
9724         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9725         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9726       }
9727
9728       return InOp;
9729     }
9730
9731     // FIXME: We should handle recursing on other vector shuffles and
9732     // scalar_to_vector here as well.
9733
9734     if (!LegalOperations) {
9735       EVT IndexTy = TLI.getVectorIdxTy();
9736       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9737                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9738     }
9739   }
9740
9741   // Perform only after legalization to ensure build_vector / vector_shuffle
9742   // optimizations have already been done.
9743   if (!LegalOperations) return SDValue();
9744
9745   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9746   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9747   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9748
9749   if (ConstEltNo) {
9750     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9751     bool NewLoad = false;
9752     bool BCNumEltsChanged = false;
9753     EVT ExtVT = VT.getVectorElementType();
9754     EVT LVT = ExtVT;
9755
9756     // If the result of load has to be truncated, then it's not necessarily
9757     // profitable.
9758     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9759       return SDValue();
9760
9761     if (InVec.getOpcode() == ISD::BITCAST) {
9762       // Don't duplicate a load with other uses.
9763       if (!InVec.hasOneUse())
9764         return SDValue();
9765
9766       EVT BCVT = InVec.getOperand(0).getValueType();
9767       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9768         return SDValue();
9769       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9770         BCNumEltsChanged = true;
9771       InVec = InVec.getOperand(0);
9772       ExtVT = BCVT.getVectorElementType();
9773       NewLoad = true;
9774     }
9775
9776     LoadSDNode *LN0 = nullptr;
9777     const ShuffleVectorSDNode *SVN = nullptr;
9778     if (ISD::isNormalLoad(InVec.getNode())) {
9779       LN0 = cast<LoadSDNode>(InVec);
9780     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9781                InVec.getOperand(0).getValueType() == ExtVT &&
9782                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9783       // Don't duplicate a load with other uses.
9784       if (!InVec.hasOneUse())
9785         return SDValue();
9786
9787       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9788     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9789       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9790       // =>
9791       // (load $addr+1*size)
9792
9793       // Don't duplicate a load with other uses.
9794       if (!InVec.hasOneUse())
9795         return SDValue();
9796
9797       // If the bit convert changed the number of elements, it is unsafe
9798       // to examine the mask.
9799       if (BCNumEltsChanged)
9800         return SDValue();
9801
9802       // Select the input vector, guarding against out of range extract vector.
9803       unsigned NumElems = VT.getVectorNumElements();
9804       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9805       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9806
9807       if (InVec.getOpcode() == ISD::BITCAST) {
9808         // Don't duplicate a load with other uses.
9809         if (!InVec.hasOneUse())
9810           return SDValue();
9811
9812         InVec = InVec.getOperand(0);
9813       }
9814       if (ISD::isNormalLoad(InVec.getNode())) {
9815         LN0 = cast<LoadSDNode>(InVec);
9816         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9817       }
9818     }
9819
9820     // Make sure we found a non-volatile load and the extractelement is
9821     // the only use.
9822     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9823       return SDValue();
9824
9825     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9826     if (Elt == -1)
9827       return DAG.getUNDEF(LVT);
9828
9829     unsigned Align = LN0->getAlignment();
9830     if (NewLoad) {
9831       // Check the resultant load doesn't need a higher alignment than the
9832       // original load.
9833       unsigned NewAlign =
9834         TLI.getDataLayout()
9835             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9836
9837       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9838         return SDValue();
9839
9840       Align = NewAlign;
9841     }
9842
9843     SDValue NewPtr = LN0->getBasePtr();
9844     unsigned PtrOff = 0;
9845
9846     if (Elt) {
9847       PtrOff = LVT.getSizeInBits() * Elt / 8;
9848       EVT PtrType = NewPtr.getValueType();
9849       if (TLI.isBigEndian())
9850         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9851       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9852                            DAG.getConstant(PtrOff, PtrType));
9853     }
9854
9855     // The replacement we need to do here is a little tricky: we need to
9856     // replace an extractelement of a load with a load.
9857     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9858     // Note that this replacement assumes that the extractvalue is the only
9859     // use of the load; that's okay because we don't want to perform this
9860     // transformation in other cases anyway.
9861     SDValue Load;
9862     SDValue Chain;
9863     if (NVT.bitsGT(LVT)) {
9864       // If the result type of vextract is wider than the load, then issue an
9865       // extending load instead.
9866       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9867         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9868       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9869                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9870                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9871                             Align, LN0->getTBAAInfo());
9872       Chain = Load.getValue(1);
9873     } else {
9874       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9875                          LN0->getPointerInfo().getWithOffset(PtrOff),
9876                          LN0->isVolatile(), LN0->isNonTemporal(),
9877                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9878       Chain = Load.getValue(1);
9879       if (NVT.bitsLT(LVT))
9880         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9881       else
9882         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9883     }
9884     WorkListRemover DeadNodes(*this);
9885     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9886     SDValue To[] = { Load, Chain };
9887     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9888     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9889     // worklist explicitly as well.
9890     AddToWorkList(Load.getNode());
9891     AddUsersToWorkList(Load.getNode()); // Add users too
9892     // Make sure to revisit this node to clean it up; it will usually be dead.
9893     AddToWorkList(N);
9894     return SDValue(N, 0);
9895   }
9896
9897   return SDValue();
9898 }
9899
9900 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9901 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9902   // We perform this optimization post type-legalization because
9903   // the type-legalizer often scalarizes integer-promoted vectors.
9904   // Performing this optimization before may create bit-casts which
9905   // will be type-legalized to complex code sequences.
9906   // We perform this optimization only before the operation legalizer because we
9907   // may introduce illegal operations.
9908   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9909     return SDValue();
9910
9911   unsigned NumInScalars = N->getNumOperands();
9912   SDLoc dl(N);
9913   EVT VT = N->getValueType(0);
9914
9915   // Check to see if this is a BUILD_VECTOR of a bunch of values
9916   // which come from any_extend or zero_extend nodes. If so, we can create
9917   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9918   // optimizations. We do not handle sign-extend because we can't fill the sign
9919   // using shuffles.
9920   EVT SourceType = MVT::Other;
9921   bool AllAnyExt = true;
9922
9923   for (unsigned i = 0; i != NumInScalars; ++i) {
9924     SDValue In = N->getOperand(i);
9925     // Ignore undef inputs.
9926     if (In.getOpcode() == ISD::UNDEF) continue;
9927
9928     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9929     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9930
9931     // Abort if the element is not an extension.
9932     if (!ZeroExt && !AnyExt) {
9933       SourceType = MVT::Other;
9934       break;
9935     }
9936
9937     // The input is a ZeroExt or AnyExt. Check the original type.
9938     EVT InTy = In.getOperand(0).getValueType();
9939
9940     // Check that all of the widened source types are the same.
9941     if (SourceType == MVT::Other)
9942       // First time.
9943       SourceType = InTy;
9944     else if (InTy != SourceType) {
9945       // Multiple income types. Abort.
9946       SourceType = MVT::Other;
9947       break;
9948     }
9949
9950     // Check if all of the extends are ANY_EXTENDs.
9951     AllAnyExt &= AnyExt;
9952   }
9953
9954   // In order to have valid types, all of the inputs must be extended from the
9955   // same source type and all of the inputs must be any or zero extend.
9956   // Scalar sizes must be a power of two.
9957   EVT OutScalarTy = VT.getScalarType();
9958   bool ValidTypes = SourceType != MVT::Other &&
9959                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9960                  isPowerOf2_32(SourceType.getSizeInBits());
9961
9962   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9963   // turn into a single shuffle instruction.
9964   if (!ValidTypes)
9965     return SDValue();
9966
9967   bool isLE = TLI.isLittleEndian();
9968   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9969   assert(ElemRatio > 1 && "Invalid element size ratio");
9970   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9971                                DAG.getConstant(0, SourceType);
9972
9973   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9974   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9975
9976   // Populate the new build_vector
9977   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9978     SDValue Cast = N->getOperand(i);
9979     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9980             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9981             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9982     SDValue In;
9983     if (Cast.getOpcode() == ISD::UNDEF)
9984       In = DAG.getUNDEF(SourceType);
9985     else
9986       In = Cast->getOperand(0);
9987     unsigned Index = isLE ? (i * ElemRatio) :
9988                             (i * ElemRatio + (ElemRatio - 1));
9989
9990     assert(Index < Ops.size() && "Invalid index");
9991     Ops[Index] = In;
9992   }
9993
9994   // The type of the new BUILD_VECTOR node.
9995   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9996   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9997          "Invalid vector size");
9998   // Check if the new vector type is legal.
9999   if (!isTypeLegal(VecVT)) return SDValue();
10000
10001   // Make the new BUILD_VECTOR.
10002   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10003
10004   // The new BUILD_VECTOR node has the potential to be further optimized.
10005   AddToWorkList(BV.getNode());
10006   // Bitcast to the desired type.
10007   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10008 }
10009
10010 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10011   EVT VT = N->getValueType(0);
10012
10013   unsigned NumInScalars = N->getNumOperands();
10014   SDLoc dl(N);
10015
10016   EVT SrcVT = MVT::Other;
10017   unsigned Opcode = ISD::DELETED_NODE;
10018   unsigned NumDefs = 0;
10019
10020   for (unsigned i = 0; i != NumInScalars; ++i) {
10021     SDValue In = N->getOperand(i);
10022     unsigned Opc = In.getOpcode();
10023
10024     if (Opc == ISD::UNDEF)
10025       continue;
10026
10027     // If all scalar values are floats and converted from integers.
10028     if (Opcode == ISD::DELETED_NODE &&
10029         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10030       Opcode = Opc;
10031     }
10032
10033     if (Opc != Opcode)
10034       return SDValue();
10035
10036     EVT InVT = In.getOperand(0).getValueType();
10037
10038     // If all scalar values are typed differently, bail out. It's chosen to
10039     // simplify BUILD_VECTOR of integer types.
10040     if (SrcVT == MVT::Other)
10041       SrcVT = InVT;
10042     if (SrcVT != InVT)
10043       return SDValue();
10044     NumDefs++;
10045   }
10046
10047   // If the vector has just one element defined, it's not worth to fold it into
10048   // a vectorized one.
10049   if (NumDefs < 2)
10050     return SDValue();
10051
10052   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10053          && "Should only handle conversion from integer to float.");
10054   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10055
10056   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10057
10058   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10059     return SDValue();
10060
10061   SmallVector<SDValue, 8> Opnds;
10062   for (unsigned i = 0; i != NumInScalars; ++i) {
10063     SDValue In = N->getOperand(i);
10064
10065     if (In.getOpcode() == ISD::UNDEF)
10066       Opnds.push_back(DAG.getUNDEF(SrcVT));
10067     else
10068       Opnds.push_back(In.getOperand(0));
10069   }
10070   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10071   AddToWorkList(BV.getNode());
10072
10073   return DAG.getNode(Opcode, dl, VT, BV);
10074 }
10075
10076 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10077   unsigned NumInScalars = N->getNumOperands();
10078   SDLoc dl(N);
10079   EVT VT = N->getValueType(0);
10080
10081   // A vector built entirely of undefs is undef.
10082   if (ISD::allOperandsUndef(N))
10083     return DAG.getUNDEF(VT);
10084
10085   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10086   if (V.getNode())
10087     return V;
10088
10089   V = reduceBuildVecConvertToConvertBuildVec(N);
10090   if (V.getNode())
10091     return V;
10092
10093   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10094   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10095   // at most two distinct vectors, turn this into a shuffle node.
10096
10097   // May only combine to shuffle after legalize if shuffle is legal.
10098   if (LegalOperations &&
10099       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10100     return SDValue();
10101
10102   SDValue VecIn1, VecIn2;
10103   for (unsigned i = 0; i != NumInScalars; ++i) {
10104     // Ignore undef inputs.
10105     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10106
10107     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10108     // constant index, bail out.
10109     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10110         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10111       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10112       break;
10113     }
10114
10115     // We allow up to two distinct input vectors.
10116     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10117     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10118       continue;
10119
10120     if (!VecIn1.getNode()) {
10121       VecIn1 = ExtractedFromVec;
10122     } else if (!VecIn2.getNode()) {
10123       VecIn2 = ExtractedFromVec;
10124     } else {
10125       // Too many inputs.
10126       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10127       break;
10128     }
10129   }
10130
10131   // If everything is good, we can make a shuffle operation.
10132   if (VecIn1.getNode()) {
10133     SmallVector<int, 8> Mask;
10134     for (unsigned i = 0; i != NumInScalars; ++i) {
10135       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10136         Mask.push_back(-1);
10137         continue;
10138       }
10139
10140       // If extracting from the first vector, just use the index directly.
10141       SDValue Extract = N->getOperand(i);
10142       SDValue ExtVal = Extract.getOperand(1);
10143       if (Extract.getOperand(0) == VecIn1) {
10144         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10145         if (ExtIndex > VT.getVectorNumElements())
10146           return SDValue();
10147
10148         Mask.push_back(ExtIndex);
10149         continue;
10150       }
10151
10152       // Otherwise, use InIdx + VecSize
10153       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10154       Mask.push_back(Idx+NumInScalars);
10155     }
10156
10157     // We can't generate a shuffle node with mismatched input and output types.
10158     // Attempt to transform a single input vector to the correct type.
10159     if ((VT != VecIn1.getValueType())) {
10160       // We don't support shuffeling between TWO values of different types.
10161       if (VecIn2.getNode())
10162         return SDValue();
10163
10164       // We only support widening of vectors which are half the size of the
10165       // output registers. For example XMM->YMM widening on X86 with AVX.
10166       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10167         return SDValue();
10168
10169       // If the input vector type has a different base type to the output
10170       // vector type, bail out.
10171       if (VecIn1.getValueType().getVectorElementType() !=
10172           VT.getVectorElementType())
10173         return SDValue();
10174
10175       // Widen the input vector by adding undef values.
10176       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10177                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10178     }
10179
10180     // If VecIn2 is unused then change it to undef.
10181     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10182
10183     // Check that we were able to transform all incoming values to the same
10184     // type.
10185     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10186         VecIn1.getValueType() != VT)
10187           return SDValue();
10188
10189     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10190     if (!isTypeLegal(VT))
10191       return SDValue();
10192
10193     // Return the new VECTOR_SHUFFLE node.
10194     SDValue Ops[2];
10195     Ops[0] = VecIn1;
10196     Ops[1] = VecIn2;
10197     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10198   }
10199
10200   return SDValue();
10201 }
10202
10203 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10204   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10205   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10206   // inputs come from at most two distinct vectors, turn this into a shuffle
10207   // node.
10208
10209   // If we only have one input vector, we don't need to do any concatenation.
10210   if (N->getNumOperands() == 1)
10211     return N->getOperand(0);
10212
10213   // Check if all of the operands are undefs.
10214   EVT VT = N->getValueType(0);
10215   if (ISD::allOperandsUndef(N))
10216     return DAG.getUNDEF(VT);
10217
10218   // Optimize concat_vectors where one of the vectors is undef.
10219   if (N->getNumOperands() == 2 &&
10220       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10221     SDValue In = N->getOperand(0);
10222     assert(In.getValueType().isVector() && "Must concat vectors");
10223
10224     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10225     if (In->getOpcode() == ISD::BITCAST &&
10226         !In->getOperand(0)->getValueType(0).isVector()) {
10227       SDValue Scalar = In->getOperand(0);
10228       EVT SclTy = Scalar->getValueType(0);
10229
10230       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10231         return SDValue();
10232
10233       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10234                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10235       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10236         return SDValue();
10237
10238       SDLoc dl = SDLoc(N);
10239       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10240       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10241     }
10242   }
10243
10244   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10245   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10246   if (N->getNumOperands() == 2 &&
10247       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10248       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10249     EVT VT = N->getValueType(0);
10250     SDValue N0 = N->getOperand(0);
10251     SDValue N1 = N->getOperand(1);
10252     SmallVector<SDValue, 8> Opnds;
10253     unsigned BuildVecNumElts =  N0.getNumOperands();
10254
10255     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10256       Opnds.push_back(N0.getOperand(i));
10257     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10258       Opnds.push_back(N1.getOperand(i));
10259
10260     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10261   }
10262
10263   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10264   // nodes often generate nop CONCAT_VECTOR nodes.
10265   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10266   // place the incoming vectors at the exact same location.
10267   SDValue SingleSource = SDValue();
10268   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10269
10270   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10271     SDValue Op = N->getOperand(i);
10272
10273     if (Op.getOpcode() == ISD::UNDEF)
10274       continue;
10275
10276     // Check if this is the identity extract:
10277     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10278       return SDValue();
10279
10280     // Find the single incoming vector for the extract_subvector.
10281     if (SingleSource.getNode()) {
10282       if (Op.getOperand(0) != SingleSource)
10283         return SDValue();
10284     } else {
10285       SingleSource = Op.getOperand(0);
10286
10287       // Check the source type is the same as the type of the result.
10288       // If not, this concat may extend the vector, so we can not
10289       // optimize it away.
10290       if (SingleSource.getValueType() != N->getValueType(0))
10291         return SDValue();
10292     }
10293
10294     unsigned IdentityIndex = i * PartNumElem;
10295     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10296     // The extract index must be constant.
10297     if (!CS)
10298       return SDValue();
10299
10300     // Check that we are reading from the identity index.
10301     if (CS->getZExtValue() != IdentityIndex)
10302       return SDValue();
10303   }
10304
10305   if (SingleSource.getNode())
10306     return SingleSource;
10307
10308   return SDValue();
10309 }
10310
10311 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10312   EVT NVT = N->getValueType(0);
10313   SDValue V = N->getOperand(0);
10314
10315   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10316     // Combine:
10317     //    (extract_subvec (concat V1, V2, ...), i)
10318     // Into:
10319     //    Vi if possible
10320     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10321     // type.
10322     if (V->getOperand(0).getValueType() != NVT)
10323       return SDValue();
10324     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10325     unsigned NumElems = NVT.getVectorNumElements();
10326     assert((Idx % NumElems) == 0 &&
10327            "IDX in concat is not a multiple of the result vector length.");
10328     return V->getOperand(Idx / NumElems);
10329   }
10330
10331   // Skip bitcasting
10332   if (V->getOpcode() == ISD::BITCAST)
10333     V = V.getOperand(0);
10334
10335   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10336     SDLoc dl(N);
10337     // Handle only simple case where vector being inserted and vector
10338     // being extracted are of same type, and are half size of larger vectors.
10339     EVT BigVT = V->getOperand(0).getValueType();
10340     EVT SmallVT = V->getOperand(1).getValueType();
10341     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10342       return SDValue();
10343
10344     // Only handle cases where both indexes are constants with the same type.
10345     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10346     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10347
10348     if (InsIdx && ExtIdx &&
10349         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10350         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10351       // Combine:
10352       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10353       // Into:
10354       //    indices are equal or bit offsets are equal => V1
10355       //    otherwise => (extract_subvec V1, ExtIdx)
10356       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10357           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10358         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10359       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10360                          DAG.getNode(ISD::BITCAST, dl,
10361                                      N->getOperand(0).getValueType(),
10362                                      V->getOperand(0)), N->getOperand(1));
10363     }
10364   }
10365
10366   return SDValue();
10367 }
10368
10369 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10370 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10371   EVT VT = N->getValueType(0);
10372   unsigned NumElts = VT.getVectorNumElements();
10373
10374   SDValue N0 = N->getOperand(0);
10375   SDValue N1 = N->getOperand(1);
10376   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10377
10378   SmallVector<SDValue, 4> Ops;
10379   EVT ConcatVT = N0.getOperand(0).getValueType();
10380   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10381   unsigned NumConcats = NumElts / NumElemsPerConcat;
10382
10383   // Look at every vector that's inserted. We're looking for exact
10384   // subvector-sized copies from a concatenated vector
10385   for (unsigned I = 0; I != NumConcats; ++I) {
10386     // Make sure we're dealing with a copy.
10387     unsigned Begin = I * NumElemsPerConcat;
10388     bool AllUndef = true, NoUndef = true;
10389     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10390       if (SVN->getMaskElt(J) >= 0)
10391         AllUndef = false;
10392       else
10393         NoUndef = false;
10394     }
10395
10396     if (NoUndef) {
10397       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10398         return SDValue();
10399
10400       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10401         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10402           return SDValue();
10403
10404       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10405       if (FirstElt < N0.getNumOperands())
10406         Ops.push_back(N0.getOperand(FirstElt));
10407       else
10408         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10409
10410     } else if (AllUndef) {
10411       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10412     } else { // Mixed with general masks and undefs, can't do optimization.
10413       return SDValue();
10414     }
10415   }
10416
10417   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10418 }
10419
10420 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10421   EVT VT = N->getValueType(0);
10422   unsigned NumElts = VT.getVectorNumElements();
10423
10424   SDValue N0 = N->getOperand(0);
10425   SDValue N1 = N->getOperand(1);
10426
10427   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10428
10429   // Canonicalize shuffle undef, undef -> undef
10430   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10431     return DAG.getUNDEF(VT);
10432
10433   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10434
10435   // Canonicalize shuffle v, v -> v, undef
10436   if (N0 == N1) {
10437     SmallVector<int, 8> NewMask;
10438     for (unsigned i = 0; i != NumElts; ++i) {
10439       int Idx = SVN->getMaskElt(i);
10440       if (Idx >= (int)NumElts) Idx -= NumElts;
10441       NewMask.push_back(Idx);
10442     }
10443     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10444                                 &NewMask[0]);
10445   }
10446
10447   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10448   if (N0.getOpcode() == ISD::UNDEF) {
10449     SmallVector<int, 8> NewMask;
10450     for (unsigned i = 0; i != NumElts; ++i) {
10451       int Idx = SVN->getMaskElt(i);
10452       if (Idx >= 0) {
10453         if (Idx >= (int)NumElts)
10454           Idx -= NumElts;
10455         else
10456           Idx = -1; // remove reference to lhs
10457       }
10458       NewMask.push_back(Idx);
10459     }
10460     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10461                                 &NewMask[0]);
10462   }
10463
10464   // Remove references to rhs if it is undef
10465   if (N1.getOpcode() == ISD::UNDEF) {
10466     bool Changed = false;
10467     SmallVector<int, 8> NewMask;
10468     for (unsigned i = 0; i != NumElts; ++i) {
10469       int Idx = SVN->getMaskElt(i);
10470       if (Idx >= (int)NumElts) {
10471         Idx = -1;
10472         Changed = true;
10473       }
10474       NewMask.push_back(Idx);
10475     }
10476     if (Changed)
10477       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10478   }
10479
10480   // If it is a splat, check if the argument vector is another splat or a
10481   // build_vector with all scalar elements the same.
10482   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10483     SDNode *V = N0.getNode();
10484
10485     // If this is a bit convert that changes the element type of the vector but
10486     // not the number of vector elements, look through it.  Be careful not to
10487     // look though conversions that change things like v4f32 to v2f64.
10488     if (V->getOpcode() == ISD::BITCAST) {
10489       SDValue ConvInput = V->getOperand(0);
10490       if (ConvInput.getValueType().isVector() &&
10491           ConvInput.getValueType().getVectorNumElements() == NumElts)
10492         V = ConvInput.getNode();
10493     }
10494
10495     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10496       assert(V->getNumOperands() == NumElts &&
10497              "BUILD_VECTOR has wrong number of operands");
10498       SDValue Base;
10499       bool AllSame = true;
10500       for (unsigned i = 0; i != NumElts; ++i) {
10501         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10502           Base = V->getOperand(i);
10503           break;
10504         }
10505       }
10506       // Splat of <u, u, u, u>, return <u, u, u, u>
10507       if (!Base.getNode())
10508         return N0;
10509       for (unsigned i = 0; i != NumElts; ++i) {
10510         if (V->getOperand(i) != Base) {
10511           AllSame = false;
10512           break;
10513         }
10514       }
10515       // Splat of <x, x, x, x>, return <x, x, x, x>
10516       if (AllSame)
10517         return N0;
10518     }
10519   }
10520
10521   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10522       Level < AfterLegalizeVectorOps &&
10523       (N1.getOpcode() == ISD::UNDEF ||
10524       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10525        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10526     SDValue V = partitionShuffleOfConcats(N, DAG);
10527
10528     if (V.getNode())
10529       return V;
10530   }
10531
10532   // If this shuffle node is simply a swizzle of another shuffle node,
10533   // and it reverses the swizzle of the previous shuffle then we can
10534   // optimize shuffle(shuffle(x, undef), undef) -> x.
10535   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10536       N1.getOpcode() == ISD::UNDEF) {
10537
10538     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10539
10540     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10541     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10542       return SDValue();
10543
10544     // The incoming shuffle must be of the same type as the result of the
10545     // current shuffle.
10546     assert(OtherSV->getOperand(0).getValueType() == VT &&
10547            "Shuffle types don't match");
10548
10549     for (unsigned i = 0; i != NumElts; ++i) {
10550       int Idx = SVN->getMaskElt(i);
10551       assert(Idx < (int)NumElts && "Index references undef operand");
10552       // Next, this index comes from the first value, which is the incoming
10553       // shuffle. Adopt the incoming index.
10554       if (Idx >= 0)
10555         Idx = OtherSV->getMaskElt(Idx);
10556
10557       // The combined shuffle must map each index to itself.
10558       if (Idx >= 0 && (unsigned)Idx != i)
10559         return SDValue();
10560     }
10561
10562     return OtherSV->getOperand(0);
10563   }
10564
10565   return SDValue();
10566 }
10567
10568 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10569   SDValue N0 = N->getOperand(0);
10570   SDValue N2 = N->getOperand(2);
10571
10572   // If the input vector is a concatenation, and the insert replaces
10573   // one of the halves, we can optimize into a single concat_vectors.
10574   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10575       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10576     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10577     EVT VT = N->getValueType(0);
10578
10579     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10580     // (concat_vectors Z, Y)
10581     if (InsIdx == 0)
10582       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10583                          N->getOperand(1), N0.getOperand(1));
10584
10585     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10586     // (concat_vectors X, Z)
10587     if (InsIdx == VT.getVectorNumElements()/2)
10588       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10589                          N0.getOperand(0), N->getOperand(1));
10590   }
10591
10592   return SDValue();
10593 }
10594
10595 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10596 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10597 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10598 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10599 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10600   EVT VT = N->getValueType(0);
10601   SDLoc dl(N);
10602   SDValue LHS = N->getOperand(0);
10603   SDValue RHS = N->getOperand(1);
10604   if (N->getOpcode() == ISD::AND) {
10605     if (RHS.getOpcode() == ISD::BITCAST)
10606       RHS = RHS.getOperand(0);
10607     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10608       SmallVector<int, 8> Indices;
10609       unsigned NumElts = RHS.getNumOperands();
10610       for (unsigned i = 0; i != NumElts; ++i) {
10611         SDValue Elt = RHS.getOperand(i);
10612         if (!isa<ConstantSDNode>(Elt))
10613           return SDValue();
10614
10615         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10616           Indices.push_back(i);
10617         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10618           Indices.push_back(NumElts);
10619         else
10620           return SDValue();
10621       }
10622
10623       // Let's see if the target supports this vector_shuffle.
10624       EVT RVT = RHS.getValueType();
10625       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10626         return SDValue();
10627
10628       // Return the new VECTOR_SHUFFLE node.
10629       EVT EltVT = RVT.getVectorElementType();
10630       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10631                                      DAG.getConstant(0, EltVT));
10632       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10633       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10634       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10635       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10636     }
10637   }
10638
10639   return SDValue();
10640 }
10641
10642 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10643 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10644   assert(N->getValueType(0).isVector() &&
10645          "SimplifyVBinOp only works on vectors!");
10646
10647   SDValue LHS = N->getOperand(0);
10648   SDValue RHS = N->getOperand(1);
10649   SDValue Shuffle = XformToShuffleWithZero(N);
10650   if (Shuffle.getNode()) return Shuffle;
10651
10652   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10653   // this operation.
10654   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10655       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10656     // Check if both vectors are constants. If not bail out.
10657     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10658           cast<BuildVectorSDNode>(RHS)->isConstant()))
10659       return SDValue();
10660
10661     SmallVector<SDValue, 8> Ops;
10662     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10663       SDValue LHSOp = LHS.getOperand(i);
10664       SDValue RHSOp = RHS.getOperand(i);
10665
10666       // Can't fold divide by zero.
10667       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10668           N->getOpcode() == ISD::FDIV) {
10669         if ((RHSOp.getOpcode() == ISD::Constant &&
10670              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10671             (RHSOp.getOpcode() == ISD::ConstantFP &&
10672              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10673           break;
10674       }
10675
10676       EVT VT = LHSOp.getValueType();
10677       EVT RVT = RHSOp.getValueType();
10678       if (RVT != VT) {
10679         // Integer BUILD_VECTOR operands may have types larger than the element
10680         // size (e.g., when the element type is not legal).  Prior to type
10681         // legalization, the types may not match between the two BUILD_VECTORS.
10682         // Truncate one of the operands to make them match.
10683         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10684           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10685         } else {
10686           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10687           VT = RVT;
10688         }
10689       }
10690       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10691                                    LHSOp, RHSOp);
10692       if (FoldOp.getOpcode() != ISD::UNDEF &&
10693           FoldOp.getOpcode() != ISD::Constant &&
10694           FoldOp.getOpcode() != ISD::ConstantFP)
10695         break;
10696       Ops.push_back(FoldOp);
10697       AddToWorkList(FoldOp.getNode());
10698     }
10699
10700     if (Ops.size() == LHS.getNumOperands())
10701       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10702   }
10703
10704   return SDValue();
10705 }
10706
10707 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10708 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10709   assert(N->getValueType(0).isVector() &&
10710          "SimplifyVUnaryOp only works on vectors!");
10711
10712   SDValue N0 = N->getOperand(0);
10713
10714   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10715     return SDValue();
10716
10717   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10718   SmallVector<SDValue, 8> Ops;
10719   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10720     SDValue Op = N0.getOperand(i);
10721     if (Op.getOpcode() != ISD::UNDEF &&
10722         Op.getOpcode() != ISD::ConstantFP)
10723       break;
10724     EVT EltVT = Op.getValueType();
10725     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10726     if (FoldOp.getOpcode() != ISD::UNDEF &&
10727         FoldOp.getOpcode() != ISD::ConstantFP)
10728       break;
10729     Ops.push_back(FoldOp);
10730     AddToWorkList(FoldOp.getNode());
10731   }
10732
10733   if (Ops.size() != N0.getNumOperands())
10734     return SDValue();
10735
10736   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
10737 }
10738
10739 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10740                                     SDValue N1, SDValue N2){
10741   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10742
10743   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10744                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10745
10746   // If we got a simplified select_cc node back from SimplifySelectCC, then
10747   // break it down into a new SETCC node, and a new SELECT node, and then return
10748   // the SELECT node, since we were called with a SELECT node.
10749   if (SCC.getNode()) {
10750     // Check to see if we got a select_cc back (to turn into setcc/select).
10751     // Otherwise, just return whatever node we got back, like fabs.
10752     if (SCC.getOpcode() == ISD::SELECT_CC) {
10753       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10754                                   N0.getValueType(),
10755                                   SCC.getOperand(0), SCC.getOperand(1),
10756                                   SCC.getOperand(4));
10757       AddToWorkList(SETCC.getNode());
10758       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10759                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10760     }
10761
10762     return SCC;
10763   }
10764   return SDValue();
10765 }
10766
10767 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10768 /// are the two values being selected between, see if we can simplify the
10769 /// select.  Callers of this should assume that TheSelect is deleted if this
10770 /// returns true.  As such, they should return the appropriate thing (e.g. the
10771 /// node) back to the top-level of the DAG combiner loop to avoid it being
10772 /// looked at.
10773 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10774                                     SDValue RHS) {
10775
10776   // Cannot simplify select with vector condition
10777   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10778
10779   // If this is a select from two identical things, try to pull the operation
10780   // through the select.
10781   if (LHS.getOpcode() != RHS.getOpcode() ||
10782       !LHS.hasOneUse() || !RHS.hasOneUse())
10783     return false;
10784
10785   // If this is a load and the token chain is identical, replace the select
10786   // of two loads with a load through a select of the address to load from.
10787   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10788   // constants have been dropped into the constant pool.
10789   if (LHS.getOpcode() == ISD::LOAD) {
10790     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10791     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10792
10793     // Token chains must be identical.
10794     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10795         // Do not let this transformation reduce the number of volatile loads.
10796         LLD->isVolatile() || RLD->isVolatile() ||
10797         // If this is an EXTLOAD, the VT's must match.
10798         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10799         // If this is an EXTLOAD, the kind of extension must match.
10800         (LLD->getExtensionType() != RLD->getExtensionType() &&
10801          // The only exception is if one of the extensions is anyext.
10802          LLD->getExtensionType() != ISD::EXTLOAD &&
10803          RLD->getExtensionType() != ISD::EXTLOAD) ||
10804         // FIXME: this discards src value information.  This is
10805         // over-conservative. It would be beneficial to be able to remember
10806         // both potential memory locations.  Since we are discarding
10807         // src value info, don't do the transformation if the memory
10808         // locations are not in the default address space.
10809         LLD->getPointerInfo().getAddrSpace() != 0 ||
10810         RLD->getPointerInfo().getAddrSpace() != 0 ||
10811         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10812                                       LLD->getBasePtr().getValueType()))
10813       return false;
10814
10815     // Check that the select condition doesn't reach either load.  If so,
10816     // folding this will induce a cycle into the DAG.  If not, this is safe to
10817     // xform, so create a select of the addresses.
10818     SDValue Addr;
10819     if (TheSelect->getOpcode() == ISD::SELECT) {
10820       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10821       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10822           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10823         return false;
10824       // The loads must not depend on one another.
10825       if (LLD->isPredecessorOf(RLD) ||
10826           RLD->isPredecessorOf(LLD))
10827         return false;
10828       Addr = DAG.getSelect(SDLoc(TheSelect),
10829                            LLD->getBasePtr().getValueType(),
10830                            TheSelect->getOperand(0), LLD->getBasePtr(),
10831                            RLD->getBasePtr());
10832     } else {  // Otherwise SELECT_CC
10833       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10834       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10835
10836       if ((LLD->hasAnyUseOfValue(1) &&
10837            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10838           (RLD->hasAnyUseOfValue(1) &&
10839            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10840         return false;
10841
10842       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10843                          LLD->getBasePtr().getValueType(),
10844                          TheSelect->getOperand(0),
10845                          TheSelect->getOperand(1),
10846                          LLD->getBasePtr(), RLD->getBasePtr(),
10847                          TheSelect->getOperand(4));
10848     }
10849
10850     SDValue Load;
10851     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10852       Load = DAG.getLoad(TheSelect->getValueType(0),
10853                          SDLoc(TheSelect),
10854                          // FIXME: Discards pointer and TBAA info.
10855                          LLD->getChain(), Addr, MachinePointerInfo(),
10856                          LLD->isVolatile(), LLD->isNonTemporal(),
10857                          LLD->isInvariant(), LLD->getAlignment());
10858     } else {
10859       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10860                             RLD->getExtensionType() : LLD->getExtensionType(),
10861                             SDLoc(TheSelect),
10862                             TheSelect->getValueType(0),
10863                             // FIXME: Discards pointer and TBAA info.
10864                             LLD->getChain(), Addr, MachinePointerInfo(),
10865                             LLD->getMemoryVT(), LLD->isVolatile(),
10866                             LLD->isNonTemporal(), LLD->getAlignment());
10867     }
10868
10869     // Users of the select now use the result of the load.
10870     CombineTo(TheSelect, Load);
10871
10872     // Users of the old loads now use the new load's chain.  We know the
10873     // old-load value is dead now.
10874     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10875     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10876     return true;
10877   }
10878
10879   return false;
10880 }
10881
10882 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10883 /// where 'cond' is the comparison specified by CC.
10884 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10885                                       SDValue N2, SDValue N3,
10886                                       ISD::CondCode CC, bool NotExtCompare) {
10887   // (x ? y : y) -> y.
10888   if (N2 == N3) return N2;
10889
10890   EVT VT = N2.getValueType();
10891   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10892   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10893   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10894
10895   // Determine if the condition we're dealing with is constant
10896   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10897                               N0, N1, CC, DL, false);
10898   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10899   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10900
10901   // fold select_cc true, x, y -> x
10902   if (SCCC && !SCCC->isNullValue())
10903     return N2;
10904   // fold select_cc false, x, y -> y
10905   if (SCCC && SCCC->isNullValue())
10906     return N3;
10907
10908   // Check to see if we can simplify the select into an fabs node
10909   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10910     // Allow either -0.0 or 0.0
10911     if (CFP->getValueAPF().isZero()) {
10912       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10913       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10914           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10915           N2 == N3.getOperand(0))
10916         return DAG.getNode(ISD::FABS, DL, VT, N0);
10917
10918       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10919       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10920           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10921           N2.getOperand(0) == N3)
10922         return DAG.getNode(ISD::FABS, DL, VT, N3);
10923     }
10924   }
10925
10926   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10927   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10928   // in it.  This is a win when the constant is not otherwise available because
10929   // it replaces two constant pool loads with one.  We only do this if the FP
10930   // type is known to be legal, because if it isn't, then we are before legalize
10931   // types an we want the other legalization to happen first (e.g. to avoid
10932   // messing with soft float) and if the ConstantFP is not legal, because if
10933   // it is legal, we may not need to store the FP constant in a constant pool.
10934   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10935     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10936       if (TLI.isTypeLegal(N2.getValueType()) &&
10937           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10938                TargetLowering::Legal &&
10939            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10940            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10941           // If both constants have multiple uses, then we won't need to do an
10942           // extra load, they are likely around in registers for other users.
10943           (TV->hasOneUse() || FV->hasOneUse())) {
10944         Constant *Elts[] = {
10945           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10946           const_cast<ConstantFP*>(TV->getConstantFPValue())
10947         };
10948         Type *FPTy = Elts[0]->getType();
10949         const DataLayout &TD = *TLI.getDataLayout();
10950
10951         // Create a ConstantArray of the two constants.
10952         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10953         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10954                                             TD.getPrefTypeAlignment(FPTy));
10955         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10956
10957         // Get the offsets to the 0 and 1 element of the array so that we can
10958         // select between them.
10959         SDValue Zero = DAG.getIntPtrConstant(0);
10960         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10961         SDValue One = DAG.getIntPtrConstant(EltSize);
10962
10963         SDValue Cond = DAG.getSetCC(DL,
10964                                     getSetCCResultType(N0.getValueType()),
10965                                     N0, N1, CC);
10966         AddToWorkList(Cond.getNode());
10967         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10968                                           Cond, One, Zero);
10969         AddToWorkList(CstOffset.getNode());
10970         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10971                             CstOffset);
10972         AddToWorkList(CPIdx.getNode());
10973         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10974                            MachinePointerInfo::getConstantPool(), false,
10975                            false, false, Alignment);
10976
10977       }
10978     }
10979
10980   // Check to see if we can perform the "gzip trick", transforming
10981   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10982   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10983       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10984        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10985     EVT XType = N0.getValueType();
10986     EVT AType = N2.getValueType();
10987     if (XType.bitsGE(AType)) {
10988       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10989       // single-bit constant.
10990       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10991         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10992         ShCtV = XType.getSizeInBits()-ShCtV-1;
10993         SDValue ShCt = DAG.getConstant(ShCtV,
10994                                        getShiftAmountTy(N0.getValueType()));
10995         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10996                                     XType, N0, ShCt);
10997         AddToWorkList(Shift.getNode());
10998
10999         if (XType.bitsGT(AType)) {
11000           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11001           AddToWorkList(Shift.getNode());
11002         }
11003
11004         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11005       }
11006
11007       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11008                                   XType, N0,
11009                                   DAG.getConstant(XType.getSizeInBits()-1,
11010                                          getShiftAmountTy(N0.getValueType())));
11011       AddToWorkList(Shift.getNode());
11012
11013       if (XType.bitsGT(AType)) {
11014         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11015         AddToWorkList(Shift.getNode());
11016       }
11017
11018       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11019     }
11020   }
11021
11022   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11023   // where y is has a single bit set.
11024   // A plaintext description would be, we can turn the SELECT_CC into an AND
11025   // when the condition can be materialized as an all-ones register.  Any
11026   // single bit-test can be materialized as an all-ones register with
11027   // shift-left and shift-right-arith.
11028   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11029       N0->getValueType(0) == VT &&
11030       N1C && N1C->isNullValue() &&
11031       N2C && N2C->isNullValue()) {
11032     SDValue AndLHS = N0->getOperand(0);
11033     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11034     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11035       // Shift the tested bit over the sign bit.
11036       APInt AndMask = ConstAndRHS->getAPIntValue();
11037       SDValue ShlAmt =
11038         DAG.getConstant(AndMask.countLeadingZeros(),
11039                         getShiftAmountTy(AndLHS.getValueType()));
11040       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11041
11042       // Now arithmetic right shift it all the way over, so the result is either
11043       // all-ones, or zero.
11044       SDValue ShrAmt =
11045         DAG.getConstant(AndMask.getBitWidth()-1,
11046                         getShiftAmountTy(Shl.getValueType()));
11047       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11048
11049       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11050     }
11051   }
11052
11053   // fold select C, 16, 0 -> shl C, 4
11054   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11055     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11056       TargetLowering::ZeroOrOneBooleanContent) {
11057
11058     // If the caller doesn't want us to simplify this into a zext of a compare,
11059     // don't do it.
11060     if (NotExtCompare && N2C->getAPIntValue() == 1)
11061       return SDValue();
11062
11063     // Get a SetCC of the condition
11064     // NOTE: Don't create a SETCC if it's not legal on this target.
11065     if (!LegalOperations ||
11066         TLI.isOperationLegal(ISD::SETCC,
11067           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11068       SDValue Temp, SCC;
11069       // cast from setcc result type to select result type
11070       if (LegalTypes) {
11071         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11072                             N0, N1, CC);
11073         if (N2.getValueType().bitsLT(SCC.getValueType()))
11074           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11075                                         N2.getValueType());
11076         else
11077           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11078                              N2.getValueType(), SCC);
11079       } else {
11080         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11081         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11082                            N2.getValueType(), SCC);
11083       }
11084
11085       AddToWorkList(SCC.getNode());
11086       AddToWorkList(Temp.getNode());
11087
11088       if (N2C->getAPIntValue() == 1)
11089         return Temp;
11090
11091       // shl setcc result by log2 n2c
11092       return DAG.getNode(
11093           ISD::SHL, DL, N2.getValueType(), Temp,
11094           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11095                           getShiftAmountTy(Temp.getValueType())));
11096     }
11097   }
11098
11099   // Check to see if this is the equivalent of setcc
11100   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11101   // otherwise, go ahead with the folds.
11102   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11103     EVT XType = N0.getValueType();
11104     if (!LegalOperations ||
11105         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11106       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11107       if (Res.getValueType() != VT)
11108         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11109       return Res;
11110     }
11111
11112     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11113     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11114         (!LegalOperations ||
11115          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11116       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11117       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11118                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11119                                        getShiftAmountTy(Ctlz.getValueType())));
11120     }
11121     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11122     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11123       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11124                                   XType, DAG.getConstant(0, XType), N0);
11125       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11126       return DAG.getNode(ISD::SRL, DL, XType,
11127                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11128                          DAG.getConstant(XType.getSizeInBits()-1,
11129                                          getShiftAmountTy(XType)));
11130     }
11131     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11132     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11133       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11134                                  DAG.getConstant(XType.getSizeInBits()-1,
11135                                          getShiftAmountTy(N0.getValueType())));
11136       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11137     }
11138   }
11139
11140   // Check to see if this is an integer abs.
11141   // select_cc setg[te] X,  0,  X, -X ->
11142   // select_cc setgt    X, -1,  X, -X ->
11143   // select_cc setl[te] X,  0, -X,  X ->
11144   // select_cc setlt    X,  1, -X,  X ->
11145   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11146   if (N1C) {
11147     ConstantSDNode *SubC = nullptr;
11148     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11149          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11150         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11151       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11152     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11153               (N1C->isOne() && CC == ISD::SETLT)) &&
11154              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11155       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11156
11157     EVT XType = N0.getValueType();
11158     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11159       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11160                                   N0,
11161                                   DAG.getConstant(XType.getSizeInBits()-1,
11162                                          getShiftAmountTy(N0.getValueType())));
11163       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11164                                 XType, N0, Shift);
11165       AddToWorkList(Shift.getNode());
11166       AddToWorkList(Add.getNode());
11167       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11168     }
11169   }
11170
11171   return SDValue();
11172 }
11173
11174 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11175 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11176                                    SDValue N1, ISD::CondCode Cond,
11177                                    SDLoc DL, bool foldBooleans) {
11178   TargetLowering::DAGCombinerInfo
11179     DagCombineInfo(DAG, Level, false, this);
11180   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11181 }
11182
11183 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11184 /// return a DAG expression to select that will generate the same value by
11185 /// multiplying by a magic number.  See:
11186 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11187 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11188   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11189   if (!C)
11190     return SDValue();
11191
11192   // Avoid division by zero.
11193   if (!C->getAPIntValue())
11194     return SDValue();
11195
11196   std::vector<SDNode*> Built;
11197   SDValue S =
11198       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11199
11200   for (SDNode *N : Built)
11201     AddToWorkList(N);
11202   return S;
11203 }
11204
11205 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11206 /// return a DAG expression to select that will generate the same value by
11207 /// multiplying by a magic number.  See:
11208 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11209 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11210   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11211   if (!C)
11212     return SDValue();
11213
11214   // Avoid division by zero.
11215   if (!C->getAPIntValue())
11216     return SDValue();
11217
11218   std::vector<SDNode*> Built;
11219   SDValue S =
11220       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11221
11222   for (SDNode *N : Built)
11223     AddToWorkList(N);
11224   return S;
11225 }
11226
11227 /// FindBaseOffset - Return true if base is a frame index, which is known not
11228 // to alias with anything but itself.  Provides base object and offset as
11229 // results.
11230 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11231                            const GlobalValue *&GV, const void *&CV) {
11232   // Assume it is a primitive operation.
11233   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11234
11235   // If it's an adding a simple constant then integrate the offset.
11236   if (Base.getOpcode() == ISD::ADD) {
11237     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11238       Base = Base.getOperand(0);
11239       Offset += C->getZExtValue();
11240     }
11241   }
11242
11243   // Return the underlying GlobalValue, and update the Offset.  Return false
11244   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11245   // by multiple nodes with different offsets.
11246   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11247     GV = G->getGlobal();
11248     Offset += G->getOffset();
11249     return false;
11250   }
11251
11252   // Return the underlying Constant value, and update the Offset.  Return false
11253   // for ConstantSDNodes since the same constant pool entry may be represented
11254   // by multiple nodes with different offsets.
11255   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11256     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11257                                          : (const void *)C->getConstVal();
11258     Offset += C->getOffset();
11259     return false;
11260   }
11261   // If it's any of the following then it can't alias with anything but itself.
11262   return isa<FrameIndexSDNode>(Base);
11263 }
11264
11265 /// isAlias - Return true if there is any possibility that the two addresses
11266 /// overlap.
11267 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11268   // If they are the same then they must be aliases.
11269   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11270
11271   // If they are both volatile then they cannot be reordered.
11272   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11273
11274   // Gather base node and offset information.
11275   SDValue Base1, Base2;
11276   int64_t Offset1, Offset2;
11277   const GlobalValue *GV1, *GV2;
11278   const void *CV1, *CV2;
11279   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11280                                       Base1, Offset1, GV1, CV1);
11281   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11282                                       Base2, Offset2, GV2, CV2);
11283
11284   // If they have a same base address then check to see if they overlap.
11285   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11286     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11287              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11288
11289   // It is possible for different frame indices to alias each other, mostly
11290   // when tail call optimization reuses return address slots for arguments.
11291   // To catch this case, look up the actual index of frame indices to compute
11292   // the real alias relationship.
11293   if (isFrameIndex1 && isFrameIndex2) {
11294     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11295     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11296     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11297     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11298              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11299   }
11300
11301   // Otherwise, if we know what the bases are, and they aren't identical, then
11302   // we know they cannot alias.
11303   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11304     return false;
11305
11306   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11307   // compared to the size and offset of the access, we may be able to prove they
11308   // do not alias.  This check is conservative for now to catch cases created by
11309   // splitting vector types.
11310   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11311       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11312       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11313        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11314       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11315     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11316     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11317
11318     // There is no overlap between these relatively aligned accesses of similar
11319     // size, return no alias.
11320     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11321         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11322       return false;
11323   }
11324
11325   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11326     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11327 #ifndef NDEBUG
11328   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11329       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11330     UseAA = false;
11331 #endif
11332   if (UseAA &&
11333       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11334     // Use alias analysis information.
11335     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11336                                  Op1->getSrcValueOffset());
11337     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11338         Op0->getSrcValueOffset() - MinOffset;
11339     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11340         Op1->getSrcValueOffset() - MinOffset;
11341     AliasAnalysis::AliasResult AAResult =
11342         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11343                                          Overlap1,
11344                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11345                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11346                                          Overlap2,
11347                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11348     if (AAResult == AliasAnalysis::NoAlias)
11349       return false;
11350   }
11351
11352   // Otherwise we have to assume they alias.
11353   return true;
11354 }
11355
11356 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11357 /// looking for aliasing nodes and adding them to the Aliases vector.
11358 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11359                                    SmallVectorImpl<SDValue> &Aliases) {
11360   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11361   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11362
11363   // Get alias information for node.
11364   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11365
11366   // Starting off.
11367   Chains.push_back(OriginalChain);
11368   unsigned Depth = 0;
11369
11370   // Look at each chain and determine if it is an alias.  If so, add it to the
11371   // aliases list.  If not, then continue up the chain looking for the next
11372   // candidate.
11373   while (!Chains.empty()) {
11374     SDValue Chain = Chains.back();
11375     Chains.pop_back();
11376
11377     // For TokenFactor nodes, look at each operand and only continue up the
11378     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11379     // find more and revert to original chain since the xform is unlikely to be
11380     // profitable.
11381     //
11382     // FIXME: The depth check could be made to return the last non-aliasing
11383     // chain we found before we hit a tokenfactor rather than the original
11384     // chain.
11385     if (Depth > 6 || Aliases.size() == 2) {
11386       Aliases.clear();
11387       Aliases.push_back(OriginalChain);
11388       return;
11389     }
11390
11391     // Don't bother if we've been before.
11392     if (!Visited.insert(Chain.getNode()))
11393       continue;
11394
11395     switch (Chain.getOpcode()) {
11396     case ISD::EntryToken:
11397       // Entry token is ideal chain operand, but handled in FindBetterChain.
11398       break;
11399
11400     case ISD::LOAD:
11401     case ISD::STORE: {
11402       // Get alias information for Chain.
11403       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11404           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11405
11406       // If chain is alias then stop here.
11407       if (!(IsLoad && IsOpLoad) &&
11408           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11409         Aliases.push_back(Chain);
11410       } else {
11411         // Look further up the chain.
11412         Chains.push_back(Chain.getOperand(0));
11413         ++Depth;
11414       }
11415       break;
11416     }
11417
11418     case ISD::TokenFactor:
11419       // We have to check each of the operands of the token factor for "small"
11420       // token factors, so we queue them up.  Adding the operands to the queue
11421       // (stack) in reverse order maintains the original order and increases the
11422       // likelihood that getNode will find a matching token factor (CSE.)
11423       if (Chain.getNumOperands() > 16) {
11424         Aliases.push_back(Chain);
11425         break;
11426       }
11427       for (unsigned n = Chain.getNumOperands(); n;)
11428         Chains.push_back(Chain.getOperand(--n));
11429       ++Depth;
11430       break;
11431
11432     default:
11433       // For all other instructions we will just have to take what we can get.
11434       Aliases.push_back(Chain);
11435       break;
11436     }
11437   }
11438
11439   // We need to be careful here to also search for aliases through the
11440   // value operand of a store, etc. Consider the following situation:
11441   //   Token1 = ...
11442   //   L1 = load Token1, %52
11443   //   S1 = store Token1, L1, %51
11444   //   L2 = load Token1, %52+8
11445   //   S2 = store Token1, L2, %51+8
11446   //   Token2 = Token(S1, S2)
11447   //   L3 = load Token2, %53
11448   //   S3 = store Token2, L3, %52
11449   //   L4 = load Token2, %53+8
11450   //   S4 = store Token2, L4, %52+8
11451   // If we search for aliases of S3 (which loads address %52), and we look
11452   // only through the chain, then we'll miss the trivial dependence on L1
11453   // (which also loads from %52). We then might change all loads and
11454   // stores to use Token1 as their chain operand, which could result in
11455   // copying %53 into %52 before copying %52 into %51 (which should
11456   // happen first).
11457   //
11458   // The problem is, however, that searching for such data dependencies
11459   // can become expensive, and the cost is not directly related to the
11460   // chain depth. Instead, we'll rule out such configurations here by
11461   // insisting that we've visited all chain users (except for users
11462   // of the original chain, which is not necessary). When doing this,
11463   // we need to look through nodes we don't care about (otherwise, things
11464   // like register copies will interfere with trivial cases).
11465
11466   SmallVector<const SDNode *, 16> Worklist;
11467   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11468        IE = Visited.end(); I != IE; ++I)
11469     if (*I != OriginalChain.getNode())
11470       Worklist.push_back(*I);
11471
11472   while (!Worklist.empty()) {
11473     const SDNode *M = Worklist.pop_back_val();
11474
11475     // We have already visited M, and want to make sure we've visited any uses
11476     // of M that we care about. For uses that we've not visisted, and don't
11477     // care about, queue them to the worklist.
11478
11479     for (SDNode::use_iterator UI = M->use_begin(),
11480          UIE = M->use_end(); UI != UIE; ++UI)
11481       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11482         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11483           // We've not visited this use, and we care about it (it could have an
11484           // ordering dependency with the original node).
11485           Aliases.clear();
11486           Aliases.push_back(OriginalChain);
11487           return;
11488         }
11489
11490         // We've not visited this use, but we don't care about it. Mark it as
11491         // visited and enqueue it to the worklist.
11492         Worklist.push_back(*UI);
11493       }
11494   }
11495 }
11496
11497 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11498 /// for a better chain (aliasing node.)
11499 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11500   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11501
11502   // Accumulate all the aliases to this node.
11503   GatherAllAliases(N, OldChain, Aliases);
11504
11505   // If no operands then chain to entry token.
11506   if (Aliases.size() == 0)
11507     return DAG.getEntryNode();
11508
11509   // If a single operand then chain to it.  We don't need to revisit it.
11510   if (Aliases.size() == 1)
11511     return Aliases[0];
11512
11513   // Construct a custom tailored token factor.
11514   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11515 }
11516
11517 // SelectionDAG::Combine - This is the entry point for the file.
11518 //
11519 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11520                            CodeGenOpt::Level OptLevel) {
11521   /// run - This is the main entry point to this class.
11522   ///
11523   DAGCombiner(*this, AA, OptLevel).Run(Level);
11524 }