7850bc25892034240a74ae40e33c19dc32956f34
[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     return BV->getConstantSplatValue();
649
650   return nullptr;
651 }
652
653 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
654                                     SDValue N0, SDValue N1) {
655   EVT VT = N0.getValueType();
656   if (N0.getOpcode() == Opc) {
657     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
658       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
659         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
660         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
661         if (!OpNode.getNode())
662           return SDValue();
663         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
664       }
665       if (N0.hasOneUse()) {
666         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
667         // use
668         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
669         if (!OpNode.getNode())
670           return SDValue();
671         AddToWorkList(OpNode.getNode());
672         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
673       }
674     }
675   }
676
677   if (N1.getOpcode() == Opc) {
678     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
679       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
680         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
681         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
682         if (!OpNode.getNode())
683           return SDValue();
684         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
685       }
686       if (N1.hasOneUse()) {
687         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
688         // use
689         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
690         if (!OpNode.getNode())
691           return SDValue();
692         AddToWorkList(OpNode.getNode());
693         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
694       }
695     }
696   }
697
698   return SDValue();
699 }
700
701 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
702                                bool AddTo) {
703   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
704   ++NodesCombined;
705   DEBUG(dbgs() << "\nReplacing.1 ";
706         N->dump(&DAG);
707         dbgs() << "\nWith: ";
708         To[0].getNode()->dump(&DAG);
709         dbgs() << " and " << NumTo-1 << " other values\n";
710         for (unsigned i = 0, e = NumTo; i != e; ++i)
711           assert((!To[i].getNode() ||
712                   N->getValueType(i) == To[i].getValueType()) &&
713                  "Cannot combine value to value of different type!"));
714   WorkListRemover DeadNodes(*this);
715   DAG.ReplaceAllUsesWith(N, To);
716   if (AddTo) {
717     // Push the new nodes and any users onto the worklist
718     for (unsigned i = 0, e = NumTo; i != e; ++i) {
719       if (To[i].getNode()) {
720         AddToWorkList(To[i].getNode());
721         AddUsersToWorkList(To[i].getNode());
722       }
723     }
724   }
725
726   // Finally, if the node is now dead, remove it from the graph.  The node
727   // may not be dead if the replacement process recursively simplified to
728   // something else needing this node.
729   if (N->use_empty()) {
730     // Nodes can be reintroduced into the worklist.  Make sure we do not
731     // process a node that has been replaced.
732     removeFromWorkList(N);
733
734     // Finally, since the node is now dead, remove it from the graph.
735     DAG.DeleteNode(N);
736   }
737   return SDValue(N, 0);
738 }
739
740 void DAGCombiner::
741 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
742   // Replace all uses.  If any nodes become isomorphic to other nodes and
743   // are deleted, make sure to remove them from our worklist.
744   WorkListRemover DeadNodes(*this);
745   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
746
747   // Push the new node and any (possibly new) users onto the worklist.
748   AddToWorkList(TLO.New.getNode());
749   AddUsersToWorkList(TLO.New.getNode());
750
751   // Finally, if the node is now dead, remove it from the graph.  The node
752   // may not be dead if the replacement process recursively simplified to
753   // something else needing this node.
754   if (TLO.Old.getNode()->use_empty()) {
755     removeFromWorkList(TLO.Old.getNode());
756
757     // If the operands of this node are only used by the node, they will now
758     // be dead.  Make sure to visit them first to delete dead nodes early.
759     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
760       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
761         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
762
763     DAG.DeleteNode(TLO.Old.getNode());
764   }
765 }
766
767 /// SimplifyDemandedBits - Check the specified integer node value to see if
768 /// it can be simplified or if things it uses can be simplified by bit
769 /// propagation.  If so, return true.
770 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
771   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
772   APInt KnownZero, KnownOne;
773   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
774     return false;
775
776   // Revisit the node.
777   AddToWorkList(Op.getNode());
778
779   // Replace the old value with the new one.
780   ++NodesCombined;
781   DEBUG(dbgs() << "\nReplacing.2 ";
782         TLO.Old.getNode()->dump(&DAG);
783         dbgs() << "\nWith: ";
784         TLO.New.getNode()->dump(&DAG);
785         dbgs() << '\n');
786
787   CommitTargetLoweringOpt(TLO);
788   return true;
789 }
790
791 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
792   SDLoc dl(Load);
793   EVT VT = Load->getValueType(0);
794   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
795
796   DEBUG(dbgs() << "\nReplacing.9 ";
797         Load->dump(&DAG);
798         dbgs() << "\nWith: ";
799         Trunc.getNode()->dump(&DAG);
800         dbgs() << '\n');
801   WorkListRemover DeadNodes(*this);
802   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
803   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
804   removeFromWorkList(Load);
805   DAG.DeleteNode(Load);
806   AddToWorkList(Trunc.getNode());
807 }
808
809 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
810   Replace = false;
811   SDLoc dl(Op);
812   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
813     EVT MemVT = LD->getMemoryVT();
814     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
815       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
816                                                   : ISD::EXTLOAD)
817       : LD->getExtensionType();
818     Replace = true;
819     return DAG.getExtLoad(ExtType, dl, PVT,
820                           LD->getChain(), LD->getBasePtr(),
821                           MemVT, LD->getMemOperand());
822   }
823
824   unsigned Opc = Op.getOpcode();
825   switch (Opc) {
826   default: break;
827   case ISD::AssertSext:
828     return DAG.getNode(ISD::AssertSext, dl, PVT,
829                        SExtPromoteOperand(Op.getOperand(0), PVT),
830                        Op.getOperand(1));
831   case ISD::AssertZext:
832     return DAG.getNode(ISD::AssertZext, dl, PVT,
833                        ZExtPromoteOperand(Op.getOperand(0), PVT),
834                        Op.getOperand(1));
835   case ISD::Constant: {
836     unsigned ExtOpc =
837       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
838     return DAG.getNode(ExtOpc, dl, PVT, Op);
839   }
840   }
841
842   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
843     return SDValue();
844   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
845 }
846
847 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
848   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
849     return SDValue();
850   EVT OldVT = Op.getValueType();
851   SDLoc dl(Op);
852   bool Replace = false;
853   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
854   if (!NewOp.getNode())
855     return SDValue();
856   AddToWorkList(NewOp.getNode());
857
858   if (Replace)
859     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
860   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
861                      DAG.getValueType(OldVT));
862 }
863
864 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
865   EVT OldVT = Op.getValueType();
866   SDLoc dl(Op);
867   bool Replace = false;
868   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
869   if (!NewOp.getNode())
870     return SDValue();
871   AddToWorkList(NewOp.getNode());
872
873   if (Replace)
874     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
875   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
876 }
877
878 /// PromoteIntBinOp - Promote the specified integer binary operation if the
879 /// target indicates it is beneficial. e.g. On x86, it's usually better to
880 /// promote i16 operations to i32 since i16 instructions are longer.
881 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
882   if (!LegalOperations)
883     return SDValue();
884
885   EVT VT = Op.getValueType();
886   if (VT.isVector() || !VT.isInteger())
887     return SDValue();
888
889   // If operation type is 'undesirable', e.g. i16 on x86, consider
890   // promoting it.
891   unsigned Opc = Op.getOpcode();
892   if (TLI.isTypeDesirableForOp(Opc, VT))
893     return SDValue();
894
895   EVT PVT = VT;
896   // Consult target whether it is a good idea to promote this operation and
897   // what's the right type to promote it to.
898   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
899     assert(PVT != VT && "Don't know what type to promote to!");
900
901     bool Replace0 = false;
902     SDValue N0 = Op.getOperand(0);
903     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
904     if (!NN0.getNode())
905       return SDValue();
906
907     bool Replace1 = false;
908     SDValue N1 = Op.getOperand(1);
909     SDValue NN1;
910     if (N0 == N1)
911       NN1 = NN0;
912     else {
913       NN1 = PromoteOperand(N1, PVT, Replace1);
914       if (!NN1.getNode())
915         return SDValue();
916     }
917
918     AddToWorkList(NN0.getNode());
919     if (NN1.getNode())
920       AddToWorkList(NN1.getNode());
921
922     if (Replace0)
923       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
924     if (Replace1)
925       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
926
927     DEBUG(dbgs() << "\nPromoting ";
928           Op.getNode()->dump(&DAG));
929     SDLoc dl(Op);
930     return DAG.getNode(ISD::TRUNCATE, dl, VT,
931                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
932   }
933   return SDValue();
934 }
935
936 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
937 /// target indicates it is beneficial. e.g. On x86, it's usually better to
938 /// promote i16 operations to i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
940   if (!LegalOperations)
941     return SDValue();
942
943   EVT VT = Op.getValueType();
944   if (VT.isVector() || !VT.isInteger())
945     return SDValue();
946
947   // If operation type is 'undesirable', e.g. i16 on x86, consider
948   // promoting it.
949   unsigned Opc = Op.getOpcode();
950   if (TLI.isTypeDesirableForOp(Opc, VT))
951     return SDValue();
952
953   EVT PVT = VT;
954   // Consult target whether it is a good idea to promote this operation and
955   // what's the right type to promote it to.
956   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957     assert(PVT != VT && "Don't know what type to promote to!");
958
959     bool Replace = false;
960     SDValue N0 = Op.getOperand(0);
961     if (Opc == ISD::SRA)
962       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
963     else if (Opc == ISD::SRL)
964       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
965     else
966       N0 = PromoteOperand(N0, PVT, Replace);
967     if (!N0.getNode())
968       return SDValue();
969
970     AddToWorkList(N0.getNode());
971     if (Replace)
972       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
973
974     DEBUG(dbgs() << "\nPromoting ";
975           Op.getNode()->dump(&DAG));
976     SDLoc dl(Op);
977     return DAG.getNode(ISD::TRUNCATE, dl, VT,
978                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
979   }
980   return SDValue();
981 }
982
983 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
984   if (!LegalOperations)
985     return SDValue();
986
987   EVT VT = Op.getValueType();
988   if (VT.isVector() || !VT.isInteger())
989     return SDValue();
990
991   // If operation type is 'undesirable', e.g. i16 on x86, consider
992   // promoting it.
993   unsigned Opc = Op.getOpcode();
994   if (TLI.isTypeDesirableForOp(Opc, VT))
995     return SDValue();
996
997   EVT PVT = VT;
998   // Consult target whether it is a good idea to promote this operation and
999   // what's the right type to promote it to.
1000   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1001     assert(PVT != VT && "Don't know what type to promote to!");
1002     // fold (aext (aext x)) -> (aext x)
1003     // fold (aext (zext x)) -> (zext x)
1004     // fold (aext (sext x)) -> (sext x)
1005     DEBUG(dbgs() << "\nPromoting ";
1006           Op.getNode()->dump(&DAG));
1007     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1008   }
1009   return SDValue();
1010 }
1011
1012 bool DAGCombiner::PromoteLoad(SDValue Op) {
1013   if (!LegalOperations)
1014     return false;
1015
1016   EVT VT = Op.getValueType();
1017   if (VT.isVector() || !VT.isInteger())
1018     return false;
1019
1020   // If operation type is 'undesirable', e.g. i16 on x86, consider
1021   // promoting it.
1022   unsigned Opc = Op.getOpcode();
1023   if (TLI.isTypeDesirableForOp(Opc, VT))
1024     return false;
1025
1026   EVT PVT = VT;
1027   // Consult target whether it is a good idea to promote this operation and
1028   // what's the right type to promote it to.
1029   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1030     assert(PVT != VT && "Don't know what type to promote to!");
1031
1032     SDLoc dl(Op);
1033     SDNode *N = Op.getNode();
1034     LoadSDNode *LD = cast<LoadSDNode>(N);
1035     EVT MemVT = LD->getMemoryVT();
1036     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1037       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1038                                                   : ISD::EXTLOAD)
1039       : LD->getExtensionType();
1040     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1041                                    LD->getChain(), LD->getBasePtr(),
1042                                    MemVT, LD->getMemOperand());
1043     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1044
1045     DEBUG(dbgs() << "\nPromoting ";
1046           N->dump(&DAG);
1047           dbgs() << "\nTo: ";
1048           Result.getNode()->dump(&DAG);
1049           dbgs() << '\n');
1050     WorkListRemover DeadNodes(*this);
1051     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1052     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1053     removeFromWorkList(N);
1054     DAG.DeleteNode(N);
1055     AddToWorkList(Result.getNode());
1056     return true;
1057   }
1058   return false;
1059 }
1060
1061
1062 //===----------------------------------------------------------------------===//
1063 //  Main DAG Combiner implementation
1064 //===----------------------------------------------------------------------===//
1065
1066 void DAGCombiner::Run(CombineLevel AtLevel) {
1067   // set the instance variables, so that the various visit routines may use it.
1068   Level = AtLevel;
1069   LegalOperations = Level >= AfterLegalizeVectorOps;
1070   LegalTypes = Level >= AfterLegalizeTypes;
1071
1072   // Add all the dag nodes to the worklist.
1073   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1074        E = DAG.allnodes_end(); I != E; ++I)
1075     AddToWorkList(I);
1076
1077   // Create a dummy node (which is not added to allnodes), that adds a reference
1078   // to the root node, preventing it from being deleted, and tracking any
1079   // changes of the root.
1080   HandleSDNode Dummy(DAG.getRoot());
1081
1082   // The root of the dag may dangle to deleted nodes until the dag combiner is
1083   // done.  Set it to null to avoid confusion.
1084   DAG.setRoot(SDValue());
1085
1086   // while the worklist isn't empty, find a node and
1087   // try and combine it.
1088   while (!WorkListContents.empty()) {
1089     SDNode *N;
1090     // The WorkListOrder holds the SDNodes in order, but it may contain
1091     // duplicates.
1092     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1093     // worklist *should* contain, and check the node we want to visit is should
1094     // actually be visited.
1095     do {
1096       N = WorkListOrder.pop_back_val();
1097     } while (!WorkListContents.erase(N));
1098
1099     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1100     // N is deleted from the DAG, since they too may now be dead or may have a
1101     // reduced number of uses, allowing other xforms.
1102     if (N->use_empty() && N != &Dummy) {
1103       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1104         AddToWorkList(N->getOperand(i).getNode());
1105
1106       DAG.DeleteNode(N);
1107       continue;
1108     }
1109
1110     SDValue RV = combine(N);
1111
1112     if (!RV.getNode())
1113       continue;
1114
1115     ++NodesCombined;
1116
1117     // If we get back the same node we passed in, rather than a new node or
1118     // zero, we know that the node must have defined multiple values and
1119     // CombineTo was used.  Since CombineTo takes care of the worklist
1120     // mechanics for us, we have no work to do in this case.
1121     if (RV.getNode() == N)
1122       continue;
1123
1124     assert(N->getOpcode() != ISD::DELETED_NODE &&
1125            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1126            "Node was deleted but visit returned new node!");
1127
1128     DEBUG(dbgs() << "\nReplacing.3 ";
1129           N->dump(&DAG);
1130           dbgs() << "\nWith: ";
1131           RV.getNode()->dump(&DAG);
1132           dbgs() << '\n');
1133
1134     // Transfer debug value.
1135     DAG.TransferDbgValues(SDValue(N, 0), RV);
1136     WorkListRemover DeadNodes(*this);
1137     if (N->getNumValues() == RV.getNode()->getNumValues())
1138       DAG.ReplaceAllUsesWith(N, RV.getNode());
1139     else {
1140       assert(N->getValueType(0) == RV.getValueType() &&
1141              N->getNumValues() == 1 && "Type mismatch");
1142       SDValue OpV = RV;
1143       DAG.ReplaceAllUsesWith(N, &OpV);
1144     }
1145
1146     // Push the new node and any users onto the worklist
1147     AddToWorkList(RV.getNode());
1148     AddUsersToWorkList(RV.getNode());
1149
1150     // Add any uses of the old node to the worklist in case this node is the
1151     // last one that uses them.  They may become dead after this node is
1152     // deleted.
1153     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1154       AddToWorkList(N->getOperand(i).getNode());
1155
1156     // Finally, if the node is now dead, remove it from the graph.  The node
1157     // may not be dead if the replacement process recursively simplified to
1158     // something else needing this node.
1159     if (N->use_empty()) {
1160       // Nodes can be reintroduced into the worklist.  Make sure we do not
1161       // process a node that has been replaced.
1162       removeFromWorkList(N);
1163
1164       // Finally, since the node is now dead, remove it from the graph.
1165       DAG.DeleteNode(N);
1166     }
1167   }
1168
1169   // If the root changed (e.g. it was a dead load, update the root).
1170   DAG.setRoot(Dummy.getValue());
1171   DAG.RemoveDeadNodes();
1172 }
1173
1174 SDValue DAGCombiner::visit(SDNode *N) {
1175   switch (N->getOpcode()) {
1176   default: break;
1177   case ISD::TokenFactor:        return visitTokenFactor(N);
1178   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1179   case ISD::ADD:                return visitADD(N);
1180   case ISD::SUB:                return visitSUB(N);
1181   case ISD::ADDC:               return visitADDC(N);
1182   case ISD::SUBC:               return visitSUBC(N);
1183   case ISD::ADDE:               return visitADDE(N);
1184   case ISD::SUBE:               return visitSUBE(N);
1185   case ISD::MUL:                return visitMUL(N);
1186   case ISD::SDIV:               return visitSDIV(N);
1187   case ISD::UDIV:               return visitUDIV(N);
1188   case ISD::SREM:               return visitSREM(N);
1189   case ISD::UREM:               return visitUREM(N);
1190   case ISD::MULHU:              return visitMULHU(N);
1191   case ISD::MULHS:              return visitMULHS(N);
1192   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1193   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1194   case ISD::SMULO:              return visitSMULO(N);
1195   case ISD::UMULO:              return visitUMULO(N);
1196   case ISD::SDIVREM:            return visitSDIVREM(N);
1197   case ISD::UDIVREM:            return visitUDIVREM(N);
1198   case ISD::AND:                return visitAND(N);
1199   case ISD::OR:                 return visitOR(N);
1200   case ISD::XOR:                return visitXOR(N);
1201   case ISD::SHL:                return visitSHL(N);
1202   case ISD::SRA:                return visitSRA(N);
1203   case ISD::SRL:                return visitSRL(N);
1204   case ISD::ROTR:
1205   case ISD::ROTL:               return visitRotate(N);
1206   case ISD::CTLZ:               return visitCTLZ(N);
1207   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1208   case ISD::CTTZ:               return visitCTTZ(N);
1209   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1210   case ISD::CTPOP:              return visitCTPOP(N);
1211   case ISD::SELECT:             return visitSELECT(N);
1212   case ISD::VSELECT:            return visitVSELECT(N);
1213   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1214   case ISD::SETCC:              return visitSETCC(N);
1215   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1216   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1217   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1218   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1219   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1220   case ISD::BITCAST:            return visitBITCAST(N);
1221   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1222   case ISD::FADD:               return visitFADD(N);
1223   case ISD::FSUB:               return visitFSUB(N);
1224   case ISD::FMUL:               return visitFMUL(N);
1225   case ISD::FMA:                return visitFMA(N);
1226   case ISD::FDIV:               return visitFDIV(N);
1227   case ISD::FREM:               return visitFREM(N);
1228   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1229   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1230   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1231   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1232   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1233   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1234   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1235   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1236   case ISD::FNEG:               return visitFNEG(N);
1237   case ISD::FABS:               return visitFABS(N);
1238   case ISD::FFLOOR:             return visitFFLOOR(N);
1239   case ISD::FCEIL:              return visitFCEIL(N);
1240   case ISD::FTRUNC:             return visitFTRUNC(N);
1241   case ISD::BRCOND:             return visitBRCOND(N);
1242   case ISD::BR_CC:              return visitBR_CC(N);
1243   case ISD::LOAD:               return visitLOAD(N);
1244   case ISD::STORE:              return visitSTORE(N);
1245   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1246   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1247   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1248   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1249   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1250   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1251   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1252   }
1253   return SDValue();
1254 }
1255
1256 SDValue DAGCombiner::combine(SDNode *N) {
1257   SDValue RV = visit(N);
1258
1259   // If nothing happened, try a target-specific DAG combine.
1260   if (!RV.getNode()) {
1261     assert(N->getOpcode() != ISD::DELETED_NODE &&
1262            "Node was deleted but visit returned NULL!");
1263
1264     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1265         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1266
1267       // Expose the DAG combiner to the target combiner impls.
1268       TargetLowering::DAGCombinerInfo
1269         DagCombineInfo(DAG, Level, false, this);
1270
1271       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1272     }
1273   }
1274
1275   // If nothing happened still, try promoting the operation.
1276   if (!RV.getNode()) {
1277     switch (N->getOpcode()) {
1278     default: break;
1279     case ISD::ADD:
1280     case ISD::SUB:
1281     case ISD::MUL:
1282     case ISD::AND:
1283     case ISD::OR:
1284     case ISD::XOR:
1285       RV = PromoteIntBinOp(SDValue(N, 0));
1286       break;
1287     case ISD::SHL:
1288     case ISD::SRA:
1289     case ISD::SRL:
1290       RV = PromoteIntShiftOp(SDValue(N, 0));
1291       break;
1292     case ISD::SIGN_EXTEND:
1293     case ISD::ZERO_EXTEND:
1294     case ISD::ANY_EXTEND:
1295       RV = PromoteExtend(SDValue(N, 0));
1296       break;
1297     case ISD::LOAD:
1298       if (PromoteLoad(SDValue(N, 0)))
1299         RV = SDValue(N, 0);
1300       break;
1301     }
1302   }
1303
1304   // If N is a commutative binary node, try commuting it to enable more
1305   // sdisel CSE.
1306   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1307       N->getNumValues() == 1) {
1308     SDValue N0 = N->getOperand(0);
1309     SDValue N1 = N->getOperand(1);
1310
1311     // Constant operands are canonicalized to RHS.
1312     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1313       SDValue Ops[] = { N1, N0 };
1314       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1315                                             Ops, 2);
1316       if (CSENode)
1317         return SDValue(CSENode, 0);
1318     }
1319   }
1320
1321   return RV;
1322 }
1323
1324 /// getInputChainForNode - Given a node, return its input chain if it has one,
1325 /// otherwise return a null sd operand.
1326 static SDValue getInputChainForNode(SDNode *N) {
1327   if (unsigned NumOps = N->getNumOperands()) {
1328     if (N->getOperand(0).getValueType() == MVT::Other)
1329       return N->getOperand(0);
1330     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1331       return N->getOperand(NumOps-1);
1332     for (unsigned i = 1; i < NumOps-1; ++i)
1333       if (N->getOperand(i).getValueType() == MVT::Other)
1334         return N->getOperand(i);
1335   }
1336   return SDValue();
1337 }
1338
1339 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1340   // If N has two operands, where one has an input chain equal to the other,
1341   // the 'other' chain is redundant.
1342   if (N->getNumOperands() == 2) {
1343     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1344       return N->getOperand(0);
1345     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1346       return N->getOperand(1);
1347   }
1348
1349   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1350   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1351   SmallPtrSet<SDNode*, 16> SeenOps;
1352   bool Changed = false;             // If we should replace this token factor.
1353
1354   // Start out with this token factor.
1355   TFs.push_back(N);
1356
1357   // Iterate through token factors.  The TFs grows when new token factors are
1358   // encountered.
1359   for (unsigned i = 0; i < TFs.size(); ++i) {
1360     SDNode *TF = TFs[i];
1361
1362     // Check each of the operands.
1363     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1364       SDValue Op = TF->getOperand(i);
1365
1366       switch (Op.getOpcode()) {
1367       case ISD::EntryToken:
1368         // Entry tokens don't need to be added to the list. They are
1369         // rededundant.
1370         Changed = true;
1371         break;
1372
1373       case ISD::TokenFactor:
1374         if (Op.hasOneUse() &&
1375             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1376           // Queue up for processing.
1377           TFs.push_back(Op.getNode());
1378           // Clean up in case the token factor is removed.
1379           AddToWorkList(Op.getNode());
1380           Changed = true;
1381           break;
1382         }
1383         // Fall thru
1384
1385       default:
1386         // Only add if it isn't already in the list.
1387         if (SeenOps.insert(Op.getNode()))
1388           Ops.push_back(Op);
1389         else
1390           Changed = true;
1391         break;
1392       }
1393     }
1394   }
1395
1396   SDValue Result;
1397
1398   // If we've change things around then replace token factor.
1399   if (Changed) {
1400     if (Ops.empty()) {
1401       // The entry token is the only possible outcome.
1402       Result = DAG.getEntryNode();
1403     } else {
1404       // New and improved token factor.
1405       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1406                            MVT::Other, &Ops[0], Ops.size());
1407     }
1408
1409     // Don't add users to work list.
1410     return CombineTo(N, Result, false);
1411   }
1412
1413   return Result;
1414 }
1415
1416 /// MERGE_VALUES can always be eliminated.
1417 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1418   WorkListRemover DeadNodes(*this);
1419   // Replacing results may cause a different MERGE_VALUES to suddenly
1420   // be CSE'd with N, and carry its uses with it. Iterate until no
1421   // uses remain, to ensure that the node can be safely deleted.
1422   // First add the users of this node to the work list so that they
1423   // can be tried again once they have new operands.
1424   AddUsersToWorkList(N);
1425   do {
1426     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1427       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1428   } while (!N->use_empty());
1429   removeFromWorkList(N);
1430   DAG.DeleteNode(N);
1431   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1432 }
1433
1434 static
1435 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1436                               SelectionDAG &DAG) {
1437   EVT VT = N0.getValueType();
1438   SDValue N00 = N0.getOperand(0);
1439   SDValue N01 = N0.getOperand(1);
1440   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1441
1442   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1443       isa<ConstantSDNode>(N00.getOperand(1))) {
1444     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1445     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1446                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1447                                  N00.getOperand(0), N01),
1448                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1449                                  N00.getOperand(1), N01));
1450     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1451   }
1452
1453   return SDValue();
1454 }
1455
1456 SDValue DAGCombiner::visitADD(SDNode *N) {
1457   SDValue N0 = N->getOperand(0);
1458   SDValue N1 = N->getOperand(1);
1459   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1460   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1461   EVT VT = N0.getValueType();
1462
1463   // fold vector ops
1464   if (VT.isVector()) {
1465     SDValue FoldedVOp = SimplifyVBinOp(N);
1466     if (FoldedVOp.getNode()) return FoldedVOp;
1467
1468     // fold (add x, 0) -> x, vector edition
1469     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1470       return N0;
1471     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1472       return N1;
1473   }
1474
1475   // fold (add x, undef) -> undef
1476   if (N0.getOpcode() == ISD::UNDEF)
1477     return N0;
1478   if (N1.getOpcode() == ISD::UNDEF)
1479     return N1;
1480   // fold (add c1, c2) -> c1+c2
1481   if (N0C && N1C)
1482     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1483   // canonicalize constant to RHS
1484   if (N0C && !N1C)
1485     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1486   // fold (add x, 0) -> x
1487   if (N1C && N1C->isNullValue())
1488     return N0;
1489   // fold (add Sym, c) -> Sym+c
1490   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1491     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1492         GA->getOpcode() == ISD::GlobalAddress)
1493       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1494                                   GA->getOffset() +
1495                                     (uint64_t)N1C->getSExtValue());
1496   // fold ((c1-A)+c2) -> (c1+c2)-A
1497   if (N1C && N0.getOpcode() == ISD::SUB)
1498     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1499       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1500                          DAG.getConstant(N1C->getAPIntValue()+
1501                                          N0C->getAPIntValue(), VT),
1502                          N0.getOperand(1));
1503   // reassociate add
1504   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1505   if (RADD.getNode())
1506     return RADD;
1507   // fold ((0-A) + B) -> B-A
1508   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1509       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1510     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1511   // fold (A + (0-B)) -> A-B
1512   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1513       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1514     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1515   // fold (A+(B-A)) -> B
1516   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1517     return N1.getOperand(0);
1518   // fold ((B-A)+A) -> B
1519   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1520     return N0.getOperand(0);
1521   // fold (A+(B-(A+C))) to (B-C)
1522   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1523       N0 == N1.getOperand(1).getOperand(0))
1524     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1525                        N1.getOperand(1).getOperand(1));
1526   // fold (A+(B-(C+A))) to (B-C)
1527   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1528       N0 == N1.getOperand(1).getOperand(1))
1529     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1530                        N1.getOperand(1).getOperand(0));
1531   // fold (A+((B-A)+or-C)) to (B+or-C)
1532   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1533       N1.getOperand(0).getOpcode() == ISD::SUB &&
1534       N0 == N1.getOperand(0).getOperand(1))
1535     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1536                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1537
1538   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1539   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1540     SDValue N00 = N0.getOperand(0);
1541     SDValue N01 = N0.getOperand(1);
1542     SDValue N10 = N1.getOperand(0);
1543     SDValue N11 = N1.getOperand(1);
1544
1545     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1546       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1547                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1548                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1549   }
1550
1551   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1552     return SDValue(N, 0);
1553
1554   // fold (a+b) -> (a|b) iff a and b share no bits.
1555   if (VT.isInteger() && !VT.isVector()) {
1556     APInt LHSZero, LHSOne;
1557     APInt RHSZero, RHSOne;
1558     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1559
1560     if (LHSZero.getBoolValue()) {
1561       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1562
1563       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1564       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1565       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1566         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1567           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1568       }
1569     }
1570   }
1571
1572   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1573   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1574     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1575     if (Result.getNode()) return Result;
1576   }
1577   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1578     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1579     if (Result.getNode()) return Result;
1580   }
1581
1582   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1583   if (N1.getOpcode() == ISD::SHL &&
1584       N1.getOperand(0).getOpcode() == ISD::SUB)
1585     if (ConstantSDNode *C =
1586           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1587       if (C->getAPIntValue() == 0)
1588         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1589                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1590                                        N1.getOperand(0).getOperand(1),
1591                                        N1.getOperand(1)));
1592   if (N0.getOpcode() == ISD::SHL &&
1593       N0.getOperand(0).getOpcode() == ISD::SUB)
1594     if (ConstantSDNode *C =
1595           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1596       if (C->getAPIntValue() == 0)
1597         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1598                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1599                                        N0.getOperand(0).getOperand(1),
1600                                        N0.getOperand(1)));
1601
1602   if (N1.getOpcode() == ISD::AND) {
1603     SDValue AndOp0 = N1.getOperand(0);
1604     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1605     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1606     unsigned DestBits = VT.getScalarType().getSizeInBits();
1607
1608     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1609     // and similar xforms where the inner op is either ~0 or 0.
1610     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1611       SDLoc DL(N);
1612       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1613     }
1614   }
1615
1616   // add (sext i1), X -> sub X, (zext i1)
1617   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1618       N0.getOperand(0).getValueType() == MVT::i1 &&
1619       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1620     SDLoc DL(N);
1621     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1622     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1623   }
1624
1625   return SDValue();
1626 }
1627
1628 SDValue DAGCombiner::visitADDC(SDNode *N) {
1629   SDValue N0 = N->getOperand(0);
1630   SDValue N1 = N->getOperand(1);
1631   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1632   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1633   EVT VT = N0.getValueType();
1634
1635   // If the flag result is dead, turn this into an ADD.
1636   if (!N->hasAnyUseOfValue(1))
1637     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1638                      DAG.getNode(ISD::CARRY_FALSE,
1639                                  SDLoc(N), MVT::Glue));
1640
1641   // canonicalize constant to RHS.
1642   if (N0C && !N1C)
1643     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1644
1645   // fold (addc x, 0) -> x + no carry out
1646   if (N1C && N1C->isNullValue())
1647     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1648                                         SDLoc(N), MVT::Glue));
1649
1650   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1651   APInt LHSZero, LHSOne;
1652   APInt RHSZero, RHSOne;
1653   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1654
1655   if (LHSZero.getBoolValue()) {
1656     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1657
1658     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1659     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1660     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1661       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1662                        DAG.getNode(ISD::CARRY_FALSE,
1663                                    SDLoc(N), MVT::Glue));
1664   }
1665
1666   return SDValue();
1667 }
1668
1669 SDValue DAGCombiner::visitADDE(SDNode *N) {
1670   SDValue N0 = N->getOperand(0);
1671   SDValue N1 = N->getOperand(1);
1672   SDValue CarryIn = N->getOperand(2);
1673   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1674   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1675
1676   // canonicalize constant to RHS
1677   if (N0C && !N1C)
1678     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1679                        N1, N0, CarryIn);
1680
1681   // fold (adde x, y, false) -> (addc x, y)
1682   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1683     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1684
1685   return SDValue();
1686 }
1687
1688 // Since it may not be valid to emit a fold to zero for vector initializers
1689 // check if we can before folding.
1690 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1691                              SelectionDAG &DAG,
1692                              bool LegalOperations, bool LegalTypes) {
1693   if (!VT.isVector())
1694     return DAG.getConstant(0, VT);
1695   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1696     return DAG.getConstant(0, VT);
1697   return SDValue();
1698 }
1699
1700 SDValue DAGCombiner::visitSUB(SDNode *N) {
1701   SDValue N0 = N->getOperand(0);
1702   SDValue N1 = N->getOperand(1);
1703   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1704   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1705   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1706     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1707   EVT VT = N0.getValueType();
1708
1709   // fold vector ops
1710   if (VT.isVector()) {
1711     SDValue FoldedVOp = SimplifyVBinOp(N);
1712     if (FoldedVOp.getNode()) return FoldedVOp;
1713
1714     // fold (sub x, 0) -> x, vector edition
1715     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1716       return N0;
1717   }
1718
1719   // fold (sub x, x) -> 0
1720   // FIXME: Refactor this and xor and other similar operations together.
1721   if (N0 == N1)
1722     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1723   // fold (sub c1, c2) -> c1-c2
1724   if (N0C && N1C)
1725     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1726   // fold (sub x, c) -> (add x, -c)
1727   if (N1C)
1728     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1729                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1730   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1731   if (N0C && N0C->isAllOnesValue())
1732     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1733   // fold A-(A-B) -> B
1734   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1735     return N1.getOperand(1);
1736   // fold (A+B)-A -> B
1737   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1738     return N0.getOperand(1);
1739   // fold (A+B)-B -> A
1740   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1741     return N0.getOperand(0);
1742   // fold C2-(A+C1) -> (C2-C1)-A
1743   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1744     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1745                                    VT);
1746     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1747                        N1.getOperand(0));
1748   }
1749   // fold ((A+(B+or-C))-B) -> A+or-C
1750   if (N0.getOpcode() == ISD::ADD &&
1751       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1752        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1753       N0.getOperand(1).getOperand(0) == N1)
1754     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1755                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1756   // fold ((A+(C+B))-B) -> A+C
1757   if (N0.getOpcode() == ISD::ADD &&
1758       N0.getOperand(1).getOpcode() == ISD::ADD &&
1759       N0.getOperand(1).getOperand(1) == N1)
1760     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1761                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1762   // fold ((A-(B-C))-C) -> A-B
1763   if (N0.getOpcode() == ISD::SUB &&
1764       N0.getOperand(1).getOpcode() == ISD::SUB &&
1765       N0.getOperand(1).getOperand(1) == N1)
1766     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1767                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1768
1769   // If either operand of a sub is undef, the result is undef
1770   if (N0.getOpcode() == ISD::UNDEF)
1771     return N0;
1772   if (N1.getOpcode() == ISD::UNDEF)
1773     return N1;
1774
1775   // If the relocation model supports it, consider symbol offsets.
1776   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1777     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1778       // fold (sub Sym, c) -> Sym-c
1779       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1780         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1781                                     GA->getOffset() -
1782                                       (uint64_t)N1C->getSExtValue());
1783       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1784       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1785         if (GA->getGlobal() == GB->getGlobal())
1786           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1787                                  VT);
1788     }
1789
1790   return SDValue();
1791 }
1792
1793 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1794   SDValue N0 = N->getOperand(0);
1795   SDValue N1 = N->getOperand(1);
1796   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1797   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1798   EVT VT = N0.getValueType();
1799
1800   // If the flag result is dead, turn this into an SUB.
1801   if (!N->hasAnyUseOfValue(1))
1802     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1803                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1804                                  MVT::Glue));
1805
1806   // fold (subc x, x) -> 0 + no borrow
1807   if (N0 == N1)
1808     return CombineTo(N, DAG.getConstant(0, VT),
1809                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1810                                  MVT::Glue));
1811
1812   // fold (subc x, 0) -> x + no borrow
1813   if (N1C && N1C->isNullValue())
1814     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1815                                         MVT::Glue));
1816
1817   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1818   if (N0C && N0C->isAllOnesValue())
1819     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1820                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1821                                  MVT::Glue));
1822
1823   return SDValue();
1824 }
1825
1826 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1827   SDValue N0 = N->getOperand(0);
1828   SDValue N1 = N->getOperand(1);
1829   SDValue CarryIn = N->getOperand(2);
1830
1831   // fold (sube x, y, false) -> (subc x, y)
1832   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1833     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1834
1835   return SDValue();
1836 }
1837
1838 SDValue DAGCombiner::visitMUL(SDNode *N) {
1839   SDValue N0 = N->getOperand(0);
1840   SDValue N1 = N->getOperand(1);
1841   EVT VT = N0.getValueType();
1842
1843   // fold (mul x, undef) -> 0
1844   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1845     return DAG.getConstant(0, VT);
1846
1847   bool N0IsConst = false;
1848   bool N1IsConst = false;
1849   APInt ConstValue0, ConstValue1;
1850   // fold vector ops
1851   if (VT.isVector()) {
1852     SDValue FoldedVOp = SimplifyVBinOp(N);
1853     if (FoldedVOp.getNode()) return FoldedVOp;
1854
1855     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1856     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1857   } else {
1858     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1859     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1860                             : APInt();
1861     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1862     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1863                             : APInt();
1864   }
1865
1866   // fold (mul c1, c2) -> c1*c2
1867   if (N0IsConst && N1IsConst)
1868     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1869
1870   // canonicalize constant to RHS
1871   if (N0IsConst && !N1IsConst)
1872     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1873   // fold (mul x, 0) -> 0
1874   if (N1IsConst && ConstValue1 == 0)
1875     return N1;
1876   // We require a splat of the entire scalar bit width for non-contiguous
1877   // bit patterns.
1878   bool IsFullSplat =
1879     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1880   // fold (mul x, 1) -> x
1881   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1882     return N0;
1883   // fold (mul x, -1) -> 0-x
1884   if (N1IsConst && ConstValue1.isAllOnesValue())
1885     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1886                        DAG.getConstant(0, VT), N0);
1887   // fold (mul x, (1 << c)) -> x << c
1888   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1889     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1890                        DAG.getConstant(ConstValue1.logBase2(),
1891                                        getShiftAmountTy(N0.getValueType())));
1892   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1893   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1894     unsigned Log2Val = (-ConstValue1).logBase2();
1895     // FIXME: If the input is something that is easily negated (e.g. a
1896     // single-use add), we should put the negate there.
1897     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1898                        DAG.getConstant(0, VT),
1899                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1900                             DAG.getConstant(Log2Val,
1901                                       getShiftAmountTy(N0.getValueType()))));
1902   }
1903
1904   APInt Val;
1905   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1906   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1907       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1908                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1909     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1910                              N1, N0.getOperand(1));
1911     AddToWorkList(C3.getNode());
1912     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1913                        N0.getOperand(0), C3);
1914   }
1915
1916   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1917   // use.
1918   {
1919     SDValue Sh(nullptr,0), Y(nullptr,0);
1920     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1921     if (N0.getOpcode() == ISD::SHL &&
1922         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1923                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1924         N0.getNode()->hasOneUse()) {
1925       Sh = N0; Y = N1;
1926     } else if (N1.getOpcode() == ISD::SHL &&
1927                isa<ConstantSDNode>(N1.getOperand(1)) &&
1928                N1.getNode()->hasOneUse()) {
1929       Sh = N1; Y = N0;
1930     }
1931
1932     if (Sh.getNode()) {
1933       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1934                                 Sh.getOperand(0), Y);
1935       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1936                          Mul, Sh.getOperand(1));
1937     }
1938   }
1939
1940   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1941   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1942       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943                      isa<ConstantSDNode>(N0.getOperand(1))))
1944     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1945                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1946                                    N0.getOperand(0), N1),
1947                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1948                                    N0.getOperand(1), N1));
1949
1950   // reassociate mul
1951   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1952   if (RMUL.getNode())
1953     return RMUL;
1954
1955   return SDValue();
1956 }
1957
1958 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1959   SDValue N0 = N->getOperand(0);
1960   SDValue N1 = N->getOperand(1);
1961   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1962   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1963   EVT VT = N->getValueType(0);
1964
1965   // fold vector ops
1966   if (VT.isVector()) {
1967     SDValue FoldedVOp = SimplifyVBinOp(N);
1968     if (FoldedVOp.getNode()) return FoldedVOp;
1969   }
1970
1971   // fold (sdiv c1, c2) -> c1/c2
1972   if (N0C && N1C && !N1C->isNullValue())
1973     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1974   // fold (sdiv X, 1) -> X
1975   if (N1C && N1C->getAPIntValue() == 1LL)
1976     return N0;
1977   // fold (sdiv X, -1) -> 0-X
1978   if (N1C && N1C->isAllOnesValue())
1979     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1980                        DAG.getConstant(0, VT), N0);
1981   // If we know the sign bits of both operands are zero, strength reduce to a
1982   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1983   if (!VT.isVector()) {
1984     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1985       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1986                          N0, N1);
1987   }
1988   // fold (sdiv X, pow2) -> simple ops after legalize
1989   if (N1C && !N1C->isNullValue() &&
1990       (N1C->getAPIntValue().isPowerOf2() ||
1991        (-N1C->getAPIntValue()).isPowerOf2())) {
1992     // If dividing by powers of two is cheap, then don't perform the following
1993     // fold.
1994     if (TLI.isPow2DivCheap())
1995       return SDValue();
1996
1997     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1998
1999     // Splat the sign bit into the register
2000     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2001                               DAG.getConstant(VT.getSizeInBits()-1,
2002                                        getShiftAmountTy(N0.getValueType())));
2003     AddToWorkList(SGN.getNode());
2004
2005     // Add (N0 < 0) ? abs2 - 1 : 0;
2006     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2007                               DAG.getConstant(VT.getSizeInBits() - lg2,
2008                                        getShiftAmountTy(SGN.getValueType())));
2009     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2010     AddToWorkList(SRL.getNode());
2011     AddToWorkList(ADD.getNode());    // Divide by pow2
2012     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2013                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2014
2015     // If we're dividing by a positive value, we're done.  Otherwise, we must
2016     // negate the result.
2017     if (N1C->getAPIntValue().isNonNegative())
2018       return SRA;
2019
2020     AddToWorkList(SRA.getNode());
2021     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2022                        DAG.getConstant(0, VT), SRA);
2023   }
2024
2025   // if integer divide is expensive and we satisfy the requirements, emit an
2026   // alternate sequence.
2027   if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2028     SDValue Op = BuildSDIV(N);
2029     if (Op.getNode()) return Op;
2030   }
2031
2032   // undef / X -> 0
2033   if (N0.getOpcode() == ISD::UNDEF)
2034     return DAG.getConstant(0, VT);
2035   // X / undef -> undef
2036   if (N1.getOpcode() == ISD::UNDEF)
2037     return N1;
2038
2039   return SDValue();
2040 }
2041
2042 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2043   SDValue N0 = N->getOperand(0);
2044   SDValue N1 = N->getOperand(1);
2045   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2046   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2047   EVT VT = N->getValueType(0);
2048
2049   // fold vector ops
2050   if (VT.isVector()) {
2051     SDValue FoldedVOp = SimplifyVBinOp(N);
2052     if (FoldedVOp.getNode()) return FoldedVOp;
2053   }
2054
2055   // fold (udiv c1, c2) -> c1/c2
2056   if (N0C && N1C && !N1C->isNullValue())
2057     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2058   // fold (udiv x, (1 << c)) -> x >>u c
2059   if (N1C && N1C->getAPIntValue().isPowerOf2())
2060     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2061                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2062                                        getShiftAmountTy(N0.getValueType())));
2063   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2064   if (N1.getOpcode() == ISD::SHL) {
2065     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2066       if (SHC->getAPIntValue().isPowerOf2()) {
2067         EVT ADDVT = N1.getOperand(1).getValueType();
2068         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2069                                   N1.getOperand(1),
2070                                   DAG.getConstant(SHC->getAPIntValue()
2071                                                                   .logBase2(),
2072                                                   ADDVT));
2073         AddToWorkList(Add.getNode());
2074         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2075       }
2076     }
2077   }
2078   // fold (udiv x, c) -> alternate
2079   if ((N1C || N1->getOpcode() == ISD::BUILD_VECTOR) && !TLI.isIntDivCheap()) {
2080     SDValue Op = BuildUDIV(N);
2081     if (Op.getNode()) return Op;
2082   }
2083
2084   // undef / X -> 0
2085   if (N0.getOpcode() == ISD::UNDEF)
2086     return DAG.getConstant(0, VT);
2087   // X / undef -> undef
2088   if (N1.getOpcode() == ISD::UNDEF)
2089     return N1;
2090
2091   return SDValue();
2092 }
2093
2094 SDValue DAGCombiner::visitSREM(SDNode *N) {
2095   SDValue N0 = N->getOperand(0);
2096   SDValue N1 = N->getOperand(1);
2097   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2098   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2099   EVT VT = N->getValueType(0);
2100
2101   // fold (srem c1, c2) -> c1%c2
2102   if (N0C && N1C && !N1C->isNullValue())
2103     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2104   // If we know the sign bits of both operands are zero, strength reduce to a
2105   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2106   if (!VT.isVector()) {
2107     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2108       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2109   }
2110
2111   // If X/C can be simplified by the division-by-constant logic, lower
2112   // X%C to the equivalent of X-X/C*C.
2113   if (N1C && !N1C->isNullValue()) {
2114     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2115     AddToWorkList(Div.getNode());
2116     SDValue OptimizedDiv = combine(Div.getNode());
2117     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2118       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2119                                 OptimizedDiv, N1);
2120       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2121       AddToWorkList(Mul.getNode());
2122       return Sub;
2123     }
2124   }
2125
2126   // undef % X -> 0
2127   if (N0.getOpcode() == ISD::UNDEF)
2128     return DAG.getConstant(0, VT);
2129   // X % undef -> undef
2130   if (N1.getOpcode() == ISD::UNDEF)
2131     return N1;
2132
2133   return SDValue();
2134 }
2135
2136 SDValue DAGCombiner::visitUREM(SDNode *N) {
2137   SDValue N0 = N->getOperand(0);
2138   SDValue N1 = N->getOperand(1);
2139   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2140   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2141   EVT VT = N->getValueType(0);
2142
2143   // fold (urem c1, c2) -> c1%c2
2144   if (N0C && N1C && !N1C->isNullValue())
2145     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2146   // fold (urem x, pow2) -> (and x, pow2-1)
2147   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2148     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2149                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2150   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2151   if (N1.getOpcode() == ISD::SHL) {
2152     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2153       if (SHC->getAPIntValue().isPowerOf2()) {
2154         SDValue Add =
2155           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2156                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2157                                  VT));
2158         AddToWorkList(Add.getNode());
2159         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2160       }
2161     }
2162   }
2163
2164   // If X/C can be simplified by the division-by-constant logic, lower
2165   // X%C to the equivalent of X-X/C*C.
2166   if (N1C && !N1C->isNullValue()) {
2167     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2168     AddToWorkList(Div.getNode());
2169     SDValue OptimizedDiv = combine(Div.getNode());
2170     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2171       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2172                                 OptimizedDiv, N1);
2173       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2174       AddToWorkList(Mul.getNode());
2175       return Sub;
2176     }
2177   }
2178
2179   // undef % X -> 0
2180   if (N0.getOpcode() == ISD::UNDEF)
2181     return DAG.getConstant(0, VT);
2182   // X % undef -> undef
2183   if (N1.getOpcode() == ISD::UNDEF)
2184     return N1;
2185
2186   return SDValue();
2187 }
2188
2189 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2190   SDValue N0 = N->getOperand(0);
2191   SDValue N1 = N->getOperand(1);
2192   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2193   EVT VT = N->getValueType(0);
2194   SDLoc DL(N);
2195
2196   // fold (mulhs x, 0) -> 0
2197   if (N1C && N1C->isNullValue())
2198     return N1;
2199   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2200   if (N1C && N1C->getAPIntValue() == 1)
2201     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2202                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2203                                        getShiftAmountTy(N0.getValueType())));
2204   // fold (mulhs x, undef) -> 0
2205   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2206     return DAG.getConstant(0, VT);
2207
2208   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2209   // plus a shift.
2210   if (VT.isSimple() && !VT.isVector()) {
2211     MVT Simple = VT.getSimpleVT();
2212     unsigned SimpleSize = Simple.getSizeInBits();
2213     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2214     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2215       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2216       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2217       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2218       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2219             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2220       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2221     }
2222   }
2223
2224   return SDValue();
2225 }
2226
2227 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2228   SDValue N0 = N->getOperand(0);
2229   SDValue N1 = N->getOperand(1);
2230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2231   EVT VT = N->getValueType(0);
2232   SDLoc DL(N);
2233
2234   // fold (mulhu x, 0) -> 0
2235   if (N1C && N1C->isNullValue())
2236     return N1;
2237   // fold (mulhu x, 1) -> 0
2238   if (N1C && N1C->getAPIntValue() == 1)
2239     return DAG.getConstant(0, N0.getValueType());
2240   // fold (mulhu x, undef) -> 0
2241   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2242     return DAG.getConstant(0, VT);
2243
2244   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2245   // plus a shift.
2246   if (VT.isSimple() && !VT.isVector()) {
2247     MVT Simple = VT.getSimpleVT();
2248     unsigned SimpleSize = Simple.getSizeInBits();
2249     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2250     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2251       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2252       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2253       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2254       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2255             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2256       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2257     }
2258   }
2259
2260   return SDValue();
2261 }
2262
2263 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2264 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2265 /// that are being performed. Return true if a simplification was made.
2266 ///
2267 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2268                                                 unsigned HiOp) {
2269   // If the high half is not needed, just compute the low half.
2270   bool HiExists = N->hasAnyUseOfValue(1);
2271   if (!HiExists &&
2272       (!LegalOperations ||
2273        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2274     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2275                               N->op_begin(), N->getNumOperands());
2276     return CombineTo(N, Res, Res);
2277   }
2278
2279   // If the low half is not needed, just compute the high half.
2280   bool LoExists = N->hasAnyUseOfValue(0);
2281   if (!LoExists &&
2282       (!LegalOperations ||
2283        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2284     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2285                               N->op_begin(), N->getNumOperands());
2286     return CombineTo(N, Res, Res);
2287   }
2288
2289   // If both halves are used, return as it is.
2290   if (LoExists && HiExists)
2291     return SDValue();
2292
2293   // If the two computed results can be simplified separately, separate them.
2294   if (LoExists) {
2295     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296                              N->op_begin(), N->getNumOperands());
2297     AddToWorkList(Lo.getNode());
2298     SDValue LoOpt = combine(Lo.getNode());
2299     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2300         (!LegalOperations ||
2301          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2302       return CombineTo(N, LoOpt, LoOpt);
2303   }
2304
2305   if (HiExists) {
2306     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2307                              N->op_begin(), N->getNumOperands());
2308     AddToWorkList(Hi.getNode());
2309     SDValue HiOpt = combine(Hi.getNode());
2310     if (HiOpt.getNode() && HiOpt != Hi &&
2311         (!LegalOperations ||
2312          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2313       return CombineTo(N, HiOpt, HiOpt);
2314   }
2315
2316   return SDValue();
2317 }
2318
2319 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2320   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2321   if (Res.getNode()) return Res;
2322
2323   EVT VT = N->getValueType(0);
2324   SDLoc DL(N);
2325
2326   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2327   // plus a shift.
2328   if (VT.isSimple() && !VT.isVector()) {
2329     MVT Simple = VT.getSimpleVT();
2330     unsigned SimpleSize = Simple.getSizeInBits();
2331     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2332     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2333       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2334       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2335       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2336       // Compute the high part as N1.
2337       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2338             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2339       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2340       // Compute the low part as N0.
2341       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2342       return CombineTo(N, Lo, Hi);
2343     }
2344   }
2345
2346   return SDValue();
2347 }
2348
2349 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2350   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2351   if (Res.getNode()) return Res;
2352
2353   EVT VT = N->getValueType(0);
2354   SDLoc DL(N);
2355
2356   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2357   // plus a shift.
2358   if (VT.isSimple() && !VT.isVector()) {
2359     MVT Simple = VT.getSimpleVT();
2360     unsigned SimpleSize = Simple.getSizeInBits();
2361     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2362     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2363       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2364       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2365       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2366       // Compute the high part as N1.
2367       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2368             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2369       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2370       // Compute the low part as N0.
2371       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2372       return CombineTo(N, Lo, Hi);
2373     }
2374   }
2375
2376   return SDValue();
2377 }
2378
2379 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2380   // (smulo x, 2) -> (saddo x, x)
2381   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2382     if (C2->getAPIntValue() == 2)
2383       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2384                          N->getOperand(0), N->getOperand(0));
2385
2386   return SDValue();
2387 }
2388
2389 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2390   // (umulo x, 2) -> (uaddo x, x)
2391   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2392     if (C2->getAPIntValue() == 2)
2393       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2394                          N->getOperand(0), N->getOperand(0));
2395
2396   return SDValue();
2397 }
2398
2399 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2400   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2401   if (Res.getNode()) return Res;
2402
2403   return SDValue();
2404 }
2405
2406 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2407   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2408   if (Res.getNode()) return Res;
2409
2410   return SDValue();
2411 }
2412
2413 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2414 /// two operands of the same opcode, try to simplify it.
2415 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2416   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2417   EVT VT = N0.getValueType();
2418   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2419
2420   // Bail early if none of these transforms apply.
2421   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2422
2423   // For each of OP in AND/OR/XOR:
2424   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2425   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2426   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2427   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2428   //
2429   // do not sink logical op inside of a vector extend, since it may combine
2430   // into a vsetcc.
2431   EVT Op0VT = N0.getOperand(0).getValueType();
2432   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2433        N0.getOpcode() == ISD::SIGN_EXTEND ||
2434        // Avoid infinite looping with PromoteIntBinOp.
2435        (N0.getOpcode() == ISD::ANY_EXTEND &&
2436         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2437        (N0.getOpcode() == ISD::TRUNCATE &&
2438         (!TLI.isZExtFree(VT, Op0VT) ||
2439          !TLI.isTruncateFree(Op0VT, VT)) &&
2440         TLI.isTypeLegal(Op0VT))) &&
2441       !VT.isVector() &&
2442       Op0VT == N1.getOperand(0).getValueType() &&
2443       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2444     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2445                                  N0.getOperand(0).getValueType(),
2446                                  N0.getOperand(0), N1.getOperand(0));
2447     AddToWorkList(ORNode.getNode());
2448     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2449   }
2450
2451   // For each of OP in SHL/SRL/SRA/AND...
2452   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2453   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2454   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2455   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2456        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2457       N0.getOperand(1) == N1.getOperand(1)) {
2458     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2459                                  N0.getOperand(0).getValueType(),
2460                                  N0.getOperand(0), N1.getOperand(0));
2461     AddToWorkList(ORNode.getNode());
2462     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2463                        ORNode, N0.getOperand(1));
2464   }
2465
2466   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2467   // Only perform this optimization after type legalization and before
2468   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2469   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2470   // we don't want to undo this promotion.
2471   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2472   // on scalars.
2473   if ((N0.getOpcode() == ISD::BITCAST ||
2474        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2475       Level == AfterLegalizeTypes) {
2476     SDValue In0 = N0.getOperand(0);
2477     SDValue In1 = N1.getOperand(0);
2478     EVT In0Ty = In0.getValueType();
2479     EVT In1Ty = In1.getValueType();
2480     SDLoc DL(N);
2481     // If both incoming values are integers, and the original types are the
2482     // same.
2483     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2484       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2485       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2486       AddToWorkList(Op.getNode());
2487       return BC;
2488     }
2489   }
2490
2491   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2492   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2493   // If both shuffles use the same mask, and both shuffle within a single
2494   // vector, then it is worthwhile to move the swizzle after the operation.
2495   // The type-legalizer generates this pattern when loading illegal
2496   // vector types from memory. In many cases this allows additional shuffle
2497   // optimizations.
2498   // There are other cases where moving the shuffle after the xor/and/or
2499   // is profitable even if shuffles don't perform a swizzle.
2500   // If both shuffles use the same mask, and both shuffles have the same first
2501   // or second operand, then it might still be profitable to move the shuffle
2502   // after the xor/and/or operation.
2503   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2504     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2505     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2506
2507     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2508            "Inputs to shuffles are not the same type");
2509  
2510     // Check that both shuffles use the same mask. The masks are known to be of
2511     // the same length because the result vector type is the same.
2512     // Check also that shuffles have only one use to avoid introducing extra
2513     // instructions.
2514     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2515         SVN0->getMask().equals(SVN1->getMask())) {
2516       SDValue ShOp = N0->getOperand(1);
2517
2518       // Don't try to fold this node if it requires introducing a
2519       // build vector of all zeros that might be illegal at this stage.
2520       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2521         if (!LegalTypes)
2522           ShOp = DAG.getConstant(0, VT);
2523         else
2524           ShOp = SDValue();
2525       }
2526
2527       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2528       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2529       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2530       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2531         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2532                                       N0->getOperand(0), N1->getOperand(0));
2533         AddToWorkList(NewNode.getNode());
2534         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2535                                     &SVN0->getMask()[0]);
2536       }
2537
2538       // Don't try to fold this node if it requires introducing a
2539       // build vector of all zeros that might be illegal at this stage.
2540       ShOp = N0->getOperand(0);
2541       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2542         if (!LegalTypes)
2543           ShOp = DAG.getConstant(0, VT);
2544         else
2545           ShOp = SDValue();
2546       }
2547
2548       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2549       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2550       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2551       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2552         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553                                       N0->getOperand(1), N1->getOperand(1));
2554         AddToWorkList(NewNode.getNode());
2555         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2556                                     &SVN0->getMask()[0]);
2557       }
2558     }
2559   }
2560
2561   return SDValue();
2562 }
2563
2564 SDValue DAGCombiner::visitAND(SDNode *N) {
2565   SDValue N0 = N->getOperand(0);
2566   SDValue N1 = N->getOperand(1);
2567   SDValue LL, LR, RL, RR, CC0, CC1;
2568   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2569   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2570   EVT VT = N1.getValueType();
2571   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2572
2573   // fold vector ops
2574   if (VT.isVector()) {
2575     SDValue FoldedVOp = SimplifyVBinOp(N);
2576     if (FoldedVOp.getNode()) return FoldedVOp;
2577
2578     // fold (and x, 0) -> 0, vector edition
2579     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2580       return N0;
2581     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2582       return N1;
2583
2584     // fold (and x, -1) -> x, vector edition
2585     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2586       return N1;
2587     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2588       return N0;
2589   }
2590
2591   // fold (and x, undef) -> 0
2592   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2593     return DAG.getConstant(0, VT);
2594   // fold (and c1, c2) -> c1&c2
2595   if (N0C && N1C)
2596     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2597   // canonicalize constant to RHS
2598   if (N0C && !N1C)
2599     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2600   // fold (and x, -1) -> x
2601   if (N1C && N1C->isAllOnesValue())
2602     return N0;
2603   // if (and x, c) is known to be zero, return 0
2604   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2605                                    APInt::getAllOnesValue(BitWidth)))
2606     return DAG.getConstant(0, VT);
2607   // reassociate and
2608   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2609   if (RAND.getNode())
2610     return RAND;
2611   // fold (and (or x, C), D) -> D if (C & D) == D
2612   if (N1C && N0.getOpcode() == ISD::OR)
2613     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2614       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2615         return N1;
2616   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2617   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2618     SDValue N0Op0 = N0.getOperand(0);
2619     APInt Mask = ~N1C->getAPIntValue();
2620     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2621     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2622       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2623                                  N0.getValueType(), N0Op0);
2624
2625       // Replace uses of the AND with uses of the Zero extend node.
2626       CombineTo(N, Zext);
2627
2628       // We actually want to replace all uses of the any_extend with the
2629       // zero_extend, to avoid duplicating things.  This will later cause this
2630       // AND to be folded.
2631       CombineTo(N0.getNode(), Zext);
2632       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2633     }
2634   }
2635   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2636   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2637   // already be zero by virtue of the width of the base type of the load.
2638   //
2639   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2640   // more cases.
2641   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2642        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2643       N0.getOpcode() == ISD::LOAD) {
2644     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2645                                          N0 : N0.getOperand(0) );
2646
2647     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2648     // This can be a pure constant or a vector splat, in which case we treat the
2649     // vector as a scalar and use the splat value.
2650     APInt Constant = APInt::getNullValue(1);
2651     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2652       Constant = C->getAPIntValue();
2653     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2654       APInt SplatValue, SplatUndef;
2655       unsigned SplatBitSize;
2656       bool HasAnyUndefs;
2657       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2658                                              SplatBitSize, HasAnyUndefs);
2659       if (IsSplat) {
2660         // Undef bits can contribute to a possible optimisation if set, so
2661         // set them.
2662         SplatValue |= SplatUndef;
2663
2664         // The splat value may be something like "0x00FFFFFF", which means 0 for
2665         // the first vector value and FF for the rest, repeating. We need a mask
2666         // that will apply equally to all members of the vector, so AND all the
2667         // lanes of the constant together.
2668         EVT VT = Vector->getValueType(0);
2669         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2670
2671         // If the splat value has been compressed to a bitlength lower
2672         // than the size of the vector lane, we need to re-expand it to
2673         // the lane size.
2674         if (BitWidth > SplatBitSize)
2675           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2676                SplatBitSize < BitWidth;
2677                SplatBitSize = SplatBitSize * 2)
2678             SplatValue |= SplatValue.shl(SplatBitSize);
2679
2680         Constant = APInt::getAllOnesValue(BitWidth);
2681         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2682           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2683       }
2684     }
2685
2686     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2687     // actually legal and isn't going to get expanded, else this is a false
2688     // optimisation.
2689     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2690                                                     Load->getMemoryVT());
2691
2692     // Resize the constant to the same size as the original memory access before
2693     // extension. If it is still the AllOnesValue then this AND is completely
2694     // unneeded.
2695     Constant =
2696       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2697
2698     bool B;
2699     switch (Load->getExtensionType()) {
2700     default: B = false; break;
2701     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2702     case ISD::ZEXTLOAD:
2703     case ISD::NON_EXTLOAD: B = true; break;
2704     }
2705
2706     if (B && Constant.isAllOnesValue()) {
2707       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2708       // preserve semantics once we get rid of the AND.
2709       SDValue NewLoad(Load, 0);
2710       if (Load->getExtensionType() == ISD::EXTLOAD) {
2711         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2712                               Load->getValueType(0), SDLoc(Load),
2713                               Load->getChain(), Load->getBasePtr(),
2714                               Load->getOffset(), Load->getMemoryVT(),
2715                               Load->getMemOperand());
2716         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2717         if (Load->getNumValues() == 3) {
2718           // PRE/POST_INC loads have 3 values.
2719           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2720                            NewLoad.getValue(2) };
2721           CombineTo(Load, To, 3, true);
2722         } else {
2723           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2724         }
2725       }
2726
2727       // Fold the AND away, taking care not to fold to the old load node if we
2728       // replaced it.
2729       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2730
2731       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2732     }
2733   }
2734   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2735   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2736     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2737     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2738
2739     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2740         LL.getValueType().isInteger()) {
2741       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2742       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2743         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2744                                      LR.getValueType(), LL, RL);
2745         AddToWorkList(ORNode.getNode());
2746         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2747       }
2748       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2749       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2750         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2751                                       LR.getValueType(), LL, RL);
2752         AddToWorkList(ANDNode.getNode());
2753         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2754       }
2755       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2756       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2757         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2758                                      LR.getValueType(), LL, RL);
2759         AddToWorkList(ORNode.getNode());
2760         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2761       }
2762     }
2763     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2764     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2765         Op0 == Op1 && LL.getValueType().isInteger() &&
2766       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2767                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2768                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2769                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2770       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2771                                     LL, DAG.getConstant(1, LL.getValueType()));
2772       AddToWorkList(ADDNode.getNode());
2773       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2774                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2775     }
2776     // canonicalize equivalent to ll == rl
2777     if (LL == RR && LR == RL) {
2778       Op1 = ISD::getSetCCSwappedOperands(Op1);
2779       std::swap(RL, RR);
2780     }
2781     if (LL == RL && LR == RR) {
2782       bool isInteger = LL.getValueType().isInteger();
2783       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2784       if (Result != ISD::SETCC_INVALID &&
2785           (!LegalOperations ||
2786            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2787             TLI.isOperationLegal(ISD::SETCC,
2788                             getSetCCResultType(N0.getSimpleValueType())))))
2789         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2790                             LL, LR, Result);
2791     }
2792   }
2793
2794   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2795   if (N0.getOpcode() == N1.getOpcode()) {
2796     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2797     if (Tmp.getNode()) return Tmp;
2798   }
2799
2800   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2801   // fold (and (sra)) -> (and (srl)) when possible.
2802   if (!VT.isVector() &&
2803       SimplifyDemandedBits(SDValue(N, 0)))
2804     return SDValue(N, 0);
2805
2806   // fold (zext_inreg (extload x)) -> (zextload x)
2807   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2808     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2809     EVT MemVT = LN0->getMemoryVT();
2810     // If we zero all the possible extended bits, then we can turn this into
2811     // a zextload if we are running before legalize or the operation is legal.
2812     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2813     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2814                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2815         ((!LegalOperations && !LN0->isVolatile()) ||
2816          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2817       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2818                                        LN0->getChain(), LN0->getBasePtr(),
2819                                        MemVT, LN0->getMemOperand());
2820       AddToWorkList(N);
2821       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2822       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2823     }
2824   }
2825   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2826   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2827       N0.hasOneUse()) {
2828     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2829     EVT MemVT = LN0->getMemoryVT();
2830     // If we zero all the possible extended bits, then we can turn this into
2831     // a zextload if we are running before legalize or the operation is legal.
2832     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2833     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2834                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2835         ((!LegalOperations && !LN0->isVolatile()) ||
2836          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2837       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2838                                        LN0->getChain(), LN0->getBasePtr(),
2839                                        MemVT, LN0->getMemOperand());
2840       AddToWorkList(N);
2841       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2842       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2843     }
2844   }
2845
2846   // fold (and (load x), 255) -> (zextload x, i8)
2847   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2848   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2849   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2850               (N0.getOpcode() == ISD::ANY_EXTEND &&
2851                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2852     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2853     LoadSDNode *LN0 = HasAnyExt
2854       ? cast<LoadSDNode>(N0.getOperand(0))
2855       : cast<LoadSDNode>(N0);
2856     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2857         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2858       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2859       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2860         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2861         EVT LoadedVT = LN0->getMemoryVT();
2862
2863         if (ExtVT == LoadedVT &&
2864             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2865           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2866
2867           SDValue NewLoad =
2868             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2869                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2870                            LN0->getMemOperand());
2871           AddToWorkList(N);
2872           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2873           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2874         }
2875
2876         // Do not change the width of a volatile load.
2877         // Do not generate loads of non-round integer types since these can
2878         // be expensive (and would be wrong if the type is not byte sized).
2879         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2880             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2881           EVT PtrType = LN0->getOperand(1).getValueType();
2882
2883           unsigned Alignment = LN0->getAlignment();
2884           SDValue NewPtr = LN0->getBasePtr();
2885
2886           // For big endian targets, we need to add an offset to the pointer
2887           // to load the correct bytes.  For little endian systems, we merely
2888           // need to read fewer bytes from the same pointer.
2889           if (TLI.isBigEndian()) {
2890             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2891             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2892             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2893             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2894                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2895             Alignment = MinAlign(Alignment, PtrOff);
2896           }
2897
2898           AddToWorkList(NewPtr.getNode());
2899
2900           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2901           SDValue Load =
2902             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2903                            LN0->getChain(), NewPtr,
2904                            LN0->getPointerInfo(),
2905                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2906                            Alignment, LN0->getTBAAInfo());
2907           AddToWorkList(N);
2908           CombineTo(LN0, Load, Load.getValue(1));
2909           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910         }
2911       }
2912     }
2913   }
2914
2915   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2916       VT.getSizeInBits() <= 64) {
2917     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2918       APInt ADDC = ADDI->getAPIntValue();
2919       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2920         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2921         // immediate for an add, but it is legal if its top c2 bits are set,
2922         // transform the ADD so the immediate doesn't need to be materialized
2923         // in a register.
2924         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2925           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2926                                              SRLI->getZExtValue());
2927           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2928             ADDC |= Mask;
2929             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2930               SDValue NewAdd =
2931                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2932                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2933               CombineTo(N0.getNode(), NewAdd);
2934               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2935             }
2936           }
2937         }
2938       }
2939     }
2940   }
2941
2942   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2943   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2944     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2945                                        N0.getOperand(1), false);
2946     if (BSwap.getNode())
2947       return BSwap;
2948   }
2949
2950   return SDValue();
2951 }
2952
2953 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2954 ///
2955 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2956                                         bool DemandHighBits) {
2957   if (!LegalOperations)
2958     return SDValue();
2959
2960   EVT VT = N->getValueType(0);
2961   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2962     return SDValue();
2963   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2964     return SDValue();
2965
2966   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2967   bool LookPassAnd0 = false;
2968   bool LookPassAnd1 = false;
2969   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2970       std::swap(N0, N1);
2971   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2972       std::swap(N0, N1);
2973   if (N0.getOpcode() == ISD::AND) {
2974     if (!N0.getNode()->hasOneUse())
2975       return SDValue();
2976     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2977     if (!N01C || N01C->getZExtValue() != 0xFF00)
2978       return SDValue();
2979     N0 = N0.getOperand(0);
2980     LookPassAnd0 = true;
2981   }
2982
2983   if (N1.getOpcode() == ISD::AND) {
2984     if (!N1.getNode()->hasOneUse())
2985       return SDValue();
2986     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2987     if (!N11C || N11C->getZExtValue() != 0xFF)
2988       return SDValue();
2989     N1 = N1.getOperand(0);
2990     LookPassAnd1 = true;
2991   }
2992
2993   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2994     std::swap(N0, N1);
2995   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2996     return SDValue();
2997   if (!N0.getNode()->hasOneUse() ||
2998       !N1.getNode()->hasOneUse())
2999     return SDValue();
3000
3001   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3002   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3003   if (!N01C || !N11C)
3004     return SDValue();
3005   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3006     return SDValue();
3007
3008   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3009   SDValue N00 = N0->getOperand(0);
3010   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3011     if (!N00.getNode()->hasOneUse())
3012       return SDValue();
3013     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3014     if (!N001C || N001C->getZExtValue() != 0xFF)
3015       return SDValue();
3016     N00 = N00.getOperand(0);
3017     LookPassAnd0 = true;
3018   }
3019
3020   SDValue N10 = N1->getOperand(0);
3021   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3022     if (!N10.getNode()->hasOneUse())
3023       return SDValue();
3024     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3025     if (!N101C || N101C->getZExtValue() != 0xFF00)
3026       return SDValue();
3027     N10 = N10.getOperand(0);
3028     LookPassAnd1 = true;
3029   }
3030
3031   if (N00 != N10)
3032     return SDValue();
3033
3034   // Make sure everything beyond the low halfword gets set to zero since the SRL
3035   // 16 will clear the top bits.
3036   unsigned OpSizeInBits = VT.getSizeInBits();
3037   if (DemandHighBits && OpSizeInBits > 16) {
3038     // If the left-shift isn't masked out then the only way this is a bswap is
3039     // if all bits beyond the low 8 are 0. In that case the entire pattern
3040     // reduces to a left shift anyway: leave it for other parts of the combiner.
3041     if (!LookPassAnd0)
3042       return SDValue();
3043
3044     // However, if the right shift isn't masked out then it might be because
3045     // it's not needed. See if we can spot that too.
3046     if (!LookPassAnd1 &&
3047         !DAG.MaskedValueIsZero(
3048             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3049       return SDValue();
3050   }
3051
3052   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3053   if (OpSizeInBits > 16)
3054     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3055                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3056   return Res;
3057 }
3058
3059 /// isBSwapHWordElement - Return true if the specified node is an element
3060 /// that makes up a 32-bit packed halfword byteswap. i.e.
3061 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3062 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3063   if (!N.getNode()->hasOneUse())
3064     return false;
3065
3066   unsigned Opc = N.getOpcode();
3067   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3068     return false;
3069
3070   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3071   if (!N1C)
3072     return false;
3073
3074   unsigned Num;
3075   switch (N1C->getZExtValue()) {
3076   default:
3077     return false;
3078   case 0xFF:       Num = 0; break;
3079   case 0xFF00:     Num = 1; break;
3080   case 0xFF0000:   Num = 2; break;
3081   case 0xFF000000: Num = 3; break;
3082   }
3083
3084   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3085   SDValue N0 = N.getOperand(0);
3086   if (Opc == ISD::AND) {
3087     if (Num == 0 || Num == 2) {
3088       // (x >> 8) & 0xff
3089       // (x >> 8) & 0xff0000
3090       if (N0.getOpcode() != ISD::SRL)
3091         return false;
3092       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3093       if (!C || C->getZExtValue() != 8)
3094         return false;
3095     } else {
3096       // (x << 8) & 0xff00
3097       // (x << 8) & 0xff000000
3098       if (N0.getOpcode() != ISD::SHL)
3099         return false;
3100       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3101       if (!C || C->getZExtValue() != 8)
3102         return false;
3103     }
3104   } else if (Opc == ISD::SHL) {
3105     // (x & 0xff) << 8
3106     // (x & 0xff0000) << 8
3107     if (Num != 0 && Num != 2)
3108       return false;
3109     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3110     if (!C || C->getZExtValue() != 8)
3111       return false;
3112   } else { // Opc == ISD::SRL
3113     // (x & 0xff00) >> 8
3114     // (x & 0xff000000) >> 8
3115     if (Num != 1 && Num != 3)
3116       return false;
3117     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3118     if (!C || C->getZExtValue() != 8)
3119       return false;
3120   }
3121
3122   if (Parts[Num])
3123     return false;
3124
3125   Parts[Num] = N0.getOperand(0).getNode();
3126   return true;
3127 }
3128
3129 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3130 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3131 /// => (rotl (bswap x), 16)
3132 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3133   if (!LegalOperations)
3134     return SDValue();
3135
3136   EVT VT = N->getValueType(0);
3137   if (VT != MVT::i32)
3138     return SDValue();
3139   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3140     return SDValue();
3141
3142   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3143   // Look for either
3144   // (or (or (and), (and)), (or (and), (and)))
3145   // (or (or (or (and), (and)), (and)), (and))
3146   if (N0.getOpcode() != ISD::OR)
3147     return SDValue();
3148   SDValue N00 = N0.getOperand(0);
3149   SDValue N01 = N0.getOperand(1);
3150
3151   if (N1.getOpcode() == ISD::OR &&
3152       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3153     // (or (or (and), (and)), (or (and), (and)))
3154     SDValue N000 = N00.getOperand(0);
3155     if (!isBSwapHWordElement(N000, Parts))
3156       return SDValue();
3157
3158     SDValue N001 = N00.getOperand(1);
3159     if (!isBSwapHWordElement(N001, Parts))
3160       return SDValue();
3161     SDValue N010 = N01.getOperand(0);
3162     if (!isBSwapHWordElement(N010, Parts))
3163       return SDValue();
3164     SDValue N011 = N01.getOperand(1);
3165     if (!isBSwapHWordElement(N011, Parts))
3166       return SDValue();
3167   } else {
3168     // (or (or (or (and), (and)), (and)), (and))
3169     if (!isBSwapHWordElement(N1, Parts))
3170       return SDValue();
3171     if (!isBSwapHWordElement(N01, Parts))
3172       return SDValue();
3173     if (N00.getOpcode() != ISD::OR)
3174       return SDValue();
3175     SDValue N000 = N00.getOperand(0);
3176     if (!isBSwapHWordElement(N000, Parts))
3177       return SDValue();
3178     SDValue N001 = N00.getOperand(1);
3179     if (!isBSwapHWordElement(N001, Parts))
3180       return SDValue();
3181   }
3182
3183   // Make sure the parts are all coming from the same node.
3184   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3185     return SDValue();
3186
3187   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3188                               SDValue(Parts[0],0));
3189
3190   // Result of the bswap should be rotated by 16. If it's not legal, then
3191   // do  (x << 16) | (x >> 16).
3192   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3193   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3194     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3195   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3196     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3197   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3198                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3199                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3200 }
3201
3202 SDValue DAGCombiner::visitOR(SDNode *N) {
3203   SDValue N0 = N->getOperand(0);
3204   SDValue N1 = N->getOperand(1);
3205   SDValue LL, LR, RL, RR, CC0, CC1;
3206   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3207   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3208   EVT VT = N1.getValueType();
3209
3210   // fold vector ops
3211   if (VT.isVector()) {
3212     SDValue FoldedVOp = SimplifyVBinOp(N);
3213     if (FoldedVOp.getNode()) return FoldedVOp;
3214
3215     // fold (or x, 0) -> x, vector edition
3216     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3217       return N1;
3218     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3219       return N0;
3220
3221     // fold (or x, -1) -> -1, vector edition
3222     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3223       return N0;
3224     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3225       return N1;
3226
3227     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3228     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3229     // Do this only if the resulting shuffle is legal.
3230     if (isa<ShuffleVectorSDNode>(N0) &&
3231         isa<ShuffleVectorSDNode>(N1) &&
3232         N0->getOperand(1) == N1->getOperand(1) &&
3233         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3234       bool CanFold = true;
3235       unsigned NumElts = VT.getVectorNumElements();
3236       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3237       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3238       // We construct two shuffle masks:
3239       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3240       // and N1 as the second operand.
3241       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3242       // and N0 as the second operand.
3243       // We do this because OR is commutable and therefore there might be
3244       // two ways to fold this node into a shuffle.
3245       SmallVector<int,4> Mask1;
3246       SmallVector<int,4> Mask2;
3247       
3248       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3249         int M0 = SV0->getMaskElt(i);
3250         int M1 = SV1->getMaskElt(i);
3251    
3252         // Both shuffle indexes are undef. Propagate Undef.
3253         if (M0 < 0 && M1 < 0) {
3254           Mask1.push_back(M0);
3255           Mask2.push_back(M0);
3256           continue;
3257         }
3258
3259         if (M0 < 0 || M1 < 0 ||
3260             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3261             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3262           CanFold = false;
3263           break;
3264         }
3265         
3266         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3267         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3268       }
3269
3270       if (CanFold) {
3271         // Fold this sequence only if the resulting shuffle is 'legal'.
3272         if (TLI.isShuffleMaskLegal(Mask1, VT))
3273           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3274                                       N1->getOperand(0), &Mask1[0]);
3275         if (TLI.isShuffleMaskLegal(Mask2, VT))
3276           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3277                                       N0->getOperand(0), &Mask2[0]);
3278       }
3279     }
3280   }
3281
3282   // fold (or x, undef) -> -1
3283   if (!LegalOperations &&
3284       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3285     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3286     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3287   }
3288   // fold (or c1, c2) -> c1|c2
3289   if (N0C && N1C)
3290     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3291   // canonicalize constant to RHS
3292   if (N0C && !N1C)
3293     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3294   // fold (or x, 0) -> x
3295   if (N1C && N1C->isNullValue())
3296     return N0;
3297   // fold (or x, -1) -> -1
3298   if (N1C && N1C->isAllOnesValue())
3299     return N1;
3300   // fold (or x, c) -> c iff (x & ~c) == 0
3301   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3302     return N1;
3303
3304   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3305   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3306   if (BSwap.getNode())
3307     return BSwap;
3308   BSwap = MatchBSwapHWordLow(N, N0, N1);
3309   if (BSwap.getNode())
3310     return BSwap;
3311
3312   // reassociate or
3313   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3314   if (ROR.getNode())
3315     return ROR;
3316   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3317   // iff (c1 & c2) == 0.
3318   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3319              isa<ConstantSDNode>(N0.getOperand(1))) {
3320     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3321     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3322       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3323       if (!COR.getNode())
3324         return SDValue();
3325       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3326                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3327                                      N0.getOperand(0), N1), COR);
3328     }
3329   }
3330   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3331   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3332     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3333     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3334
3335     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3336         LL.getValueType().isInteger()) {
3337       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3338       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3339       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3340           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3341         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3342                                      LR.getValueType(), LL, RL);
3343         AddToWorkList(ORNode.getNode());
3344         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3345       }
3346       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3347       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3348       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3349           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3350         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3351                                       LR.getValueType(), LL, RL);
3352         AddToWorkList(ANDNode.getNode());
3353         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3354       }
3355     }
3356     // canonicalize equivalent to ll == rl
3357     if (LL == RR && LR == RL) {
3358       Op1 = ISD::getSetCCSwappedOperands(Op1);
3359       std::swap(RL, RR);
3360     }
3361     if (LL == RL && LR == RR) {
3362       bool isInteger = LL.getValueType().isInteger();
3363       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3364       if (Result != ISD::SETCC_INVALID &&
3365           (!LegalOperations ||
3366            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3367             TLI.isOperationLegal(ISD::SETCC,
3368               getSetCCResultType(N0.getValueType())))))
3369         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3370                             LL, LR, Result);
3371     }
3372   }
3373
3374   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3375   if (N0.getOpcode() == N1.getOpcode()) {
3376     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3377     if (Tmp.getNode()) return Tmp;
3378   }
3379
3380   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3381   if (N0.getOpcode() == ISD::AND &&
3382       N1.getOpcode() == ISD::AND &&
3383       N0.getOperand(1).getOpcode() == ISD::Constant &&
3384       N1.getOperand(1).getOpcode() == ISD::Constant &&
3385       // Don't increase # computations.
3386       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3387     // We can only do this xform if we know that bits from X that are set in C2
3388     // but not in C1 are already zero.  Likewise for Y.
3389     const APInt &LHSMask =
3390       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3391     const APInt &RHSMask =
3392       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3393
3394     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3395         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3396       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3397                               N0.getOperand(0), N1.getOperand(0));
3398       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3399                          DAG.getConstant(LHSMask | RHSMask, VT));
3400     }
3401   }
3402
3403   // See if this is some rotate idiom.
3404   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3405     return SDValue(Rot, 0);
3406
3407   // Simplify the operands using demanded-bits information.
3408   if (!VT.isVector() &&
3409       SimplifyDemandedBits(SDValue(N, 0)))
3410     return SDValue(N, 0);
3411
3412   return SDValue();
3413 }
3414
3415 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3416 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3417   if (Op.getOpcode() == ISD::AND) {
3418     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3419       Mask = Op.getOperand(1);
3420       Op = Op.getOperand(0);
3421     } else {
3422       return false;
3423     }
3424   }
3425
3426   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3427     Shift = Op;
3428     return true;
3429   }
3430
3431   return false;
3432 }
3433
3434 // Return true if we can prove that, whenever Neg and Pos are both in the
3435 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3436 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3437 //
3438 //     (or (shift1 X, Neg), (shift2 X, Pos))
3439 //
3440 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3441 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3442 // to consider shift amounts with defined behavior.
3443 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3444   // If OpSize is a power of 2 then:
3445   //
3446   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3447   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3448   //
3449   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3450   // for the stronger condition:
3451   //
3452   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3453   //
3454   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3455   // we can just replace Neg with Neg' for the rest of the function.
3456   //
3457   // In other cases we check for the even stronger condition:
3458   //
3459   //     Neg == OpSize - Pos                                    [B]
3460   //
3461   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3462   // behavior if Pos == 0 (and consequently Neg == OpSize).
3463   //
3464   // We could actually use [A] whenever OpSize is a power of 2, but the
3465   // only extra cases that it would match are those uninteresting ones
3466   // where Neg and Pos are never in range at the same time.  E.g. for
3467   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3468   // as well as (sub 32, Pos), but:
3469   //
3470   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3471   //
3472   // always invokes undefined behavior for 32-bit X.
3473   //
3474   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3475   unsigned MaskLoBits = 0;
3476   if (Neg.getOpcode() == ISD::AND &&
3477       isPowerOf2_64(OpSize) &&
3478       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3479       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3480     Neg = Neg.getOperand(0);
3481     MaskLoBits = Log2_64(OpSize);
3482   }
3483
3484   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3485   if (Neg.getOpcode() != ISD::SUB)
3486     return 0;
3487   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3488   if (!NegC)
3489     return 0;
3490   SDValue NegOp1 = Neg.getOperand(1);
3491
3492   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3493   // Pos'.  The truncation is redundant for the purpose of the equality.
3494   if (MaskLoBits &&
3495       Pos.getOpcode() == ISD::AND &&
3496       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3497       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3498     Pos = Pos.getOperand(0);
3499
3500   // The condition we need is now:
3501   //
3502   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3503   //
3504   // If NegOp1 == Pos then we need:
3505   //
3506   //              OpSize & Mask == NegC & Mask
3507   //
3508   // (because "x & Mask" is a truncation and distributes through subtraction).
3509   APInt Width;
3510   if (Pos == NegOp1)
3511     Width = NegC->getAPIntValue();
3512   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3513   // Then the condition we want to prove becomes:
3514   //
3515   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3516   //
3517   // which, again because "x & Mask" is a truncation, becomes:
3518   //
3519   //                NegC & Mask == (OpSize - PosC) & Mask
3520   //              OpSize & Mask == (NegC + PosC) & Mask
3521   else if (Pos.getOpcode() == ISD::ADD &&
3522            Pos.getOperand(0) == NegOp1 &&
3523            Pos.getOperand(1).getOpcode() == ISD::Constant)
3524     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3525              NegC->getAPIntValue());
3526   else
3527     return false;
3528
3529   // Now we just need to check that OpSize & Mask == Width & Mask.
3530   if (MaskLoBits)
3531     // Opsize & Mask is 0 since Mask is Opsize - 1.
3532     return Width.getLoBits(MaskLoBits) == 0;
3533   return Width == OpSize;
3534 }
3535
3536 // A subroutine of MatchRotate used once we have found an OR of two opposite
3537 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3538 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3539 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3540 // Neg with outer conversions stripped away.
3541 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3542                                        SDValue Neg, SDValue InnerPos,
3543                                        SDValue InnerNeg, unsigned PosOpcode,
3544                                        unsigned NegOpcode, SDLoc DL) {
3545   // fold (or (shl x, (*ext y)),
3546   //          (srl x, (*ext (sub 32, y)))) ->
3547   //   (rotl x, y) or (rotr x, (sub 32, y))
3548   //
3549   // fold (or (shl x, (*ext (sub 32, y))),
3550   //          (srl x, (*ext y))) ->
3551   //   (rotr x, y) or (rotl x, (sub 32, y))
3552   EVT VT = Shifted.getValueType();
3553   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3554     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3555     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3556                        HasPos ? Pos : Neg).getNode();
3557   }
3558
3559   return nullptr;
3560 }
3561
3562 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3563 // idioms for rotate, and if the target supports rotation instructions, generate
3564 // a rot[lr].
3565 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3566   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3567   EVT VT = LHS.getValueType();
3568   if (!TLI.isTypeLegal(VT)) return nullptr;
3569
3570   // The target must have at least one rotate flavor.
3571   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3572   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3573   if (!HasROTL && !HasROTR) return nullptr;
3574
3575   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3576   SDValue LHSShift;   // The shift.
3577   SDValue LHSMask;    // AND value if any.
3578   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3579     return nullptr; // Not part of a rotate.
3580
3581   SDValue RHSShift;   // The shift.
3582   SDValue RHSMask;    // AND value if any.
3583   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3584     return nullptr; // Not part of a rotate.
3585
3586   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3587     return nullptr;   // Not shifting the same value.
3588
3589   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3590     return nullptr;   // Shifts must disagree.
3591
3592   // Canonicalize shl to left side in a shl/srl pair.
3593   if (RHSShift.getOpcode() == ISD::SHL) {
3594     std::swap(LHS, RHS);
3595     std::swap(LHSShift, RHSShift);
3596     std::swap(LHSMask , RHSMask );
3597   }
3598
3599   unsigned OpSizeInBits = VT.getSizeInBits();
3600   SDValue LHSShiftArg = LHSShift.getOperand(0);
3601   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3602   SDValue RHSShiftArg = RHSShift.getOperand(0);
3603   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3604
3605   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3606   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3607   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3608       RHSShiftAmt.getOpcode() == ISD::Constant) {
3609     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3610     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3611     if ((LShVal + RShVal) != OpSizeInBits)
3612       return nullptr;
3613
3614     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3615                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3616
3617     // If there is an AND of either shifted operand, apply it to the result.
3618     if (LHSMask.getNode() || RHSMask.getNode()) {
3619       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3620
3621       if (LHSMask.getNode()) {
3622         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3623         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3624       }
3625       if (RHSMask.getNode()) {
3626         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3627         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3628       }
3629
3630       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3631     }
3632
3633     return Rot.getNode();
3634   }
3635
3636   // If there is a mask here, and we have a variable shift, we can't be sure
3637   // that we're masking out the right stuff.
3638   if (LHSMask.getNode() || RHSMask.getNode())
3639     return nullptr;
3640
3641   // If the shift amount is sign/zext/any-extended just peel it off.
3642   SDValue LExtOp0 = LHSShiftAmt;
3643   SDValue RExtOp0 = RHSShiftAmt;
3644   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3645        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3646        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3647        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3648       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3649        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3650        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3651        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3652     LExtOp0 = LHSShiftAmt.getOperand(0);
3653     RExtOp0 = RHSShiftAmt.getOperand(0);
3654   }
3655
3656   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3657                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3658   if (TryL)
3659     return TryL;
3660
3661   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3662                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3663   if (TryR)
3664     return TryR;
3665
3666   return nullptr;
3667 }
3668
3669 SDValue DAGCombiner::visitXOR(SDNode *N) {
3670   SDValue N0 = N->getOperand(0);
3671   SDValue N1 = N->getOperand(1);
3672   SDValue LHS, RHS, CC;
3673   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3674   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3675   EVT VT = N0.getValueType();
3676
3677   // fold vector ops
3678   if (VT.isVector()) {
3679     SDValue FoldedVOp = SimplifyVBinOp(N);
3680     if (FoldedVOp.getNode()) return FoldedVOp;
3681
3682     // fold (xor x, 0) -> x, vector edition
3683     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3684       return N1;
3685     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3686       return N0;
3687   }
3688
3689   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3690   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3691     return DAG.getConstant(0, VT);
3692   // fold (xor x, undef) -> undef
3693   if (N0.getOpcode() == ISD::UNDEF)
3694     return N0;
3695   if (N1.getOpcode() == ISD::UNDEF)
3696     return N1;
3697   // fold (xor c1, c2) -> c1^c2
3698   if (N0C && N1C)
3699     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3700   // canonicalize constant to RHS
3701   if (N0C && !N1C)
3702     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3703   // fold (xor x, 0) -> x
3704   if (N1C && N1C->isNullValue())
3705     return N0;
3706   // reassociate xor
3707   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3708   if (RXOR.getNode())
3709     return RXOR;
3710
3711   // fold !(x cc y) -> (x !cc y)
3712   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3713     bool isInt = LHS.getValueType().isInteger();
3714     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3715                                                isInt);
3716
3717     if (!LegalOperations ||
3718         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3719       switch (N0.getOpcode()) {
3720       default:
3721         llvm_unreachable("Unhandled SetCC Equivalent!");
3722       case ISD::SETCC:
3723         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3724       case ISD::SELECT_CC:
3725         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3726                                N0.getOperand(3), NotCC);
3727       }
3728     }
3729   }
3730
3731   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3732   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3733       N0.getNode()->hasOneUse() &&
3734       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3735     SDValue V = N0.getOperand(0);
3736     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3737                     DAG.getConstant(1, V.getValueType()));
3738     AddToWorkList(V.getNode());
3739     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3740   }
3741
3742   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3743   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3744       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3745     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3746     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3747       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3748       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3749       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3750       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3751       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3752     }
3753   }
3754   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3755   if (N1C && N1C->isAllOnesValue() &&
3756       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3757     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3758     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3759       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3760       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3761       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3762       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3763       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3764     }
3765   }
3766   // fold (xor (and x, y), y) -> (and (not x), y)
3767   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3768       N0->getOperand(1) == N1) {
3769     SDValue X = N0->getOperand(0);
3770     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3771     AddToWorkList(NotX.getNode());
3772     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3773   }
3774   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3775   if (N1C && N0.getOpcode() == ISD::XOR) {
3776     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3777     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3778     if (N00C)
3779       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3780                          DAG.getConstant(N1C->getAPIntValue() ^
3781                                          N00C->getAPIntValue(), VT));
3782     if (N01C)
3783       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3784                          DAG.getConstant(N1C->getAPIntValue() ^
3785                                          N01C->getAPIntValue(), VT));
3786   }
3787   // fold (xor x, x) -> 0
3788   if (N0 == N1)
3789     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3790
3791   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3792   if (N0.getOpcode() == N1.getOpcode()) {
3793     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3794     if (Tmp.getNode()) return Tmp;
3795   }
3796
3797   // Simplify the expression using non-local knowledge.
3798   if (!VT.isVector() &&
3799       SimplifyDemandedBits(SDValue(N, 0)))
3800     return SDValue(N, 0);
3801
3802   return SDValue();
3803 }
3804
3805 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3806 /// the shift amount is a constant.
3807 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3808   // We can't and shouldn't fold opaque constants.
3809   if (Amt->isOpaque())
3810     return SDValue();
3811
3812   SDNode *LHS = N->getOperand(0).getNode();
3813   if (!LHS->hasOneUse()) return SDValue();
3814
3815   // We want to pull some binops through shifts, so that we have (and (shift))
3816   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3817   // thing happens with address calculations, so it's important to canonicalize
3818   // it.
3819   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3820
3821   switch (LHS->getOpcode()) {
3822   default: return SDValue();
3823   case ISD::OR:
3824   case ISD::XOR:
3825     HighBitSet = false; // We can only transform sra if the high bit is clear.
3826     break;
3827   case ISD::AND:
3828     HighBitSet = true;  // We can only transform sra if the high bit is set.
3829     break;
3830   case ISD::ADD:
3831     if (N->getOpcode() != ISD::SHL)
3832       return SDValue(); // only shl(add) not sr[al](add).
3833     HighBitSet = false; // We can only transform sra if the high bit is clear.
3834     break;
3835   }
3836
3837   // We require the RHS of the binop to be a constant and not opaque as well.
3838   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3839   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3840
3841   // FIXME: disable this unless the input to the binop is a shift by a constant.
3842   // If it is not a shift, it pessimizes some common cases like:
3843   //
3844   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3845   //    int bar(int *X, int i) { return X[i & 255]; }
3846   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3847   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3848        BinOpLHSVal->getOpcode() != ISD::SRA &&
3849        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3850       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3851     return SDValue();
3852
3853   EVT VT = N->getValueType(0);
3854
3855   // If this is a signed shift right, and the high bit is modified by the
3856   // logical operation, do not perform the transformation. The highBitSet
3857   // boolean indicates the value of the high bit of the constant which would
3858   // cause it to be modified for this operation.
3859   if (N->getOpcode() == ISD::SRA) {
3860     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3861     if (BinOpRHSSignSet != HighBitSet)
3862       return SDValue();
3863   }
3864
3865   // Fold the constants, shifting the binop RHS by the shift amount.
3866   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3867                                N->getValueType(0),
3868                                LHS->getOperand(1), N->getOperand(1));
3869   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3870
3871   // Create the new shift.
3872   SDValue NewShift = DAG.getNode(N->getOpcode(),
3873                                  SDLoc(LHS->getOperand(0)),
3874                                  VT, LHS->getOperand(0), N->getOperand(1));
3875
3876   // Create the new binop.
3877   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3878 }
3879
3880 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3881   assert(N->getOpcode() == ISD::TRUNCATE);
3882   assert(N->getOperand(0).getOpcode() == ISD::AND);
3883
3884   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3885   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3886     SDValue N01 = N->getOperand(0).getOperand(1);
3887
3888     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3889       EVT TruncVT = N->getValueType(0);
3890       SDValue N00 = N->getOperand(0).getOperand(0);
3891       APInt TruncC = N01C->getAPIntValue();
3892       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3893
3894       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3895                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3896                          DAG.getConstant(TruncC, TruncVT));
3897     }
3898   }
3899
3900   return SDValue();
3901 }
3902
3903 SDValue DAGCombiner::visitRotate(SDNode *N) {
3904   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3905   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3906       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3907     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3908     if (NewOp1.getNode())
3909       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3910                          N->getOperand(0), NewOp1);
3911   }
3912   return SDValue();
3913 }
3914
3915 SDValue DAGCombiner::visitSHL(SDNode *N) {
3916   SDValue N0 = N->getOperand(0);
3917   SDValue N1 = N->getOperand(1);
3918   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3919   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3920   EVT VT = N0.getValueType();
3921   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3922
3923   // fold vector ops
3924   if (VT.isVector()) {
3925     SDValue FoldedVOp = SimplifyVBinOp(N);
3926     if (FoldedVOp.getNode()) return FoldedVOp;
3927
3928     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3929     // If setcc produces all-one true value then:
3930     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3931     if (N1CV && N1CV->isConstant()) {
3932       if (N0.getOpcode() == ISD::AND &&
3933           TLI.getBooleanContents(true) ==
3934           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3935         SDValue N00 = N0->getOperand(0);
3936         SDValue N01 = N0->getOperand(1);
3937         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3938
3939         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3940           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3941           if (C.getNode())
3942             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3943         }
3944       } else {
3945         N1C = isConstOrConstSplat(N1);
3946       }
3947     }
3948   }
3949
3950   // fold (shl c1, c2) -> c1<<c2
3951   if (N0C && N1C)
3952     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3953   // fold (shl 0, x) -> 0
3954   if (N0C && N0C->isNullValue())
3955     return N0;
3956   // fold (shl x, c >= size(x)) -> undef
3957   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3958     return DAG.getUNDEF(VT);
3959   // fold (shl x, 0) -> x
3960   if (N1C && N1C->isNullValue())
3961     return N0;
3962   // fold (shl undef, x) -> 0
3963   if (N0.getOpcode() == ISD::UNDEF)
3964     return DAG.getConstant(0, VT);
3965   // if (shl x, c) is known to be zero, return 0
3966   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3967                             APInt::getAllOnesValue(OpSizeInBits)))
3968     return DAG.getConstant(0, VT);
3969   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3970   if (N1.getOpcode() == ISD::TRUNCATE &&
3971       N1.getOperand(0).getOpcode() == ISD::AND) {
3972     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3973     if (NewOp1.getNode())
3974       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3975   }
3976
3977   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3978     return SDValue(N, 0);
3979
3980   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3981   if (N1C && N0.getOpcode() == ISD::SHL) {
3982     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
3983       uint64_t c1 = N0C1->getZExtValue();
3984       uint64_t c2 = N1C->getZExtValue();
3985       if (c1 + c2 >= OpSizeInBits)
3986         return DAG.getConstant(0, VT);
3987       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3988                          DAG.getConstant(c1 + c2, N1.getValueType()));
3989     }
3990   }
3991
3992   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3993   // For this to be valid, the second form must not preserve any of the bits
3994   // that are shifted out by the inner shift in the first form.  This means
3995   // the outer shift size must be >= the number of bits added by the ext.
3996   // As a corollary, we don't care what kind of ext it is.
3997   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3998               N0.getOpcode() == ISD::ANY_EXTEND ||
3999               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4000       N0.getOperand(0).getOpcode() == ISD::SHL) {
4001     SDValue N0Op0 = N0.getOperand(0);
4002     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4003       uint64_t c1 = N0Op0C1->getZExtValue();
4004       uint64_t c2 = N1C->getZExtValue();
4005       EVT InnerShiftVT = N0Op0.getValueType();
4006       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4007       if (c2 >= OpSizeInBits - InnerShiftSize) {
4008         if (c1 + c2 >= OpSizeInBits)
4009           return DAG.getConstant(0, VT);
4010         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4011                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4012                                        N0Op0->getOperand(0)),
4013                            DAG.getConstant(c1 + c2, N1.getValueType()));
4014       }
4015     }
4016   }
4017
4018   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4019   // Only fold this if the inner zext has no other uses to avoid increasing
4020   // the total number of instructions.
4021   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4022       N0.getOperand(0).getOpcode() == ISD::SRL) {
4023     SDValue N0Op0 = N0.getOperand(0);
4024     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4025       uint64_t c1 = N0Op0C1->getZExtValue();
4026       if (c1 < VT.getScalarSizeInBits()) {
4027         uint64_t c2 = N1C->getZExtValue();
4028         if (c1 == c2) {
4029           SDValue NewOp0 = N0.getOperand(0);
4030           EVT CountVT = NewOp0.getOperand(1).getValueType();
4031           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4032                                        NewOp0, DAG.getConstant(c2, CountVT));
4033           AddToWorkList(NewSHL.getNode());
4034           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4035         }
4036       }
4037     }
4038   }
4039
4040   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4041   //                               (and (srl x, (sub c1, c2), MASK)
4042   // Only fold this if the inner shift has no other uses -- if it does, folding
4043   // this will increase the total number of instructions.
4044   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4045     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4046       uint64_t c1 = N0C1->getZExtValue();
4047       if (c1 < OpSizeInBits) {
4048         uint64_t c2 = N1C->getZExtValue();
4049         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4050         SDValue Shift;
4051         if (c2 > c1) {
4052           Mask = Mask.shl(c2 - c1);
4053           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4054                               DAG.getConstant(c2 - c1, N1.getValueType()));
4055         } else {
4056           Mask = Mask.lshr(c1 - c2);
4057           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4058                               DAG.getConstant(c1 - c2, N1.getValueType()));
4059         }
4060         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4061                            DAG.getConstant(Mask, VT));
4062       }
4063     }
4064   }
4065   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4066   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4067     unsigned BitSize = VT.getScalarSizeInBits();
4068     SDValue HiBitsMask =
4069       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4070                                             BitSize - N1C->getZExtValue()), VT);
4071     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4072                        HiBitsMask);
4073   }
4074
4075   if (N1C) {
4076     SDValue NewSHL = visitShiftByConstant(N, N1C);
4077     if (NewSHL.getNode())
4078       return NewSHL;
4079   }
4080
4081   return SDValue();
4082 }
4083
4084 SDValue DAGCombiner::visitSRA(SDNode *N) {
4085   SDValue N0 = N->getOperand(0);
4086   SDValue N1 = N->getOperand(1);
4087   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4088   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4089   EVT VT = N0.getValueType();
4090   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4091
4092   // fold vector ops
4093   if (VT.isVector()) {
4094     SDValue FoldedVOp = SimplifyVBinOp(N);
4095     if (FoldedVOp.getNode()) return FoldedVOp;
4096
4097     N1C = isConstOrConstSplat(N1);
4098   }
4099
4100   // fold (sra c1, c2) -> (sra c1, c2)
4101   if (N0C && N1C)
4102     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4103   // fold (sra 0, x) -> 0
4104   if (N0C && N0C->isNullValue())
4105     return N0;
4106   // fold (sra -1, x) -> -1
4107   if (N0C && N0C->isAllOnesValue())
4108     return N0;
4109   // fold (sra x, (setge c, size(x))) -> undef
4110   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4111     return DAG.getUNDEF(VT);
4112   // fold (sra x, 0) -> x
4113   if (N1C && N1C->isNullValue())
4114     return N0;
4115   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4116   // sext_inreg.
4117   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4118     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4119     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4120     if (VT.isVector())
4121       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4122                                ExtVT, VT.getVectorNumElements());
4123     if ((!LegalOperations ||
4124          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4125       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4126                          N0.getOperand(0), DAG.getValueType(ExtVT));
4127   }
4128
4129   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4130   if (N1C && N0.getOpcode() == ISD::SRA) {
4131     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4132       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4133       if (Sum >= OpSizeInBits)
4134         Sum = OpSizeInBits - 1;
4135       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4136                          DAG.getConstant(Sum, N1.getValueType()));
4137     }
4138   }
4139
4140   // fold (sra (shl X, m), (sub result_size, n))
4141   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4142   // result_size - n != m.
4143   // If truncate is free for the target sext(shl) is likely to result in better
4144   // code.
4145   if (N0.getOpcode() == ISD::SHL && N1C) {
4146     // Get the two constanst of the shifts, CN0 = m, CN = n.
4147     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4148     if (N01C) {
4149       LLVMContext &Ctx = *DAG.getContext();
4150       // Determine what the truncate's result bitsize and type would be.
4151       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4152
4153       if (VT.isVector())
4154         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4155
4156       // Determine the residual right-shift amount.
4157       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4158
4159       // If the shift is not a no-op (in which case this should be just a sign
4160       // extend already), the truncated to type is legal, sign_extend is legal
4161       // on that type, and the truncate to that type is both legal and free,
4162       // perform the transform.
4163       if ((ShiftAmt > 0) &&
4164           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4165           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4166           TLI.isTruncateFree(VT, TruncVT)) {
4167
4168           SDValue Amt = DAG.getConstant(ShiftAmt,
4169               getShiftAmountTy(N0.getOperand(0).getValueType()));
4170           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4171                                       N0.getOperand(0), Amt);
4172           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4173                                       Shift);
4174           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4175                              N->getValueType(0), Trunc);
4176       }
4177     }
4178   }
4179
4180   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4181   if (N1.getOpcode() == ISD::TRUNCATE &&
4182       N1.getOperand(0).getOpcode() == ISD::AND) {
4183     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4184     if (NewOp1.getNode())
4185       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4186   }
4187
4188   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4189   //      if c1 is equal to the number of bits the trunc removes
4190   if (N0.getOpcode() == ISD::TRUNCATE &&
4191       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4192        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4193       N0.getOperand(0).hasOneUse() &&
4194       N0.getOperand(0).getOperand(1).hasOneUse() &&
4195       N1C) {
4196     SDValue N0Op0 = N0.getOperand(0);
4197     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4198       unsigned LargeShiftVal = LargeShift->getZExtValue();
4199       EVT LargeVT = N0Op0.getValueType();
4200
4201       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4202         SDValue Amt =
4203           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4204                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4205         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4206                                   N0Op0.getOperand(0), Amt);
4207         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4208       }
4209     }
4210   }
4211
4212   // Simplify, based on bits shifted out of the LHS.
4213   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4214     return SDValue(N, 0);
4215
4216
4217   // If the sign bit is known to be zero, switch this to a SRL.
4218   if (DAG.SignBitIsZero(N0))
4219     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4220
4221   if (N1C) {
4222     SDValue NewSRA = visitShiftByConstant(N, N1C);
4223     if (NewSRA.getNode())
4224       return NewSRA;
4225   }
4226
4227   return SDValue();
4228 }
4229
4230 SDValue DAGCombiner::visitSRL(SDNode *N) {
4231   SDValue N0 = N->getOperand(0);
4232   SDValue N1 = N->getOperand(1);
4233   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4234   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4235   EVT VT = N0.getValueType();
4236   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4237
4238   // fold vector ops
4239   if (VT.isVector()) {
4240     SDValue FoldedVOp = SimplifyVBinOp(N);
4241     if (FoldedVOp.getNode()) return FoldedVOp;
4242
4243     N1C = isConstOrConstSplat(N1);
4244   }
4245
4246   // fold (srl c1, c2) -> c1 >>u c2
4247   if (N0C && N1C)
4248     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4249   // fold (srl 0, x) -> 0
4250   if (N0C && N0C->isNullValue())
4251     return N0;
4252   // fold (srl x, c >= size(x)) -> undef
4253   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4254     return DAG.getUNDEF(VT);
4255   // fold (srl x, 0) -> x
4256   if (N1C && N1C->isNullValue())
4257     return N0;
4258   // if (srl x, c) is known to be zero, return 0
4259   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4260                                    APInt::getAllOnesValue(OpSizeInBits)))
4261     return DAG.getConstant(0, VT);
4262
4263   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4264   if (N1C && N0.getOpcode() == ISD::SRL) {
4265     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4266       uint64_t c1 = N01C->getZExtValue();
4267       uint64_t c2 = N1C->getZExtValue();
4268       if (c1 + c2 >= OpSizeInBits)
4269         return DAG.getConstant(0, VT);
4270       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4271                          DAG.getConstant(c1 + c2, N1.getValueType()));
4272     }
4273   }
4274
4275   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4276   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4277       N0.getOperand(0).getOpcode() == ISD::SRL &&
4278       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4279     uint64_t c1 =
4280       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4281     uint64_t c2 = N1C->getZExtValue();
4282     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4283     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4284     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4285     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4286     if (c1 + OpSizeInBits == InnerShiftSize) {
4287       if (c1 + c2 >= InnerShiftSize)
4288         return DAG.getConstant(0, VT);
4289       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4290                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4291                                      N0.getOperand(0)->getOperand(0),
4292                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4293     }
4294   }
4295
4296   // fold (srl (shl x, c), c) -> (and x, cst2)
4297   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4298     unsigned BitSize = N0.getScalarValueSizeInBits();
4299     if (BitSize <= 64) {
4300       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4301       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4302                          DAG.getConstant(~0ULL >> ShAmt, VT));
4303     }
4304   }
4305
4306   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4307   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4308     // Shifting in all undef bits?
4309     EVT SmallVT = N0.getOperand(0).getValueType();
4310     unsigned BitSize = SmallVT.getScalarSizeInBits();
4311     if (N1C->getZExtValue() >= BitSize)
4312       return DAG.getUNDEF(VT);
4313
4314     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4315       uint64_t ShiftAmt = N1C->getZExtValue();
4316       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4317                                        N0.getOperand(0),
4318                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4319       AddToWorkList(SmallShift.getNode());
4320       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4321       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4322                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4323                          DAG.getConstant(Mask, VT));
4324     }
4325   }
4326
4327   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4328   // bit, which is unmodified by sra.
4329   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4330     if (N0.getOpcode() == ISD::SRA)
4331       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4332   }
4333
4334   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4335   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4336       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4337     APInt KnownZero, KnownOne;
4338     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4339
4340     // If any of the input bits are KnownOne, then the input couldn't be all
4341     // zeros, thus the result of the srl will always be zero.
4342     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4343
4344     // If all of the bits input the to ctlz node are known to be zero, then
4345     // the result of the ctlz is "32" and the result of the shift is one.
4346     APInt UnknownBits = ~KnownZero;
4347     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4348
4349     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4350     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4351       // Okay, we know that only that the single bit specified by UnknownBits
4352       // could be set on input to the CTLZ node. If this bit is set, the SRL
4353       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4354       // to an SRL/XOR pair, which is likely to simplify more.
4355       unsigned ShAmt = UnknownBits.countTrailingZeros();
4356       SDValue Op = N0.getOperand(0);
4357
4358       if (ShAmt) {
4359         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4360                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4361         AddToWorkList(Op.getNode());
4362       }
4363
4364       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4365                          Op, DAG.getConstant(1, VT));
4366     }
4367   }
4368
4369   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4370   if (N1.getOpcode() == ISD::TRUNCATE &&
4371       N1.getOperand(0).getOpcode() == ISD::AND) {
4372     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4373     if (NewOp1.getNode())
4374       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4375   }
4376
4377   // fold operands of srl based on knowledge that the low bits are not
4378   // demanded.
4379   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4380     return SDValue(N, 0);
4381
4382   if (N1C) {
4383     SDValue NewSRL = visitShiftByConstant(N, N1C);
4384     if (NewSRL.getNode())
4385       return NewSRL;
4386   }
4387
4388   // Attempt to convert a srl of a load into a narrower zero-extending load.
4389   SDValue NarrowLoad = ReduceLoadWidth(N);
4390   if (NarrowLoad.getNode())
4391     return NarrowLoad;
4392
4393   // Here is a common situation. We want to optimize:
4394   //
4395   //   %a = ...
4396   //   %b = and i32 %a, 2
4397   //   %c = srl i32 %b, 1
4398   //   brcond i32 %c ...
4399   //
4400   // into
4401   //
4402   //   %a = ...
4403   //   %b = and %a, 2
4404   //   %c = setcc eq %b, 0
4405   //   brcond %c ...
4406   //
4407   // However when after the source operand of SRL is optimized into AND, the SRL
4408   // itself may not be optimized further. Look for it and add the BRCOND into
4409   // the worklist.
4410   if (N->hasOneUse()) {
4411     SDNode *Use = *N->use_begin();
4412     if (Use->getOpcode() == ISD::BRCOND)
4413       AddToWorkList(Use);
4414     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4415       // Also look pass the truncate.
4416       Use = *Use->use_begin();
4417       if (Use->getOpcode() == ISD::BRCOND)
4418         AddToWorkList(Use);
4419     }
4420   }
4421
4422   return SDValue();
4423 }
4424
4425 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4426   SDValue N0 = N->getOperand(0);
4427   EVT VT = N->getValueType(0);
4428
4429   // fold (ctlz c1) -> c2
4430   if (isa<ConstantSDNode>(N0))
4431     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4432   return SDValue();
4433 }
4434
4435 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4436   SDValue N0 = N->getOperand(0);
4437   EVT VT = N->getValueType(0);
4438
4439   // fold (ctlz_zero_undef c1) -> c2
4440   if (isa<ConstantSDNode>(N0))
4441     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4442   return SDValue();
4443 }
4444
4445 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4446   SDValue N0 = N->getOperand(0);
4447   EVT VT = N->getValueType(0);
4448
4449   // fold (cttz c1) -> c2
4450   if (isa<ConstantSDNode>(N0))
4451     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4452   return SDValue();
4453 }
4454
4455 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4456   SDValue N0 = N->getOperand(0);
4457   EVT VT = N->getValueType(0);
4458
4459   // fold (cttz_zero_undef c1) -> c2
4460   if (isa<ConstantSDNode>(N0))
4461     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4462   return SDValue();
4463 }
4464
4465 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4466   SDValue N0 = N->getOperand(0);
4467   EVT VT = N->getValueType(0);
4468
4469   // fold (ctpop c1) -> c2
4470   if (isa<ConstantSDNode>(N0))
4471     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4472   return SDValue();
4473 }
4474
4475 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4476   SDValue N0 = N->getOperand(0);
4477   SDValue N1 = N->getOperand(1);
4478   SDValue N2 = N->getOperand(2);
4479   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4480   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4481   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4482   EVT VT = N->getValueType(0);
4483   EVT VT0 = N0.getValueType();
4484
4485   // fold (select C, X, X) -> X
4486   if (N1 == N2)
4487     return N1;
4488   // fold (select true, X, Y) -> X
4489   if (N0C && !N0C->isNullValue())
4490     return N1;
4491   // fold (select false, X, Y) -> Y
4492   if (N0C && N0C->isNullValue())
4493     return N2;
4494   // fold (select C, 1, X) -> (or C, X)
4495   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4496     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4497   // fold (select C, 0, 1) -> (xor C, 1)
4498   if (VT.isInteger() &&
4499       (VT0 == MVT::i1 ||
4500        (VT0.isInteger() &&
4501         TLI.getBooleanContents(false) ==
4502         TargetLowering::ZeroOrOneBooleanContent)) &&
4503       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4504     SDValue XORNode;
4505     if (VT == VT0)
4506       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4507                          N0, DAG.getConstant(1, VT0));
4508     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4509                           N0, DAG.getConstant(1, VT0));
4510     AddToWorkList(XORNode.getNode());
4511     if (VT.bitsGT(VT0))
4512       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4513     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4514   }
4515   // fold (select C, 0, X) -> (and (not C), X)
4516   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4517     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4518     AddToWorkList(NOTNode.getNode());
4519     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4520   }
4521   // fold (select C, X, 1) -> (or (not C), X)
4522   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4523     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4524     AddToWorkList(NOTNode.getNode());
4525     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4526   }
4527   // fold (select C, X, 0) -> (and C, X)
4528   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4529     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4530   // fold (select X, X, Y) -> (or X, Y)
4531   // fold (select X, 1, Y) -> (or X, Y)
4532   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4533     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4534   // fold (select X, Y, X) -> (and X, Y)
4535   // fold (select X, Y, 0) -> (and X, Y)
4536   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4537     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4538
4539   // If we can fold this based on the true/false value, do so.
4540   if (SimplifySelectOps(N, N1, N2))
4541     return SDValue(N, 0);  // Don't revisit N.
4542
4543   // fold selects based on a setcc into other things, such as min/max/abs
4544   if (N0.getOpcode() == ISD::SETCC) {
4545     // FIXME:
4546     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4547     // having to say they don't support SELECT_CC on every type the DAG knows
4548     // about, since there is no way to mark an opcode illegal at all value types
4549     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4550         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4551       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4552                          N0.getOperand(0), N0.getOperand(1),
4553                          N1, N2, N0.getOperand(2));
4554     return SimplifySelect(SDLoc(N), N0, N1, N2);
4555   }
4556
4557   return SDValue();
4558 }
4559
4560 static
4561 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4562   SDLoc DL(N);
4563   EVT LoVT, HiVT;
4564   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4565
4566   // Split the inputs.
4567   SDValue Lo, Hi, LL, LH, RL, RH;
4568   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4569   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4570
4571   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4572   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4573
4574   return std::make_pair(Lo, Hi);
4575 }
4576
4577 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4578   SDValue N0 = N->getOperand(0);
4579   SDValue N1 = N->getOperand(1);
4580   SDValue N2 = N->getOperand(2);
4581   SDLoc DL(N);
4582
4583   // Canonicalize integer abs.
4584   // vselect (setg[te] X,  0),  X, -X ->
4585   // vselect (setgt    X, -1),  X, -X ->
4586   // vselect (setl[te] X,  0), -X,  X ->
4587   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4588   if (N0.getOpcode() == ISD::SETCC) {
4589     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4590     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4591     bool isAbs = false;
4592     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4593
4594     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4595          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4596         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4597       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4598     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4599              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4600       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4601
4602     if (isAbs) {
4603       EVT VT = LHS.getValueType();
4604       SDValue Shift = DAG.getNode(
4605           ISD::SRA, DL, VT, LHS,
4606           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4607       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4608       AddToWorkList(Shift.getNode());
4609       AddToWorkList(Add.getNode());
4610       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4611     }
4612   }
4613
4614   // If the VSELECT result requires splitting and the mask is provided by a
4615   // SETCC, then split both nodes and its operands before legalization. This
4616   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4617   // and enables future optimizations (e.g. min/max pattern matching on X86).
4618   if (N0.getOpcode() == ISD::SETCC) {
4619     EVT VT = N->getValueType(0);
4620
4621     // Check if any splitting is required.
4622     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4623         TargetLowering::TypeSplitVector)
4624       return SDValue();
4625
4626     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4627     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4628     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4629     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4630
4631     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4632     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4633
4634     // Add the new VSELECT nodes to the work list in case they need to be split
4635     // again.
4636     AddToWorkList(Lo.getNode());
4637     AddToWorkList(Hi.getNode());
4638
4639     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4640   }
4641
4642   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4643   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4644     return N1;
4645   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4646   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4647     return N2;
4648
4649   return SDValue();
4650 }
4651
4652 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4653   SDValue N0 = N->getOperand(0);
4654   SDValue N1 = N->getOperand(1);
4655   SDValue N2 = N->getOperand(2);
4656   SDValue N3 = N->getOperand(3);
4657   SDValue N4 = N->getOperand(4);
4658   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4659
4660   // fold select_cc lhs, rhs, x, x, cc -> x
4661   if (N2 == N3)
4662     return N2;
4663
4664   // Determine if the condition we're dealing with is constant
4665   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4666                               N0, N1, CC, SDLoc(N), false);
4667   if (SCC.getNode()) {
4668     AddToWorkList(SCC.getNode());
4669
4670     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4671       if (!SCCC->isNullValue())
4672         return N2;    // cond always true -> true val
4673       else
4674         return N3;    // cond always false -> false val
4675     }
4676
4677     // Fold to a simpler select_cc
4678     if (SCC.getOpcode() == ISD::SETCC)
4679       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4680                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4681                          SCC.getOperand(2));
4682   }
4683
4684   // If we can fold this based on the true/false value, do so.
4685   if (SimplifySelectOps(N, N2, N3))
4686     return SDValue(N, 0);  // Don't revisit N.
4687
4688   // fold select_cc into other things, such as min/max/abs
4689   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4690 }
4691
4692 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4693   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4694                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4695                        SDLoc(N));
4696 }
4697
4698 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4699 // dag node into a ConstantSDNode or a build_vector of constants.
4700 // This function is called by the DAGCombiner when visiting sext/zext/aext
4701 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4702 // Vector extends are not folded if operations are legal; this is to
4703 // avoid introducing illegal build_vector dag nodes.
4704 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4705                                          SelectionDAG &DAG, bool LegalTypes,
4706                                          bool LegalOperations) {
4707   unsigned Opcode = N->getOpcode();
4708   SDValue N0 = N->getOperand(0);
4709   EVT VT = N->getValueType(0);
4710
4711   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4712          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4713
4714   // fold (sext c1) -> c1
4715   // fold (zext c1) -> c1
4716   // fold (aext c1) -> c1
4717   if (isa<ConstantSDNode>(N0))
4718     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4719
4720   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4721   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4722   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4723   EVT SVT = VT.getScalarType();
4724   if (!(VT.isVector() &&
4725       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4726       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4727     return nullptr;
4728   
4729   // We can fold this node into a build_vector.
4730   unsigned VTBits = SVT.getSizeInBits();
4731   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4732   unsigned ShAmt = VTBits - EVTBits;
4733   SmallVector<SDValue, 8> Elts;
4734   unsigned NumElts = N0->getNumOperands();
4735   SDLoc DL(N);
4736
4737   for (unsigned i=0; i != NumElts; ++i) {
4738     SDValue Op = N0->getOperand(i);
4739     if (Op->getOpcode() == ISD::UNDEF) {
4740       Elts.push_back(DAG.getUNDEF(SVT));
4741       continue;
4742     }
4743
4744     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4745     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4746     if (Opcode == ISD::SIGN_EXTEND)
4747       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4748                                      SVT));
4749     else
4750       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4751                                      SVT));
4752   }
4753
4754   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4755 }
4756
4757 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4758 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4759 // transformation. Returns true if extension are possible and the above
4760 // mentioned transformation is profitable.
4761 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4762                                     unsigned ExtOpc,
4763                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4764                                     const TargetLowering &TLI) {
4765   bool HasCopyToRegUses = false;
4766   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4767   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4768                             UE = N0.getNode()->use_end();
4769        UI != UE; ++UI) {
4770     SDNode *User = *UI;
4771     if (User == N)
4772       continue;
4773     if (UI.getUse().getResNo() != N0.getResNo())
4774       continue;
4775     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4776     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4777       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4778       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4779         // Sign bits will be lost after a zext.
4780         return false;
4781       bool Add = false;
4782       for (unsigned i = 0; i != 2; ++i) {
4783         SDValue UseOp = User->getOperand(i);
4784         if (UseOp == N0)
4785           continue;
4786         if (!isa<ConstantSDNode>(UseOp))
4787           return false;
4788         Add = true;
4789       }
4790       if (Add)
4791         ExtendNodes.push_back(User);
4792       continue;
4793     }
4794     // If truncates aren't free and there are users we can't
4795     // extend, it isn't worthwhile.
4796     if (!isTruncFree)
4797       return false;
4798     // Remember if this value is live-out.
4799     if (User->getOpcode() == ISD::CopyToReg)
4800       HasCopyToRegUses = true;
4801   }
4802
4803   if (HasCopyToRegUses) {
4804     bool BothLiveOut = false;
4805     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4806          UI != UE; ++UI) {
4807       SDUse &Use = UI.getUse();
4808       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4809         BothLiveOut = true;
4810         break;
4811       }
4812     }
4813     if (BothLiveOut)
4814       // Both unextended and extended values are live out. There had better be
4815       // a good reason for the transformation.
4816       return ExtendNodes.size();
4817   }
4818   return true;
4819 }
4820
4821 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4822                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4823                                   ISD::NodeType ExtType) {
4824   // Extend SetCC uses if necessary.
4825   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4826     SDNode *SetCC = SetCCs[i];
4827     SmallVector<SDValue, 4> Ops;
4828
4829     for (unsigned j = 0; j != 2; ++j) {
4830       SDValue SOp = SetCC->getOperand(j);
4831       if (SOp == Trunc)
4832         Ops.push_back(ExtLoad);
4833       else
4834         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4835     }
4836
4837     Ops.push_back(SetCC->getOperand(2));
4838     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4839                                  &Ops[0], Ops.size()));
4840   }
4841 }
4842
4843 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4844   SDValue N0 = N->getOperand(0);
4845   EVT VT = N->getValueType(0);
4846
4847   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4848                                               LegalOperations))
4849     return SDValue(Res, 0);
4850
4851   // fold (sext (sext x)) -> (sext x)
4852   // fold (sext (aext x)) -> (sext x)
4853   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4854     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4855                        N0.getOperand(0));
4856
4857   if (N0.getOpcode() == ISD::TRUNCATE) {
4858     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4859     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4860     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4861     if (NarrowLoad.getNode()) {
4862       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4863       if (NarrowLoad.getNode() != N0.getNode()) {
4864         CombineTo(N0.getNode(), NarrowLoad);
4865         // CombineTo deleted the truncate, if needed, but not what's under it.
4866         AddToWorkList(oye);
4867       }
4868       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4869     }
4870
4871     // See if the value being truncated is already sign extended.  If so, just
4872     // eliminate the trunc/sext pair.
4873     SDValue Op = N0.getOperand(0);
4874     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4875     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4876     unsigned DestBits = VT.getScalarType().getSizeInBits();
4877     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4878
4879     if (OpBits == DestBits) {
4880       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4881       // bits, it is already ready.
4882       if (NumSignBits > DestBits-MidBits)
4883         return Op;
4884     } else if (OpBits < DestBits) {
4885       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4886       // bits, just sext from i32.
4887       if (NumSignBits > OpBits-MidBits)
4888         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4889     } else {
4890       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4891       // bits, just truncate to i32.
4892       if (NumSignBits > OpBits-MidBits)
4893         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4894     }
4895
4896     // fold (sext (truncate x)) -> (sextinreg x).
4897     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4898                                                  N0.getValueType())) {
4899       if (OpBits < DestBits)
4900         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4901       else if (OpBits > DestBits)
4902         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4903       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4904                          DAG.getValueType(N0.getValueType()));
4905     }
4906   }
4907
4908   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4909   // None of the supported targets knows how to perform load and sign extend
4910   // on vectors in one instruction.  We only perform this transformation on
4911   // scalars.
4912   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4913       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4914       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4915        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4916     bool DoXform = true;
4917     SmallVector<SDNode*, 4> SetCCs;
4918     if (!N0.hasOneUse())
4919       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4920     if (DoXform) {
4921       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4922       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4923                                        LN0->getChain(),
4924                                        LN0->getBasePtr(), N0.getValueType(),
4925                                        LN0->getMemOperand());
4926       CombineTo(N, ExtLoad);
4927       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4928                                   N0.getValueType(), ExtLoad);
4929       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4930       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4931                       ISD::SIGN_EXTEND);
4932       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4933     }
4934   }
4935
4936   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4937   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4938   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4939       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4940     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4941     EVT MemVT = LN0->getMemoryVT();
4942     if ((!LegalOperations && !LN0->isVolatile()) ||
4943         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4944       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4945                                        LN0->getChain(),
4946                                        LN0->getBasePtr(), MemVT,
4947                                        LN0->getMemOperand());
4948       CombineTo(N, ExtLoad);
4949       CombineTo(N0.getNode(),
4950                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4951                             N0.getValueType(), ExtLoad),
4952                 ExtLoad.getValue(1));
4953       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4954     }
4955   }
4956
4957   // fold (sext (and/or/xor (load x), cst)) ->
4958   //      (and/or/xor (sextload x), (sext cst))
4959   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4960        N0.getOpcode() == ISD::XOR) &&
4961       isa<LoadSDNode>(N0.getOperand(0)) &&
4962       N0.getOperand(1).getOpcode() == ISD::Constant &&
4963       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4964       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4965     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4966     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4967       bool DoXform = true;
4968       SmallVector<SDNode*, 4> SetCCs;
4969       if (!N0.hasOneUse())
4970         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4971                                           SetCCs, TLI);
4972       if (DoXform) {
4973         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4974                                          LN0->getChain(), LN0->getBasePtr(),
4975                                          LN0->getMemoryVT(),
4976                                          LN0->getMemOperand());
4977         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4978         Mask = Mask.sext(VT.getSizeInBits());
4979         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4980                                   ExtLoad, DAG.getConstant(Mask, VT));
4981         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4982                                     SDLoc(N0.getOperand(0)),
4983                                     N0.getOperand(0).getValueType(), ExtLoad);
4984         CombineTo(N, And);
4985         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4986         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4987                         ISD::SIGN_EXTEND);
4988         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4989       }
4990     }
4991   }
4992
4993   if (N0.getOpcode() == ISD::SETCC) {
4994     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4995     // Only do this before legalize for now.
4996     if (VT.isVector() && !LegalOperations &&
4997         TLI.getBooleanContents(true) ==
4998           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4999       EVT N0VT = N0.getOperand(0).getValueType();
5000       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5001       // of the same size as the compared operands. Only optimize sext(setcc())
5002       // if this is the case.
5003       EVT SVT = getSetCCResultType(N0VT);
5004
5005       // We know that the # elements of the results is the same as the
5006       // # elements of the compare (and the # elements of the compare result
5007       // for that matter).  Check to see that they are the same size.  If so,
5008       // we know that the element size of the sext'd result matches the
5009       // element size of the compare operands.
5010       if (VT.getSizeInBits() == SVT.getSizeInBits())
5011         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5012                              N0.getOperand(1),
5013                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5014
5015       // If the desired elements are smaller or larger than the source
5016       // elements we can use a matching integer vector type and then
5017       // truncate/sign extend
5018       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5019       if (SVT == MatchingVectorType) {
5020         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5021                                N0.getOperand(0), N0.getOperand(1),
5022                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5023         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5024       }
5025     }
5026
5027     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5028     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5029     SDValue NegOne =
5030       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5031     SDValue SCC =
5032       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5033                        NegOne, DAG.getConstant(0, VT),
5034                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5035     if (SCC.getNode()) return SCC;
5036
5037     if (!VT.isVector()) {
5038       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5039       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5040         SDLoc DL(N);
5041         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5042         SDValue SetCC = DAG.getSetCC(DL,
5043                                      SetCCVT,
5044                                      N0.getOperand(0), N0.getOperand(1), CC);
5045         EVT SelectVT = getSetCCResultType(VT);
5046         return DAG.getSelect(DL, VT,
5047                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5048                              NegOne, DAG.getConstant(0, VT));
5049
5050       }
5051     }
5052   }
5053
5054   // fold (sext x) -> (zext x) if the sign bit is known zero.
5055   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5056       DAG.SignBitIsZero(N0))
5057     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5058
5059   return SDValue();
5060 }
5061
5062 // isTruncateOf - If N is a truncate of some other value, return true, record
5063 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5064 // This function computes KnownZero to avoid a duplicated call to
5065 // ComputeMaskedBits in the caller.
5066 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5067                          APInt &KnownZero) {
5068   APInt KnownOne;
5069   if (N->getOpcode() == ISD::TRUNCATE) {
5070     Op = N->getOperand(0);
5071     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5072     return true;
5073   }
5074
5075   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5076       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5077     return false;
5078
5079   SDValue Op0 = N->getOperand(0);
5080   SDValue Op1 = N->getOperand(1);
5081   assert(Op0.getValueType() == Op1.getValueType());
5082
5083   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5084   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5085   if (COp0 && COp0->isNullValue())
5086     Op = Op1;
5087   else if (COp1 && COp1->isNullValue())
5088     Op = Op0;
5089   else
5090     return false;
5091
5092   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5093
5094   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5095     return false;
5096
5097   return true;
5098 }
5099
5100 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5101   SDValue N0 = N->getOperand(0);
5102   EVT VT = N->getValueType(0);
5103
5104   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5105                                               LegalOperations))
5106     return SDValue(Res, 0);
5107
5108   // fold (zext (zext x)) -> (zext x)
5109   // fold (zext (aext x)) -> (zext x)
5110   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5111     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5112                        N0.getOperand(0));
5113
5114   // fold (zext (truncate x)) -> (zext x) or
5115   //      (zext (truncate x)) -> (truncate x)
5116   // This is valid when the truncated bits of x are already zero.
5117   // FIXME: We should extend this to work for vectors too.
5118   SDValue Op;
5119   APInt KnownZero;
5120   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5121     APInt TruncatedBits =
5122       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5123       APInt(Op.getValueSizeInBits(), 0) :
5124       APInt::getBitsSet(Op.getValueSizeInBits(),
5125                         N0.getValueSizeInBits(),
5126                         std::min(Op.getValueSizeInBits(),
5127                                  VT.getSizeInBits()));
5128     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5129       if (VT.bitsGT(Op.getValueType()))
5130         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5131       if (VT.bitsLT(Op.getValueType()))
5132         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5133
5134       return Op;
5135     }
5136   }
5137
5138   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5139   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5140   if (N0.getOpcode() == ISD::TRUNCATE) {
5141     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5142     if (NarrowLoad.getNode()) {
5143       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5144       if (NarrowLoad.getNode() != N0.getNode()) {
5145         CombineTo(N0.getNode(), NarrowLoad);
5146         // CombineTo deleted the truncate, if needed, but not what's under it.
5147         AddToWorkList(oye);
5148       }
5149       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5150     }
5151   }
5152
5153   // fold (zext (truncate x)) -> (and x, mask)
5154   if (N0.getOpcode() == ISD::TRUNCATE &&
5155       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5156
5157     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5158     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5159     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5160     if (NarrowLoad.getNode()) {
5161       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5162       if (NarrowLoad.getNode() != N0.getNode()) {
5163         CombineTo(N0.getNode(), NarrowLoad);
5164         // CombineTo deleted the truncate, if needed, but not what's under it.
5165         AddToWorkList(oye);
5166       }
5167       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5168     }
5169
5170     SDValue Op = N0.getOperand(0);
5171     if (Op.getValueType().bitsLT(VT)) {
5172       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5173       AddToWorkList(Op.getNode());
5174     } else if (Op.getValueType().bitsGT(VT)) {
5175       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5176       AddToWorkList(Op.getNode());
5177     }
5178     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5179                                   N0.getValueType().getScalarType());
5180   }
5181
5182   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5183   // if either of the casts is not free.
5184   if (N0.getOpcode() == ISD::AND &&
5185       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5186       N0.getOperand(1).getOpcode() == ISD::Constant &&
5187       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5188                            N0.getValueType()) ||
5189        !TLI.isZExtFree(N0.getValueType(), VT))) {
5190     SDValue X = N0.getOperand(0).getOperand(0);
5191     if (X.getValueType().bitsLT(VT)) {
5192       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5193     } else if (X.getValueType().bitsGT(VT)) {
5194       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5195     }
5196     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5197     Mask = Mask.zext(VT.getSizeInBits());
5198     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5199                        X, DAG.getConstant(Mask, VT));
5200   }
5201
5202   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5203   // None of the supported targets knows how to perform load and vector_zext
5204   // on vectors in one instruction.  We only perform this transformation on
5205   // scalars.
5206   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5207       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5208       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5209        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5210     bool DoXform = true;
5211     SmallVector<SDNode*, 4> SetCCs;
5212     if (!N0.hasOneUse())
5213       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5214     if (DoXform) {
5215       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5216       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5217                                        LN0->getChain(),
5218                                        LN0->getBasePtr(), N0.getValueType(),
5219                                        LN0->getMemOperand());
5220       CombineTo(N, ExtLoad);
5221       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5222                                   N0.getValueType(), ExtLoad);
5223       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5224
5225       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5226                       ISD::ZERO_EXTEND);
5227       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5228     }
5229   }
5230
5231   // fold (zext (and/or/xor (load x), cst)) ->
5232   //      (and/or/xor (zextload x), (zext cst))
5233   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5234        N0.getOpcode() == ISD::XOR) &&
5235       isa<LoadSDNode>(N0.getOperand(0)) &&
5236       N0.getOperand(1).getOpcode() == ISD::Constant &&
5237       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5238       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5239     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5240     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5241       bool DoXform = true;
5242       SmallVector<SDNode*, 4> SetCCs;
5243       if (!N0.hasOneUse())
5244         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5245                                           SetCCs, TLI);
5246       if (DoXform) {
5247         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5248                                          LN0->getChain(), LN0->getBasePtr(),
5249                                          LN0->getMemoryVT(),
5250                                          LN0->getMemOperand());
5251         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5252         Mask = Mask.zext(VT.getSizeInBits());
5253         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5254                                   ExtLoad, DAG.getConstant(Mask, VT));
5255         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5256                                     SDLoc(N0.getOperand(0)),
5257                                     N0.getOperand(0).getValueType(), ExtLoad);
5258         CombineTo(N, And);
5259         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5260         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5261                         ISD::ZERO_EXTEND);
5262         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5263       }
5264     }
5265   }
5266
5267   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5268   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5269   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5270       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5271     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5272     EVT MemVT = LN0->getMemoryVT();
5273     if ((!LegalOperations && !LN0->isVolatile()) ||
5274         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5275       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5276                                        LN0->getChain(),
5277                                        LN0->getBasePtr(), MemVT,
5278                                        LN0->getMemOperand());
5279       CombineTo(N, ExtLoad);
5280       CombineTo(N0.getNode(),
5281                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5282                             ExtLoad),
5283                 ExtLoad.getValue(1));
5284       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5285     }
5286   }
5287
5288   if (N0.getOpcode() == ISD::SETCC) {
5289     if (!LegalOperations && VT.isVector() &&
5290         N0.getValueType().getVectorElementType() == MVT::i1) {
5291       EVT N0VT = N0.getOperand(0).getValueType();
5292       if (getSetCCResultType(N0VT) == N0.getValueType())
5293         return SDValue();
5294
5295       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5296       // Only do this before legalize for now.
5297       EVT EltVT = VT.getVectorElementType();
5298       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5299                                     DAG.getConstant(1, EltVT));
5300       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5301         // We know that the # elements of the results is the same as the
5302         // # elements of the compare (and the # elements of the compare result
5303         // for that matter).  Check to see that they are the same size.  If so,
5304         // we know that the element size of the sext'd result matches the
5305         // element size of the compare operands.
5306         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5307                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5308                                          N0.getOperand(1),
5309                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5310                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5311                                        &OneOps[0], OneOps.size()));
5312
5313       // If the desired elements are smaller or larger than the source
5314       // elements we can use a matching integer vector type and then
5315       // truncate/sign extend
5316       EVT MatchingElementType =
5317         EVT::getIntegerVT(*DAG.getContext(),
5318                           N0VT.getScalarType().getSizeInBits());
5319       EVT MatchingVectorType =
5320         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5321                          N0VT.getVectorNumElements());
5322       SDValue VsetCC =
5323         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5324                       N0.getOperand(1),
5325                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5326       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5327                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5328                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5329                                      &OneOps[0], OneOps.size()));
5330     }
5331
5332     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5333     SDValue SCC =
5334       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5335                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5336                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5337     if (SCC.getNode()) return SCC;
5338   }
5339
5340   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5341   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5342       isa<ConstantSDNode>(N0.getOperand(1)) &&
5343       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5344       N0.hasOneUse()) {
5345     SDValue ShAmt = N0.getOperand(1);
5346     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5347     if (N0.getOpcode() == ISD::SHL) {
5348       SDValue InnerZExt = N0.getOperand(0);
5349       // If the original shl may be shifting out bits, do not perform this
5350       // transformation.
5351       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5352         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5353       if (ShAmtVal > KnownZeroBits)
5354         return SDValue();
5355     }
5356
5357     SDLoc DL(N);
5358
5359     // Ensure that the shift amount is wide enough for the shifted value.
5360     if (VT.getSizeInBits() >= 256)
5361       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5362
5363     return DAG.getNode(N0.getOpcode(), DL, VT,
5364                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5365                        ShAmt);
5366   }
5367
5368   return SDValue();
5369 }
5370
5371 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5372   SDValue N0 = N->getOperand(0);
5373   EVT VT = N->getValueType(0);
5374
5375   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5376                                               LegalOperations))
5377     return SDValue(Res, 0);
5378
5379   // fold (aext (aext x)) -> (aext x)
5380   // fold (aext (zext x)) -> (zext x)
5381   // fold (aext (sext x)) -> (sext x)
5382   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5383       N0.getOpcode() == ISD::ZERO_EXTEND ||
5384       N0.getOpcode() == ISD::SIGN_EXTEND)
5385     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5386
5387   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5388   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5389   if (N0.getOpcode() == ISD::TRUNCATE) {
5390     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5391     if (NarrowLoad.getNode()) {
5392       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5393       if (NarrowLoad.getNode() != N0.getNode()) {
5394         CombineTo(N0.getNode(), NarrowLoad);
5395         // CombineTo deleted the truncate, if needed, but not what's under it.
5396         AddToWorkList(oye);
5397       }
5398       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5399     }
5400   }
5401
5402   // fold (aext (truncate x))
5403   if (N0.getOpcode() == ISD::TRUNCATE) {
5404     SDValue TruncOp = N0.getOperand(0);
5405     if (TruncOp.getValueType() == VT)
5406       return TruncOp; // x iff x size == zext size.
5407     if (TruncOp.getValueType().bitsGT(VT))
5408       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5409     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5410   }
5411
5412   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5413   // if the trunc is not free.
5414   if (N0.getOpcode() == ISD::AND &&
5415       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5416       N0.getOperand(1).getOpcode() == ISD::Constant &&
5417       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5418                           N0.getValueType())) {
5419     SDValue X = N0.getOperand(0).getOperand(0);
5420     if (X.getValueType().bitsLT(VT)) {
5421       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5422     } else if (X.getValueType().bitsGT(VT)) {
5423       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5424     }
5425     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5426     Mask = Mask.zext(VT.getSizeInBits());
5427     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5428                        X, DAG.getConstant(Mask, VT));
5429   }
5430
5431   // fold (aext (load x)) -> (aext (truncate (extload x)))
5432   // None of the supported targets knows how to perform load and any_ext
5433   // on vectors in one instruction.  We only perform this transformation on
5434   // scalars.
5435   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5436       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5437       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5438        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5439     bool DoXform = true;
5440     SmallVector<SDNode*, 4> SetCCs;
5441     if (!N0.hasOneUse())
5442       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5443     if (DoXform) {
5444       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5445       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5446                                        LN0->getChain(),
5447                                        LN0->getBasePtr(), N0.getValueType(),
5448                                        LN0->getMemOperand());
5449       CombineTo(N, ExtLoad);
5450       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5451                                   N0.getValueType(), ExtLoad);
5452       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5453       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5454                       ISD::ANY_EXTEND);
5455       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5456     }
5457   }
5458
5459   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5460   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5461   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5462   if (N0.getOpcode() == ISD::LOAD &&
5463       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5464       N0.hasOneUse()) {
5465     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5466     ISD::LoadExtType ExtType = LN0->getExtensionType();
5467     EVT MemVT = LN0->getMemoryVT();
5468     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5469       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5470                                        VT, LN0->getChain(), LN0->getBasePtr(),
5471                                        MemVT, LN0->getMemOperand());
5472       CombineTo(N, ExtLoad);
5473       CombineTo(N0.getNode(),
5474                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5475                             N0.getValueType(), ExtLoad),
5476                 ExtLoad.getValue(1));
5477       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5478     }
5479   }
5480
5481   if (N0.getOpcode() == ISD::SETCC) {
5482     // For vectors:
5483     // aext(setcc) -> vsetcc
5484     // aext(setcc) -> truncate(vsetcc)
5485     // aext(setcc) -> aext(vsetcc)
5486     // Only do this before legalize for now.
5487     if (VT.isVector() && !LegalOperations) {
5488       EVT N0VT = N0.getOperand(0).getValueType();
5489         // We know that the # elements of the results is the same as the
5490         // # elements of the compare (and the # elements of the compare result
5491         // for that matter).  Check to see that they are the same size.  If so,
5492         // we know that the element size of the sext'd result matches the
5493         // element size of the compare operands.
5494       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5495         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5496                              N0.getOperand(1),
5497                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5498       // If the desired elements are smaller or larger than the source
5499       // elements we can use a matching integer vector type and then
5500       // truncate/any extend
5501       else {
5502         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5503         SDValue VsetCC =
5504           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5505                         N0.getOperand(1),
5506                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5507         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5508       }
5509     }
5510
5511     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5512     SDValue SCC =
5513       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5514                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5515                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5516     if (SCC.getNode())
5517       return SCC;
5518   }
5519
5520   return SDValue();
5521 }
5522
5523 /// GetDemandedBits - See if the specified operand can be simplified with the
5524 /// knowledge that only the bits specified by Mask are used.  If so, return the
5525 /// simpler operand, otherwise return a null SDValue.
5526 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5527   switch (V.getOpcode()) {
5528   default: break;
5529   case ISD::Constant: {
5530     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5531     assert(CV && "Const value should be ConstSDNode.");
5532     const APInt &CVal = CV->getAPIntValue();
5533     APInt NewVal = CVal & Mask;
5534     if (NewVal != CVal)
5535       return DAG.getConstant(NewVal, V.getValueType());
5536     break;
5537   }
5538   case ISD::OR:
5539   case ISD::XOR:
5540     // If the LHS or RHS don't contribute bits to the or, drop them.
5541     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5542       return V.getOperand(1);
5543     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5544       return V.getOperand(0);
5545     break;
5546   case ISD::SRL:
5547     // Only look at single-use SRLs.
5548     if (!V.getNode()->hasOneUse())
5549       break;
5550     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5551       // See if we can recursively simplify the LHS.
5552       unsigned Amt = RHSC->getZExtValue();
5553
5554       // Watch out for shift count overflow though.
5555       if (Amt >= Mask.getBitWidth()) break;
5556       APInt NewMask = Mask << Amt;
5557       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5558       if (SimplifyLHS.getNode())
5559         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5560                            SimplifyLHS, V.getOperand(1));
5561     }
5562   }
5563   return SDValue();
5564 }
5565
5566 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5567 /// bits and then truncated to a narrower type and where N is a multiple
5568 /// of number of bits of the narrower type, transform it to a narrower load
5569 /// from address + N / num of bits of new type. If the result is to be
5570 /// extended, also fold the extension to form a extending load.
5571 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5572   unsigned Opc = N->getOpcode();
5573
5574   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5575   SDValue N0 = N->getOperand(0);
5576   EVT VT = N->getValueType(0);
5577   EVT ExtVT = VT;
5578
5579   // This transformation isn't valid for vector loads.
5580   if (VT.isVector())
5581     return SDValue();
5582
5583   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5584   // extended to VT.
5585   if (Opc == ISD::SIGN_EXTEND_INREG) {
5586     ExtType = ISD::SEXTLOAD;
5587     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5588   } else if (Opc == ISD::SRL) {
5589     // Another special-case: SRL is basically zero-extending a narrower value.
5590     ExtType = ISD::ZEXTLOAD;
5591     N0 = SDValue(N, 0);
5592     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5593     if (!N01) return SDValue();
5594     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5595                               VT.getSizeInBits() - N01->getZExtValue());
5596   }
5597   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5598     return SDValue();
5599
5600   unsigned EVTBits = ExtVT.getSizeInBits();
5601
5602   // Do not generate loads of non-round integer types since these can
5603   // be expensive (and would be wrong if the type is not byte sized).
5604   if (!ExtVT.isRound())
5605     return SDValue();
5606
5607   unsigned ShAmt = 0;
5608   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5609     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5610       ShAmt = N01->getZExtValue();
5611       // Is the shift amount a multiple of size of VT?
5612       if ((ShAmt & (EVTBits-1)) == 0) {
5613         N0 = N0.getOperand(0);
5614         // Is the load width a multiple of size of VT?
5615         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5616           return SDValue();
5617       }
5618
5619       // At this point, we must have a load or else we can't do the transform.
5620       if (!isa<LoadSDNode>(N0)) return SDValue();
5621
5622       // Because a SRL must be assumed to *need* to zero-extend the high bits
5623       // (as opposed to anyext the high bits), we can't combine the zextload
5624       // lowering of SRL and an sextload.
5625       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5626         return SDValue();
5627
5628       // If the shift amount is larger than the input type then we're not
5629       // accessing any of the loaded bytes.  If the load was a zextload/extload
5630       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5631       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5632         return SDValue();
5633     }
5634   }
5635
5636   // If the load is shifted left (and the result isn't shifted back right),
5637   // we can fold the truncate through the shift.
5638   unsigned ShLeftAmt = 0;
5639   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5640       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5641     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5642       ShLeftAmt = N01->getZExtValue();
5643       N0 = N0.getOperand(0);
5644     }
5645   }
5646
5647   // If we haven't found a load, we can't narrow it.  Don't transform one with
5648   // multiple uses, this would require adding a new load.
5649   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5650     return SDValue();
5651
5652   // Don't change the width of a volatile load.
5653   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5654   if (LN0->isVolatile())
5655     return SDValue();
5656
5657   // Verify that we are actually reducing a load width here.
5658   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5659     return SDValue();
5660
5661   // For the transform to be legal, the load must produce only two values
5662   // (the value loaded and the chain).  Don't transform a pre-increment
5663   // load, for example, which produces an extra value.  Otherwise the
5664   // transformation is not equivalent, and the downstream logic to replace
5665   // uses gets things wrong.
5666   if (LN0->getNumValues() > 2)
5667     return SDValue();
5668
5669   // If the load that we're shrinking is an extload and we're not just
5670   // discarding the extension we can't simply shrink the load. Bail.
5671   // TODO: It would be possible to merge the extensions in some cases.
5672   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5673       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5674     return SDValue();
5675
5676   EVT PtrType = N0.getOperand(1).getValueType();
5677
5678   if (PtrType == MVT::Untyped || PtrType.isExtended())
5679     // It's not possible to generate a constant of extended or untyped type.
5680     return SDValue();
5681
5682   // For big endian targets, we need to adjust the offset to the pointer to
5683   // load the correct bytes.
5684   if (TLI.isBigEndian()) {
5685     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5686     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5687     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5688   }
5689
5690   uint64_t PtrOff = ShAmt / 8;
5691   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5692   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5693                                PtrType, LN0->getBasePtr(),
5694                                DAG.getConstant(PtrOff, PtrType));
5695   AddToWorkList(NewPtr.getNode());
5696
5697   SDValue Load;
5698   if (ExtType == ISD::NON_EXTLOAD)
5699     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5700                         LN0->getPointerInfo().getWithOffset(PtrOff),
5701                         LN0->isVolatile(), LN0->isNonTemporal(),
5702                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5703   else
5704     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5705                           LN0->getPointerInfo().getWithOffset(PtrOff),
5706                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5707                           NewAlign, LN0->getTBAAInfo());
5708
5709   // Replace the old load's chain with the new load's chain.
5710   WorkListRemover DeadNodes(*this);
5711   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5712
5713   // Shift the result left, if we've swallowed a left shift.
5714   SDValue Result = Load;
5715   if (ShLeftAmt != 0) {
5716     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5717     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5718       ShImmTy = VT;
5719     // If the shift amount is as large as the result size (but, presumably,
5720     // no larger than the source) then the useful bits of the result are
5721     // zero; we can't simply return the shortened shift, because the result
5722     // of that operation is undefined.
5723     if (ShLeftAmt >= VT.getSizeInBits())
5724       Result = DAG.getConstant(0, VT);
5725     else
5726       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5727                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5728   }
5729
5730   // Return the new loaded value.
5731   return Result;
5732 }
5733
5734 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5735   SDValue N0 = N->getOperand(0);
5736   SDValue N1 = N->getOperand(1);
5737   EVT VT = N->getValueType(0);
5738   EVT EVT = cast<VTSDNode>(N1)->getVT();
5739   unsigned VTBits = VT.getScalarType().getSizeInBits();
5740   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5741
5742   // fold (sext_in_reg c1) -> c1
5743   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5744     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5745
5746   // If the input is already sign extended, just drop the extension.
5747   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5748     return N0;
5749
5750   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5751   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5752       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5753     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5754                        N0.getOperand(0), N1);
5755
5756   // fold (sext_in_reg (sext x)) -> (sext x)
5757   // fold (sext_in_reg (aext x)) -> (sext x)
5758   // if x is small enough.
5759   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5760     SDValue N00 = N0.getOperand(0);
5761     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5762         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5763       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5764   }
5765
5766   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5767   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5768     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5769
5770   // fold operands of sext_in_reg based on knowledge that the top bits are not
5771   // demanded.
5772   if (SimplifyDemandedBits(SDValue(N, 0)))
5773     return SDValue(N, 0);
5774
5775   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5776   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5777   SDValue NarrowLoad = ReduceLoadWidth(N);
5778   if (NarrowLoad.getNode())
5779     return NarrowLoad;
5780
5781   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5782   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5783   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5784   if (N0.getOpcode() == ISD::SRL) {
5785     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5786       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5787         // We can turn this into an SRA iff the input to the SRL is already sign
5788         // extended enough.
5789         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5790         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5791           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5792                              N0.getOperand(0), N0.getOperand(1));
5793       }
5794   }
5795
5796   // fold (sext_inreg (extload x)) -> (sextload x)
5797   if (ISD::isEXTLoad(N0.getNode()) &&
5798       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5799       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5800       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5801        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5802     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5803     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5804                                      LN0->getChain(),
5805                                      LN0->getBasePtr(), EVT,
5806                                      LN0->getMemOperand());
5807     CombineTo(N, ExtLoad);
5808     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5809     AddToWorkList(ExtLoad.getNode());
5810     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5811   }
5812   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5813   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5814       N0.hasOneUse() &&
5815       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5816       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5817        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5818     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5819     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5820                                      LN0->getChain(),
5821                                      LN0->getBasePtr(), EVT,
5822                                      LN0->getMemOperand());
5823     CombineTo(N, ExtLoad);
5824     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5825     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5826   }
5827
5828   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5829   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5830     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5831                                        N0.getOperand(1), false);
5832     if (BSwap.getNode())
5833       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5834                          BSwap, N1);
5835   }
5836
5837   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5838   // into a build_vector.
5839   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5840     SmallVector<SDValue, 8> Elts;
5841     unsigned NumElts = N0->getNumOperands();
5842     unsigned ShAmt = VTBits - EVTBits;
5843
5844     for (unsigned i = 0; i != NumElts; ++i) {
5845       SDValue Op = N0->getOperand(i);
5846       if (Op->getOpcode() == ISD::UNDEF) {
5847         Elts.push_back(Op);
5848         continue;
5849       }
5850
5851       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5852       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5853       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5854                                      Op.getValueType()));
5855     }
5856
5857     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5858   }
5859
5860   return SDValue();
5861 }
5862
5863 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5864   SDValue N0 = N->getOperand(0);
5865   EVT VT = N->getValueType(0);
5866   bool isLE = TLI.isLittleEndian();
5867
5868   // noop truncate
5869   if (N0.getValueType() == N->getValueType(0))
5870     return N0;
5871   // fold (truncate c1) -> c1
5872   if (isa<ConstantSDNode>(N0))
5873     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5874   // fold (truncate (truncate x)) -> (truncate x)
5875   if (N0.getOpcode() == ISD::TRUNCATE)
5876     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5877   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5878   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5879       N0.getOpcode() == ISD::SIGN_EXTEND ||
5880       N0.getOpcode() == ISD::ANY_EXTEND) {
5881     if (N0.getOperand(0).getValueType().bitsLT(VT))
5882       // if the source is smaller than the dest, we still need an extend
5883       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5884                          N0.getOperand(0));
5885     if (N0.getOperand(0).getValueType().bitsGT(VT))
5886       // if the source is larger than the dest, than we just need the truncate
5887       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5888     // if the source and dest are the same type, we can drop both the extend
5889     // and the truncate.
5890     return N0.getOperand(0);
5891   }
5892
5893   // Fold extract-and-trunc into a narrow extract. For example:
5894   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5895   //   i32 y = TRUNCATE(i64 x)
5896   //        -- becomes --
5897   //   v16i8 b = BITCAST (v2i64 val)
5898   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5899   //
5900   // Note: We only run this optimization after type legalization (which often
5901   // creates this pattern) and before operation legalization after which
5902   // we need to be more careful about the vector instructions that we generate.
5903   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5904       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5905
5906     EVT VecTy = N0.getOperand(0).getValueType();
5907     EVT ExTy = N0.getValueType();
5908     EVT TrTy = N->getValueType(0);
5909
5910     unsigned NumElem = VecTy.getVectorNumElements();
5911     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5912
5913     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5914     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5915
5916     SDValue EltNo = N0->getOperand(1);
5917     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5918       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5919       EVT IndexTy = TLI.getVectorIdxTy();
5920       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5921
5922       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5923                               NVT, N0.getOperand(0));
5924
5925       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5926                          SDLoc(N), TrTy, V,
5927                          DAG.getConstant(Index, IndexTy));
5928     }
5929   }
5930
5931   // Fold a series of buildvector, bitcast, and truncate if possible.
5932   // For example fold
5933   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5934   //   (2xi32 (buildvector x, y)).
5935   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5936       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5937       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5938       N0.getOperand(0).hasOneUse()) {
5939
5940     SDValue BuildVect = N0.getOperand(0);
5941     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5942     EVT TruncVecEltTy = VT.getVectorElementType();
5943
5944     // Check that the element types match.
5945     if (BuildVectEltTy == TruncVecEltTy) {
5946       // Now we only need to compute the offset of the truncated elements.
5947       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5948       unsigned TruncVecNumElts = VT.getVectorNumElements();
5949       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5950
5951       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5952              "Invalid number of elements");
5953
5954       SmallVector<SDValue, 8> Opnds;
5955       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5956         Opnds.push_back(BuildVect.getOperand(i));
5957
5958       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5959                          Opnds.size());
5960     }
5961   }
5962
5963   // See if we can simplify the input to this truncate through knowledge that
5964   // only the low bits are being used.
5965   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5966   // Currently we only perform this optimization on scalars because vectors
5967   // may have different active low bits.
5968   if (!VT.isVector()) {
5969     SDValue Shorter =
5970       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5971                                                VT.getSizeInBits()));
5972     if (Shorter.getNode())
5973       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5974   }
5975   // fold (truncate (load x)) -> (smaller load x)
5976   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5977   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5978     SDValue Reduced = ReduceLoadWidth(N);
5979     if (Reduced.getNode())
5980       return Reduced;
5981     // Handle the case where the load remains an extending load even
5982     // after truncation.
5983     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5984       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5985       if (!LN0->isVolatile() &&
5986           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5987         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5988                                          VT, LN0->getChain(), LN0->getBasePtr(),
5989                                          LN0->getMemoryVT(),
5990                                          LN0->getMemOperand());
5991         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5992         return NewLoad;
5993       }
5994     }
5995   }
5996   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5997   // where ... are all 'undef'.
5998   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5999     SmallVector<EVT, 8> VTs;
6000     SDValue V;
6001     unsigned Idx = 0;
6002     unsigned NumDefs = 0;
6003
6004     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6005       SDValue X = N0.getOperand(i);
6006       if (X.getOpcode() != ISD::UNDEF) {
6007         V = X;
6008         Idx = i;
6009         NumDefs++;
6010       }
6011       // Stop if more than one members are non-undef.
6012       if (NumDefs > 1)
6013         break;
6014       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6015                                      VT.getVectorElementType(),
6016                                      X.getValueType().getVectorNumElements()));
6017     }
6018
6019     if (NumDefs == 0)
6020       return DAG.getUNDEF(VT);
6021
6022     if (NumDefs == 1) {
6023       assert(V.getNode() && "The single defined operand is empty!");
6024       SmallVector<SDValue, 8> Opnds;
6025       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6026         if (i != Idx) {
6027           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6028           continue;
6029         }
6030         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6031         AddToWorkList(NV.getNode());
6032         Opnds.push_back(NV);
6033       }
6034       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6035                          &Opnds[0], Opnds.size());
6036     }
6037   }
6038
6039   // Simplify the operands using demanded-bits information.
6040   if (!VT.isVector() &&
6041       SimplifyDemandedBits(SDValue(N, 0)))
6042     return SDValue(N, 0);
6043
6044   return SDValue();
6045 }
6046
6047 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6048   SDValue Elt = N->getOperand(i);
6049   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6050     return Elt.getNode();
6051   return Elt.getOperand(Elt.getResNo()).getNode();
6052 }
6053
6054 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6055 /// if load locations are consecutive.
6056 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6057   assert(N->getOpcode() == ISD::BUILD_PAIR);
6058
6059   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6060   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6061   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6062       LD1->getAddressSpace() != LD2->getAddressSpace())
6063     return SDValue();
6064   EVT LD1VT = LD1->getValueType(0);
6065
6066   if (ISD::isNON_EXTLoad(LD2) &&
6067       LD2->hasOneUse() &&
6068       // If both are volatile this would reduce the number of volatile loads.
6069       // If one is volatile it might be ok, but play conservative and bail out.
6070       !LD1->isVolatile() &&
6071       !LD2->isVolatile() &&
6072       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6073     unsigned Align = LD1->getAlignment();
6074     unsigned NewAlign = TLI.getDataLayout()->
6075       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6076
6077     if (NewAlign <= Align &&
6078         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6079       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6080                          LD1->getBasePtr(), LD1->getPointerInfo(),
6081                          false, false, false, Align);
6082   }
6083
6084   return SDValue();
6085 }
6086
6087 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6088   SDValue N0 = N->getOperand(0);
6089   EVT VT = N->getValueType(0);
6090
6091   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6092   // Only do this before legalize, since afterward the target may be depending
6093   // on the bitconvert.
6094   // First check to see if this is all constant.
6095   if (!LegalTypes &&
6096       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6097       VT.isVector()) {
6098     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6099
6100     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6101     assert(!DestEltVT.isVector() &&
6102            "Element type of vector ValueType must not be vector!");
6103     if (isSimple)
6104       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6105   }
6106
6107   // If the input is a constant, let getNode fold it.
6108   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6109     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6110     if (Res.getNode() != N) {
6111       if (!LegalOperations ||
6112           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6113         return Res;
6114
6115       // Folding it resulted in an illegal node, and it's too late to
6116       // do that. Clean up the old node and forego the transformation.
6117       // Ideally this won't happen very often, because instcombine
6118       // and the earlier dagcombine runs (where illegal nodes are
6119       // permitted) should have folded most of them already.
6120       DAG.DeleteNode(Res.getNode());
6121     }
6122   }
6123
6124   // (conv (conv x, t1), t2) -> (conv x, t2)
6125   if (N0.getOpcode() == ISD::BITCAST)
6126     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6127                        N0.getOperand(0));
6128
6129   // fold (conv (load x)) -> (load (conv*)x)
6130   // If the resultant load doesn't need a higher alignment than the original!
6131   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6132       // Do not change the width of a volatile load.
6133       !cast<LoadSDNode>(N0)->isVolatile() &&
6134       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6135       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6136     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6137     unsigned Align = TLI.getDataLayout()->
6138       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6139     unsigned OrigAlign = LN0->getAlignment();
6140
6141     if (Align <= OrigAlign) {
6142       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6143                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6144                                  LN0->isVolatile(), LN0->isNonTemporal(),
6145                                  LN0->isInvariant(), OrigAlign,
6146                                  LN0->getTBAAInfo());
6147       AddToWorkList(N);
6148       CombineTo(N0.getNode(),
6149                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6150                             N0.getValueType(), Load),
6151                 Load.getValue(1));
6152       return Load;
6153     }
6154   }
6155
6156   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6157   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6158   // This often reduces constant pool loads.
6159   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6160        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6161       N0.getNode()->hasOneUse() && VT.isInteger() &&
6162       !VT.isVector() && !N0.getValueType().isVector()) {
6163     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6164                                   N0.getOperand(0));
6165     AddToWorkList(NewConv.getNode());
6166
6167     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6168     if (N0.getOpcode() == ISD::FNEG)
6169       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6170                          NewConv, DAG.getConstant(SignBit, VT));
6171     assert(N0.getOpcode() == ISD::FABS);
6172     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6173                        NewConv, DAG.getConstant(~SignBit, VT));
6174   }
6175
6176   // fold (bitconvert (fcopysign cst, x)) ->
6177   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6178   // Note that we don't handle (copysign x, cst) because this can always be
6179   // folded to an fneg or fabs.
6180   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6181       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6182       VT.isInteger() && !VT.isVector()) {
6183     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6184     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6185     if (isTypeLegal(IntXVT)) {
6186       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6187                               IntXVT, N0.getOperand(1));
6188       AddToWorkList(X.getNode());
6189
6190       // If X has a different width than the result/lhs, sext it or truncate it.
6191       unsigned VTWidth = VT.getSizeInBits();
6192       if (OrigXWidth < VTWidth) {
6193         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6194         AddToWorkList(X.getNode());
6195       } else if (OrigXWidth > VTWidth) {
6196         // To get the sign bit in the right place, we have to shift it right
6197         // before truncating.
6198         X = DAG.getNode(ISD::SRL, SDLoc(X),
6199                         X.getValueType(), X,
6200                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6201         AddToWorkList(X.getNode());
6202         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6203         AddToWorkList(X.getNode());
6204       }
6205
6206       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6207       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6208                       X, DAG.getConstant(SignBit, VT));
6209       AddToWorkList(X.getNode());
6210
6211       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6212                                 VT, N0.getOperand(0));
6213       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6214                         Cst, DAG.getConstant(~SignBit, VT));
6215       AddToWorkList(Cst.getNode());
6216
6217       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6218     }
6219   }
6220
6221   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6222   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6223     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6224     if (CombineLD.getNode())
6225       return CombineLD;
6226   }
6227
6228   return SDValue();
6229 }
6230
6231 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6232   EVT VT = N->getValueType(0);
6233   return CombineConsecutiveLoads(N, VT);
6234 }
6235
6236 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6237 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6238 /// destination element value type.
6239 SDValue DAGCombiner::
6240 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6241   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6242
6243   // If this is already the right type, we're done.
6244   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6245
6246   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6247   unsigned DstBitSize = DstEltVT.getSizeInBits();
6248
6249   // If this is a conversion of N elements of one type to N elements of another
6250   // type, convert each element.  This handles FP<->INT cases.
6251   if (SrcBitSize == DstBitSize) {
6252     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6253                               BV->getValueType(0).getVectorNumElements());
6254
6255     // Due to the FP element handling below calling this routine recursively,
6256     // we can end up with a scalar-to-vector node here.
6257     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6258       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6259                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6260                                      DstEltVT, BV->getOperand(0)));
6261
6262     SmallVector<SDValue, 8> Ops;
6263     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6264       SDValue Op = BV->getOperand(i);
6265       // If the vector element type is not legal, the BUILD_VECTOR operands
6266       // are promoted and implicitly truncated.  Make that explicit here.
6267       if (Op.getValueType() != SrcEltVT)
6268         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6269       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6270                                 DstEltVT, Op));
6271       AddToWorkList(Ops.back().getNode());
6272     }
6273     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6274                        &Ops[0], Ops.size());
6275   }
6276
6277   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6278   // handle annoying details of growing/shrinking FP values, we convert them to
6279   // int first.
6280   if (SrcEltVT.isFloatingPoint()) {
6281     // Convert the input float vector to a int vector where the elements are the
6282     // same sizes.
6283     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6284     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6285     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6286     SrcEltVT = IntVT;
6287   }
6288
6289   // Now we know the input is an integer vector.  If the output is a FP type,
6290   // convert to integer first, then to FP of the right size.
6291   if (DstEltVT.isFloatingPoint()) {
6292     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6293     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6294     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6295
6296     // Next, convert to FP elements of the same size.
6297     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6298   }
6299
6300   // Okay, we know the src/dst types are both integers of differing types.
6301   // Handling growing first.
6302   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6303   if (SrcBitSize < DstBitSize) {
6304     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6305
6306     SmallVector<SDValue, 8> Ops;
6307     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6308          i += NumInputsPerOutput) {
6309       bool isLE = TLI.isLittleEndian();
6310       APInt NewBits = APInt(DstBitSize, 0);
6311       bool EltIsUndef = true;
6312       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6313         // Shift the previously computed bits over.
6314         NewBits <<= SrcBitSize;
6315         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6316         if (Op.getOpcode() == ISD::UNDEF) continue;
6317         EltIsUndef = false;
6318
6319         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6320                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6321       }
6322
6323       if (EltIsUndef)
6324         Ops.push_back(DAG.getUNDEF(DstEltVT));
6325       else
6326         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6327     }
6328
6329     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6330     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6331                        &Ops[0], Ops.size());
6332   }
6333
6334   // Finally, this must be the case where we are shrinking elements: each input
6335   // turns into multiple outputs.
6336   bool isS2V = ISD::isScalarToVector(BV);
6337   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6338   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6339                             NumOutputsPerInput*BV->getNumOperands());
6340   SmallVector<SDValue, 8> Ops;
6341
6342   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6343     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6344       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6345         Ops.push_back(DAG.getUNDEF(DstEltVT));
6346       continue;
6347     }
6348
6349     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6350                   getAPIntValue().zextOrTrunc(SrcBitSize);
6351
6352     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6353       APInt ThisVal = OpVal.trunc(DstBitSize);
6354       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6355       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6356         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6357         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6358                            Ops[0]);
6359       OpVal = OpVal.lshr(DstBitSize);
6360     }
6361
6362     // For big endian targets, swap the order of the pieces of each element.
6363     if (TLI.isBigEndian())
6364       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6365   }
6366
6367   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6368                      &Ops[0], Ops.size());
6369 }
6370
6371 SDValue DAGCombiner::visitFADD(SDNode *N) {
6372   SDValue N0 = N->getOperand(0);
6373   SDValue N1 = N->getOperand(1);
6374   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6375   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6376   EVT VT = N->getValueType(0);
6377
6378   // fold vector ops
6379   if (VT.isVector()) {
6380     SDValue FoldedVOp = SimplifyVBinOp(N);
6381     if (FoldedVOp.getNode()) return FoldedVOp;
6382   }
6383
6384   // fold (fadd c1, c2) -> c1 + c2
6385   if (N0CFP && N1CFP)
6386     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6387   // canonicalize constant to RHS
6388   if (N0CFP && !N1CFP)
6389     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6390   // fold (fadd A, 0) -> A
6391   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6392       N1CFP->getValueAPF().isZero())
6393     return N0;
6394   // fold (fadd A, (fneg B)) -> (fsub A, B)
6395   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6396     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6397     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6398                        GetNegatedExpression(N1, DAG, LegalOperations));
6399   // fold (fadd (fneg A), B) -> (fsub B, A)
6400   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6401     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6402     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6403                        GetNegatedExpression(N0, DAG, LegalOperations));
6404
6405   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6406   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6407       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6408       isa<ConstantFPSDNode>(N0.getOperand(1)))
6409     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6410                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6411                                    N0.getOperand(1), N1));
6412
6413   // No FP constant should be created after legalization as Instruction
6414   // Selection pass has hard time in dealing with FP constant.
6415   //
6416   // We don't need test this condition for transformation like following, as
6417   // the DAG being transformed implies it is legal to take FP constant as
6418   // operand.
6419   //
6420   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6421   //
6422   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6423
6424   // If allow, fold (fadd (fneg x), x) -> 0.0
6425   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6426       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6427     return DAG.getConstantFP(0.0, VT);
6428
6429     // If allow, fold (fadd x, (fneg x)) -> 0.0
6430   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6431       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6432     return DAG.getConstantFP(0.0, VT);
6433
6434   // In unsafe math mode, we can fold chains of FADD's of the same value
6435   // into multiplications.  This transform is not safe in general because
6436   // we are reducing the number of rounding steps.
6437   if (DAG.getTarget().Options.UnsafeFPMath &&
6438       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6439       !N0CFP && !N1CFP) {
6440     if (N0.getOpcode() == ISD::FMUL) {
6441       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6442       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6443
6444       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6445       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6446         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6447                                      SDValue(CFP00, 0),
6448                                      DAG.getConstantFP(1.0, VT));
6449         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6450                            N1, NewCFP);
6451       }
6452
6453       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6454       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6455         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6456                                      SDValue(CFP01, 0),
6457                                      DAG.getConstantFP(1.0, VT));
6458         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6459                            N1, NewCFP);
6460       }
6461
6462       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6463       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6464           N1.getOperand(0) == N1.getOperand(1) &&
6465           N0.getOperand(1) == N1.getOperand(0)) {
6466         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6467                                      SDValue(CFP00, 0),
6468                                      DAG.getConstantFP(2.0, VT));
6469         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6470                            N0.getOperand(1), NewCFP);
6471       }
6472
6473       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6474       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6475           N1.getOperand(0) == N1.getOperand(1) &&
6476           N0.getOperand(0) == N1.getOperand(0)) {
6477         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6478                                      SDValue(CFP01, 0),
6479                                      DAG.getConstantFP(2.0, VT));
6480         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6481                            N0.getOperand(0), NewCFP);
6482       }
6483     }
6484
6485     if (N1.getOpcode() == ISD::FMUL) {
6486       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6487       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6488
6489       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6490       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6491         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6492                                      SDValue(CFP10, 0),
6493                                      DAG.getConstantFP(1.0, VT));
6494         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6495                            N0, NewCFP);
6496       }
6497
6498       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6499       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6500         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6501                                      SDValue(CFP11, 0),
6502                                      DAG.getConstantFP(1.0, VT));
6503         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6504                            N0, NewCFP);
6505       }
6506
6507
6508       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6509       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6510           N0.getOperand(0) == N0.getOperand(1) &&
6511           N1.getOperand(1) == N0.getOperand(0)) {
6512         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6513                                      SDValue(CFP10, 0),
6514                                      DAG.getConstantFP(2.0, VT));
6515         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6516                            N1.getOperand(1), NewCFP);
6517       }
6518
6519       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6520       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6521           N0.getOperand(0) == N0.getOperand(1) &&
6522           N1.getOperand(0) == N0.getOperand(0)) {
6523         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6524                                      SDValue(CFP11, 0),
6525                                      DAG.getConstantFP(2.0, VT));
6526         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6527                            N1.getOperand(0), NewCFP);
6528       }
6529     }
6530
6531     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6532       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6533       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6534       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6535           (N0.getOperand(0) == N1))
6536         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6537                            N1, DAG.getConstantFP(3.0, VT));
6538     }
6539
6540     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6541       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6542       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6543       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6544           N1.getOperand(0) == N0)
6545         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6546                            N0, DAG.getConstantFP(3.0, VT));
6547     }
6548
6549     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6550     if (AllowNewFpConst &&
6551         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6552         N0.getOperand(0) == N0.getOperand(1) &&
6553         N1.getOperand(0) == N1.getOperand(1) &&
6554         N0.getOperand(0) == N1.getOperand(0))
6555       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6556                          N0.getOperand(0),
6557                          DAG.getConstantFP(4.0, VT));
6558   }
6559
6560   // FADD -> FMA combines:
6561   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6562        DAG.getTarget().Options.UnsafeFPMath) &&
6563       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6564       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6565
6566     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6567     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6568       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6569                          N0.getOperand(0), N0.getOperand(1), N1);
6570
6571     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6572     // Note: Commutes FADD operands.
6573     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6574       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6575                          N1.getOperand(0), N1.getOperand(1), N0);
6576   }
6577
6578   return SDValue();
6579 }
6580
6581 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6582   SDValue N0 = N->getOperand(0);
6583   SDValue N1 = N->getOperand(1);
6584   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6585   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6586   EVT VT = N->getValueType(0);
6587   SDLoc dl(N);
6588
6589   // fold vector ops
6590   if (VT.isVector()) {
6591     SDValue FoldedVOp = SimplifyVBinOp(N);
6592     if (FoldedVOp.getNode()) return FoldedVOp;
6593   }
6594
6595   // fold (fsub c1, c2) -> c1-c2
6596   if (N0CFP && N1CFP)
6597     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6598   // fold (fsub A, 0) -> A
6599   if (DAG.getTarget().Options.UnsafeFPMath &&
6600       N1CFP && N1CFP->getValueAPF().isZero())
6601     return N0;
6602   // fold (fsub 0, B) -> -B
6603   if (DAG.getTarget().Options.UnsafeFPMath &&
6604       N0CFP && N0CFP->getValueAPF().isZero()) {
6605     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6606       return GetNegatedExpression(N1, DAG, LegalOperations);
6607     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6608       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6609   }
6610   // fold (fsub A, (fneg B)) -> (fadd A, B)
6611   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6612     return DAG.getNode(ISD::FADD, dl, VT, N0,
6613                        GetNegatedExpression(N1, DAG, LegalOperations));
6614
6615   // If 'unsafe math' is enabled, fold
6616   //    (fsub x, x) -> 0.0 &
6617   //    (fsub x, (fadd x, y)) -> (fneg y) &
6618   //    (fsub x, (fadd y, x)) -> (fneg y)
6619   if (DAG.getTarget().Options.UnsafeFPMath) {
6620     if (N0 == N1)
6621       return DAG.getConstantFP(0.0f, VT);
6622
6623     if (N1.getOpcode() == ISD::FADD) {
6624       SDValue N10 = N1->getOperand(0);
6625       SDValue N11 = N1->getOperand(1);
6626
6627       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6628                                           &DAG.getTarget().Options))
6629         return GetNegatedExpression(N11, DAG, LegalOperations);
6630
6631       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6632                                           &DAG.getTarget().Options))
6633         return GetNegatedExpression(N10, DAG, LegalOperations);
6634     }
6635   }
6636
6637   // FSUB -> FMA combines:
6638   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6639        DAG.getTarget().Options.UnsafeFPMath) &&
6640       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6641       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6642
6643     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6644     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6645       return DAG.getNode(ISD::FMA, dl, VT,
6646                          N0.getOperand(0), N0.getOperand(1),
6647                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6648
6649     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6650     // Note: Commutes FSUB operands.
6651     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6652       return DAG.getNode(ISD::FMA, dl, VT,
6653                          DAG.getNode(ISD::FNEG, dl, VT,
6654                          N1.getOperand(0)),
6655                          N1.getOperand(1), N0);
6656
6657     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6658     if (N0.getOpcode() == ISD::FNEG &&
6659         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6660         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6661       SDValue N00 = N0.getOperand(0).getOperand(0);
6662       SDValue N01 = N0.getOperand(0).getOperand(1);
6663       return DAG.getNode(ISD::FMA, dl, VT,
6664                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6665                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6666     }
6667   }
6668
6669   return SDValue();
6670 }
6671
6672 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6673   SDValue N0 = N->getOperand(0);
6674   SDValue N1 = N->getOperand(1);
6675   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6676   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6677   EVT VT = N->getValueType(0);
6678   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6679
6680   // fold vector ops
6681   if (VT.isVector()) {
6682     SDValue FoldedVOp = SimplifyVBinOp(N);
6683     if (FoldedVOp.getNode()) return FoldedVOp;
6684   }
6685
6686   // fold (fmul c1, c2) -> c1*c2
6687   if (N0CFP && N1CFP)
6688     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6689   // canonicalize constant to RHS
6690   if (N0CFP && !N1CFP)
6691     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6692   // fold (fmul A, 0) -> 0
6693   if (DAG.getTarget().Options.UnsafeFPMath &&
6694       N1CFP && N1CFP->getValueAPF().isZero())
6695     return N1;
6696   // fold (fmul A, 0) -> 0, vector edition.
6697   if (DAG.getTarget().Options.UnsafeFPMath &&
6698       ISD::isBuildVectorAllZeros(N1.getNode()))
6699     return N1;
6700   // fold (fmul A, 1.0) -> A
6701   if (N1CFP && N1CFP->isExactlyValue(1.0))
6702     return N0;
6703   // fold (fmul X, 2.0) -> (fadd X, X)
6704   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6705     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6706   // fold (fmul X, -1.0) -> (fneg X)
6707   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6708     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6709       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6710
6711   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6712   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6713                                        &DAG.getTarget().Options)) {
6714     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6715                                          &DAG.getTarget().Options)) {
6716       // Both can be negated for free, check to see if at least one is cheaper
6717       // negated.
6718       if (LHSNeg == 2 || RHSNeg == 2)
6719         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6720                            GetNegatedExpression(N0, DAG, LegalOperations),
6721                            GetNegatedExpression(N1, DAG, LegalOperations));
6722     }
6723   }
6724
6725   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6726   if (DAG.getTarget().Options.UnsafeFPMath &&
6727       N1CFP && N0.getOpcode() == ISD::FMUL &&
6728       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6729     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6730                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6731                                    N0.getOperand(1), N1));
6732
6733   return SDValue();
6734 }
6735
6736 SDValue DAGCombiner::visitFMA(SDNode *N) {
6737   SDValue N0 = N->getOperand(0);
6738   SDValue N1 = N->getOperand(1);
6739   SDValue N2 = N->getOperand(2);
6740   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6741   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6742   EVT VT = N->getValueType(0);
6743   SDLoc dl(N);
6744
6745   if (DAG.getTarget().Options.UnsafeFPMath) {
6746     if (N0CFP && N0CFP->isZero())
6747       return N2;
6748     if (N1CFP && N1CFP->isZero())
6749       return N2;
6750   }
6751   if (N0CFP && N0CFP->isExactlyValue(1.0))
6752     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6753   if (N1CFP && N1CFP->isExactlyValue(1.0))
6754     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6755
6756   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6757   if (N0CFP && !N1CFP)
6758     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6759
6760   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6761   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6762       N2.getOpcode() == ISD::FMUL &&
6763       N0 == N2.getOperand(0) &&
6764       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6765     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6766                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6767   }
6768
6769
6770   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6771   if (DAG.getTarget().Options.UnsafeFPMath &&
6772       N0.getOpcode() == ISD::FMUL && N1CFP &&
6773       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6774     return DAG.getNode(ISD::FMA, dl, VT,
6775                        N0.getOperand(0),
6776                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6777                        N2);
6778   }
6779
6780   // (fma x, 1, y) -> (fadd x, y)
6781   // (fma x, -1, y) -> (fadd (fneg x), y)
6782   if (N1CFP) {
6783     if (N1CFP->isExactlyValue(1.0))
6784       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6785
6786     if (N1CFP->isExactlyValue(-1.0) &&
6787         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6788       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6789       AddToWorkList(RHSNeg.getNode());
6790       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6791     }
6792   }
6793
6794   // (fma x, c, x) -> (fmul x, (c+1))
6795   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6796     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6797                        DAG.getNode(ISD::FADD, dl, VT,
6798                                    N1, DAG.getConstantFP(1.0, VT)));
6799
6800   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6801   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6802       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6803     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6804                        DAG.getNode(ISD::FADD, dl, VT,
6805                                    N1, DAG.getConstantFP(-1.0, VT)));
6806
6807
6808   return SDValue();
6809 }
6810
6811 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6812   SDValue N0 = N->getOperand(0);
6813   SDValue N1 = N->getOperand(1);
6814   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6815   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6816   EVT VT = N->getValueType(0);
6817   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6818
6819   // fold vector ops
6820   if (VT.isVector()) {
6821     SDValue FoldedVOp = SimplifyVBinOp(N);
6822     if (FoldedVOp.getNode()) return FoldedVOp;
6823   }
6824
6825   // fold (fdiv c1, c2) -> c1/c2
6826   if (N0CFP && N1CFP)
6827     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6828
6829   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6830   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6831     // Compute the reciprocal 1.0 / c2.
6832     APFloat N1APF = N1CFP->getValueAPF();
6833     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6834     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6835     // Only do the transform if the reciprocal is a legal fp immediate that
6836     // isn't too nasty (eg NaN, denormal, ...).
6837     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6838         (!LegalOperations ||
6839          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6840          // backend)... we should handle this gracefully after Legalize.
6841          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6842          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6843          TLI.isFPImmLegal(Recip, VT)))
6844       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6845                          DAG.getConstantFP(Recip, VT));
6846   }
6847
6848   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6849   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6850                                        &DAG.getTarget().Options)) {
6851     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6852                                          &DAG.getTarget().Options)) {
6853       // Both can be negated for free, check to see if at least one is cheaper
6854       // negated.
6855       if (LHSNeg == 2 || RHSNeg == 2)
6856         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6857                            GetNegatedExpression(N0, DAG, LegalOperations),
6858                            GetNegatedExpression(N1, DAG, LegalOperations));
6859     }
6860   }
6861
6862   return SDValue();
6863 }
6864
6865 SDValue DAGCombiner::visitFREM(SDNode *N) {
6866   SDValue N0 = N->getOperand(0);
6867   SDValue N1 = N->getOperand(1);
6868   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6869   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6870   EVT VT = N->getValueType(0);
6871
6872   // fold (frem c1, c2) -> fmod(c1,c2)
6873   if (N0CFP && N1CFP)
6874     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6875
6876   return SDValue();
6877 }
6878
6879 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6880   SDValue N0 = N->getOperand(0);
6881   SDValue N1 = N->getOperand(1);
6882   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6883   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6884   EVT VT = N->getValueType(0);
6885
6886   if (N0CFP && N1CFP)  // Constant fold
6887     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6888
6889   if (N1CFP) {
6890     const APFloat& V = N1CFP->getValueAPF();
6891     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6892     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6893     if (!V.isNegative()) {
6894       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6895         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6896     } else {
6897       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6898         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6899                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6900     }
6901   }
6902
6903   // copysign(fabs(x), y) -> copysign(x, y)
6904   // copysign(fneg(x), y) -> copysign(x, y)
6905   // copysign(copysign(x,z), y) -> copysign(x, y)
6906   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6907       N0.getOpcode() == ISD::FCOPYSIGN)
6908     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6909                        N0.getOperand(0), N1);
6910
6911   // copysign(x, abs(y)) -> abs(x)
6912   if (N1.getOpcode() == ISD::FABS)
6913     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6914
6915   // copysign(x, copysign(y,z)) -> copysign(x, z)
6916   if (N1.getOpcode() == ISD::FCOPYSIGN)
6917     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6918                        N0, N1.getOperand(1));
6919
6920   // copysign(x, fp_extend(y)) -> copysign(x, y)
6921   // copysign(x, fp_round(y)) -> copysign(x, y)
6922   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6923     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6924                        N0, N1.getOperand(0));
6925
6926   return SDValue();
6927 }
6928
6929 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6930   SDValue N0 = N->getOperand(0);
6931   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6932   EVT VT = N->getValueType(0);
6933   EVT OpVT = N0.getValueType();
6934
6935   // fold (sint_to_fp c1) -> c1fp
6936   if (N0C &&
6937       // ...but only if the target supports immediate floating-point values
6938       (!LegalOperations ||
6939        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6940     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6941
6942   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6943   // but UINT_TO_FP is legal on this target, try to convert.
6944   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6945       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6946     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6947     if (DAG.SignBitIsZero(N0))
6948       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6949   }
6950
6951   // The next optimizations are desirable only if SELECT_CC can be lowered.
6952   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6953   // having to say they don't support SELECT_CC on every type the DAG knows
6954   // about, since there is no way to mark an opcode illegal at all value types
6955   // (See also visitSELECT)
6956   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6957     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6958     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6959         !VT.isVector() &&
6960         (!LegalOperations ||
6961          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6962       SDValue Ops[] =
6963         { N0.getOperand(0), N0.getOperand(1),
6964           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6965           N0.getOperand(2) };
6966       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6967     }
6968
6969     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6970     //      (select_cc x, y, 1.0, 0.0,, cc)
6971     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6972         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6973         (!LegalOperations ||
6974          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6975       SDValue Ops[] =
6976         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6977           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6978           N0.getOperand(0).getOperand(2) };
6979       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6980     }
6981   }
6982
6983   return SDValue();
6984 }
6985
6986 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6987   SDValue N0 = N->getOperand(0);
6988   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6989   EVT VT = N->getValueType(0);
6990   EVT OpVT = N0.getValueType();
6991
6992   // fold (uint_to_fp c1) -> c1fp
6993   if (N0C &&
6994       // ...but only if the target supports immediate floating-point values
6995       (!LegalOperations ||
6996        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6997     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6998
6999   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7000   // but SINT_TO_FP is legal on this target, try to convert.
7001   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7002       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7003     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7004     if (DAG.SignBitIsZero(N0))
7005       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7006   }
7007
7008   // The next optimizations are desirable only if SELECT_CC can be lowered.
7009   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7010   // having to say they don't support SELECT_CC on every type the DAG knows
7011   // about, since there is no way to mark an opcode illegal at all value types
7012   // (See also visitSELECT)
7013   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7014     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7015
7016     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7017         (!LegalOperations ||
7018          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7019       SDValue Ops[] =
7020         { N0.getOperand(0), N0.getOperand(1),
7021           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7022           N0.getOperand(2) };
7023       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7024     }
7025   }
7026
7027   return SDValue();
7028 }
7029
7030 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7031   SDValue N0 = N->getOperand(0);
7032   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7033   EVT VT = N->getValueType(0);
7034
7035   // fold (fp_to_sint c1fp) -> c1
7036   if (N0CFP)
7037     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7038
7039   return SDValue();
7040 }
7041
7042 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7043   SDValue N0 = N->getOperand(0);
7044   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7045   EVT VT = N->getValueType(0);
7046
7047   // fold (fp_to_uint c1fp) -> c1
7048   if (N0CFP)
7049     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7050
7051   return SDValue();
7052 }
7053
7054 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7055   SDValue N0 = N->getOperand(0);
7056   SDValue N1 = N->getOperand(1);
7057   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7058   EVT VT = N->getValueType(0);
7059
7060   // fold (fp_round c1fp) -> c1fp
7061   if (N0CFP)
7062     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7063
7064   // fold (fp_round (fp_extend x)) -> x
7065   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7066     return N0.getOperand(0);
7067
7068   // fold (fp_round (fp_round x)) -> (fp_round x)
7069   if (N0.getOpcode() == ISD::FP_ROUND) {
7070     // This is a value preserving truncation if both round's are.
7071     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7072                    N0.getNode()->getConstantOperandVal(1) == 1;
7073     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7074                        DAG.getIntPtrConstant(IsTrunc));
7075   }
7076
7077   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7078   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7079     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7080                               N0.getOperand(0), N1);
7081     AddToWorkList(Tmp.getNode());
7082     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7083                        Tmp, N0.getOperand(1));
7084   }
7085
7086   return SDValue();
7087 }
7088
7089 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7090   SDValue N0 = N->getOperand(0);
7091   EVT VT = N->getValueType(0);
7092   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7093   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7094
7095   // fold (fp_round_inreg c1fp) -> c1fp
7096   if (N0CFP && isTypeLegal(EVT)) {
7097     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7098     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7099   }
7100
7101   return SDValue();
7102 }
7103
7104 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7105   SDValue N0 = N->getOperand(0);
7106   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7107   EVT VT = N->getValueType(0);
7108
7109   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7110   if (N->hasOneUse() &&
7111       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7112     return SDValue();
7113
7114   // fold (fp_extend c1fp) -> c1fp
7115   if (N0CFP)
7116     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7117
7118   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7119   // value of X.
7120   if (N0.getOpcode() == ISD::FP_ROUND
7121       && N0.getNode()->getConstantOperandVal(1) == 1) {
7122     SDValue In = N0.getOperand(0);
7123     if (In.getValueType() == VT) return In;
7124     if (VT.bitsLT(In.getValueType()))
7125       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7126                          In, N0.getOperand(1));
7127     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7128   }
7129
7130   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7131   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7132       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7133        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7134     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7135     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7136                                      LN0->getChain(),
7137                                      LN0->getBasePtr(), N0.getValueType(),
7138                                      LN0->getMemOperand());
7139     CombineTo(N, ExtLoad);
7140     CombineTo(N0.getNode(),
7141               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7142                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7143               ExtLoad.getValue(1));
7144     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7145   }
7146
7147   return SDValue();
7148 }
7149
7150 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7151   SDValue N0 = N->getOperand(0);
7152   EVT VT = N->getValueType(0);
7153
7154   if (VT.isVector()) {
7155     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7156     if (FoldedVOp.getNode()) return FoldedVOp;
7157   }
7158
7159   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7160                          &DAG.getTarget().Options))
7161     return GetNegatedExpression(N0, DAG, LegalOperations);
7162
7163   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7164   // constant pool values.
7165   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7166       !VT.isVector() &&
7167       N0.getNode()->hasOneUse() &&
7168       N0.getOperand(0).getValueType().isInteger()) {
7169     SDValue Int = N0.getOperand(0);
7170     EVT IntVT = Int.getValueType();
7171     if (IntVT.isInteger() && !IntVT.isVector()) {
7172       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7173               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7174       AddToWorkList(Int.getNode());
7175       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7176                          VT, Int);
7177     }
7178   }
7179
7180   // (fneg (fmul c, x)) -> (fmul -c, x)
7181   if (N0.getOpcode() == ISD::FMUL) {
7182     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7183     if (CFP1)
7184       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7185                          N0.getOperand(0),
7186                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7187                                      N0.getOperand(1)));
7188   }
7189
7190   return SDValue();
7191 }
7192
7193 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7194   SDValue N0 = N->getOperand(0);
7195   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7196   EVT VT = N->getValueType(0);
7197
7198   // fold (fceil c1) -> fceil(c1)
7199   if (N0CFP)
7200     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7201
7202   return SDValue();
7203 }
7204
7205 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7206   SDValue N0 = N->getOperand(0);
7207   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7208   EVT VT = N->getValueType(0);
7209
7210   // fold (ftrunc c1) -> ftrunc(c1)
7211   if (N0CFP)
7212     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7213
7214   return SDValue();
7215 }
7216
7217 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7218   SDValue N0 = N->getOperand(0);
7219   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7220   EVT VT = N->getValueType(0);
7221
7222   // fold (ffloor c1) -> ffloor(c1)
7223   if (N0CFP)
7224     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7225
7226   return SDValue();
7227 }
7228
7229 SDValue DAGCombiner::visitFABS(SDNode *N) {
7230   SDValue N0 = N->getOperand(0);
7231   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7232   EVT VT = N->getValueType(0);
7233
7234   if (VT.isVector()) {
7235     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7236     if (FoldedVOp.getNode()) return FoldedVOp;
7237   }
7238
7239   // fold (fabs c1) -> fabs(c1)
7240   if (N0CFP)
7241     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7242   // fold (fabs (fabs x)) -> (fabs x)
7243   if (N0.getOpcode() == ISD::FABS)
7244     return N->getOperand(0);
7245   // fold (fabs (fneg x)) -> (fabs x)
7246   // fold (fabs (fcopysign x, y)) -> (fabs x)
7247   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7248     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7249
7250   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7251   // constant pool values.
7252   if (!TLI.isFAbsFree(VT) &&
7253       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7254       N0.getOperand(0).getValueType().isInteger() &&
7255       !N0.getOperand(0).getValueType().isVector()) {
7256     SDValue Int = N0.getOperand(0);
7257     EVT IntVT = Int.getValueType();
7258     if (IntVT.isInteger() && !IntVT.isVector()) {
7259       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7260              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7261       AddToWorkList(Int.getNode());
7262       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7263                          N->getValueType(0), Int);
7264     }
7265   }
7266
7267   return SDValue();
7268 }
7269
7270 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7271   SDValue Chain = N->getOperand(0);
7272   SDValue N1 = N->getOperand(1);
7273   SDValue N2 = N->getOperand(2);
7274
7275   // If N is a constant we could fold this into a fallthrough or unconditional
7276   // branch. However that doesn't happen very often in normal code, because
7277   // Instcombine/SimplifyCFG should have handled the available opportunities.
7278   // If we did this folding here, it would be necessary to update the
7279   // MachineBasicBlock CFG, which is awkward.
7280
7281   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7282   // on the target.
7283   if (N1.getOpcode() == ISD::SETCC &&
7284       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7285                                    N1.getOperand(0).getValueType())) {
7286     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7287                        Chain, N1.getOperand(2),
7288                        N1.getOperand(0), N1.getOperand(1), N2);
7289   }
7290
7291   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7292       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7293        (N1.getOperand(0).hasOneUse() &&
7294         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7295     SDNode *Trunc = nullptr;
7296     if (N1.getOpcode() == ISD::TRUNCATE) {
7297       // Look pass the truncate.
7298       Trunc = N1.getNode();
7299       N1 = N1.getOperand(0);
7300     }
7301
7302     // Match this pattern so that we can generate simpler code:
7303     //
7304     //   %a = ...
7305     //   %b = and i32 %a, 2
7306     //   %c = srl i32 %b, 1
7307     //   brcond i32 %c ...
7308     //
7309     // into
7310     //
7311     //   %a = ...
7312     //   %b = and i32 %a, 2
7313     //   %c = setcc eq %b, 0
7314     //   brcond %c ...
7315     //
7316     // This applies only when the AND constant value has one bit set and the
7317     // SRL constant is equal to the log2 of the AND constant. The back-end is
7318     // smart enough to convert the result into a TEST/JMP sequence.
7319     SDValue Op0 = N1.getOperand(0);
7320     SDValue Op1 = N1.getOperand(1);
7321
7322     if (Op0.getOpcode() == ISD::AND &&
7323         Op1.getOpcode() == ISD::Constant) {
7324       SDValue AndOp1 = Op0.getOperand(1);
7325
7326       if (AndOp1.getOpcode() == ISD::Constant) {
7327         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7328
7329         if (AndConst.isPowerOf2() &&
7330             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7331           SDValue SetCC =
7332             DAG.getSetCC(SDLoc(N),
7333                          getSetCCResultType(Op0.getValueType()),
7334                          Op0, DAG.getConstant(0, Op0.getValueType()),
7335                          ISD::SETNE);
7336
7337           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7338                                           MVT::Other, Chain, SetCC, N2);
7339           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7340           // will convert it back to (X & C1) >> C2.
7341           CombineTo(N, NewBRCond, false);
7342           // Truncate is dead.
7343           if (Trunc) {
7344             removeFromWorkList(Trunc);
7345             DAG.DeleteNode(Trunc);
7346           }
7347           // Replace the uses of SRL with SETCC
7348           WorkListRemover DeadNodes(*this);
7349           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7350           removeFromWorkList(N1.getNode());
7351           DAG.DeleteNode(N1.getNode());
7352           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7353         }
7354       }
7355     }
7356
7357     if (Trunc)
7358       // Restore N1 if the above transformation doesn't match.
7359       N1 = N->getOperand(1);
7360   }
7361
7362   // Transform br(xor(x, y)) -> br(x != y)
7363   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7364   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7365     SDNode *TheXor = N1.getNode();
7366     SDValue Op0 = TheXor->getOperand(0);
7367     SDValue Op1 = TheXor->getOperand(1);
7368     if (Op0.getOpcode() == Op1.getOpcode()) {
7369       // Avoid missing important xor optimizations.
7370       SDValue Tmp = visitXOR(TheXor);
7371       if (Tmp.getNode()) {
7372         if (Tmp.getNode() != TheXor) {
7373           DEBUG(dbgs() << "\nReplacing.8 ";
7374                 TheXor->dump(&DAG);
7375                 dbgs() << "\nWith: ";
7376                 Tmp.getNode()->dump(&DAG);
7377                 dbgs() << '\n');
7378           WorkListRemover DeadNodes(*this);
7379           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7380           removeFromWorkList(TheXor);
7381           DAG.DeleteNode(TheXor);
7382           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7383                              MVT::Other, Chain, Tmp, N2);
7384         }
7385
7386         // visitXOR has changed XOR's operands or replaced the XOR completely,
7387         // bail out.
7388         return SDValue(N, 0);
7389       }
7390     }
7391
7392     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7393       bool Equal = false;
7394       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7395         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7396             Op0.getOpcode() == ISD::XOR) {
7397           TheXor = Op0.getNode();
7398           Equal = true;
7399         }
7400
7401       EVT SetCCVT = N1.getValueType();
7402       if (LegalTypes)
7403         SetCCVT = getSetCCResultType(SetCCVT);
7404       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7405                                    SetCCVT,
7406                                    Op0, Op1,
7407                                    Equal ? ISD::SETEQ : ISD::SETNE);
7408       // Replace the uses of XOR with SETCC
7409       WorkListRemover DeadNodes(*this);
7410       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7411       removeFromWorkList(N1.getNode());
7412       DAG.DeleteNode(N1.getNode());
7413       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7414                          MVT::Other, Chain, SetCC, N2);
7415     }
7416   }
7417
7418   return SDValue();
7419 }
7420
7421 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7422 //
7423 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7424   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7425   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7426
7427   // If N is a constant we could fold this into a fallthrough or unconditional
7428   // branch. However that doesn't happen very often in normal code, because
7429   // Instcombine/SimplifyCFG should have handled the available opportunities.
7430   // If we did this folding here, it would be necessary to update the
7431   // MachineBasicBlock CFG, which is awkward.
7432
7433   // Use SimplifySetCC to simplify SETCC's.
7434   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7435                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7436                                false);
7437   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7438
7439   // fold to a simpler setcc
7440   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7441     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7442                        N->getOperand(0), Simp.getOperand(2),
7443                        Simp.getOperand(0), Simp.getOperand(1),
7444                        N->getOperand(4));
7445
7446   return SDValue();
7447 }
7448
7449 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7450 /// uses N as its base pointer and that N may be folded in the load / store
7451 /// addressing mode.
7452 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7453                                     SelectionDAG &DAG,
7454                                     const TargetLowering &TLI) {
7455   EVT VT;
7456   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7457     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7458       return false;
7459     VT = Use->getValueType(0);
7460   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7461     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7462       return false;
7463     VT = ST->getValue().getValueType();
7464   } else
7465     return false;
7466
7467   TargetLowering::AddrMode AM;
7468   if (N->getOpcode() == ISD::ADD) {
7469     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7470     if (Offset)
7471       // [reg +/- imm]
7472       AM.BaseOffs = Offset->getSExtValue();
7473     else
7474       // [reg +/- reg]
7475       AM.Scale = 1;
7476   } else if (N->getOpcode() == ISD::SUB) {
7477     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7478     if (Offset)
7479       // [reg +/- imm]
7480       AM.BaseOffs = -Offset->getSExtValue();
7481     else
7482       // [reg +/- reg]
7483       AM.Scale = 1;
7484   } else
7485     return false;
7486
7487   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7488 }
7489
7490 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7491 /// pre-indexed load / store when the base pointer is an add or subtract
7492 /// and it has other uses besides the load / store. After the
7493 /// transformation, the new indexed load / store has effectively folded
7494 /// the add / subtract in and all of its other uses are redirected to the
7495 /// new load / store.
7496 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7497   if (Level < AfterLegalizeDAG)
7498     return false;
7499
7500   bool isLoad = true;
7501   SDValue Ptr;
7502   EVT VT;
7503   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7504     if (LD->isIndexed())
7505       return false;
7506     VT = LD->getMemoryVT();
7507     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7508         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7509       return false;
7510     Ptr = LD->getBasePtr();
7511   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7512     if (ST->isIndexed())
7513       return false;
7514     VT = ST->getMemoryVT();
7515     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7516         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7517       return false;
7518     Ptr = ST->getBasePtr();
7519     isLoad = false;
7520   } else {
7521     return false;
7522   }
7523
7524   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7525   // out.  There is no reason to make this a preinc/predec.
7526   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7527       Ptr.getNode()->hasOneUse())
7528     return false;
7529
7530   // Ask the target to do addressing mode selection.
7531   SDValue BasePtr;
7532   SDValue Offset;
7533   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7534   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7535     return false;
7536
7537   // Backends without true r+i pre-indexed forms may need to pass a
7538   // constant base with a variable offset so that constant coercion
7539   // will work with the patterns in canonical form.
7540   bool Swapped = false;
7541   if (isa<ConstantSDNode>(BasePtr)) {
7542     std::swap(BasePtr, Offset);
7543     Swapped = true;
7544   }
7545
7546   // Don't create a indexed load / store with zero offset.
7547   if (isa<ConstantSDNode>(Offset) &&
7548       cast<ConstantSDNode>(Offset)->isNullValue())
7549     return false;
7550
7551   // Try turning it into a pre-indexed load / store except when:
7552   // 1) The new base ptr is a frame index.
7553   // 2) If N is a store and the new base ptr is either the same as or is a
7554   //    predecessor of the value being stored.
7555   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7556   //    that would create a cycle.
7557   // 4) All uses are load / store ops that use it as old base ptr.
7558
7559   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7560   // (plus the implicit offset) to a register to preinc anyway.
7561   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7562     return false;
7563
7564   // Check #2.
7565   if (!isLoad) {
7566     SDValue Val = cast<StoreSDNode>(N)->getValue();
7567     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7568       return false;
7569   }
7570
7571   // If the offset is a constant, there may be other adds of constants that
7572   // can be folded with this one. We should do this to avoid having to keep
7573   // a copy of the original base pointer.
7574   SmallVector<SDNode *, 16> OtherUses;
7575   if (isa<ConstantSDNode>(Offset))
7576     for (SDNode *Use : BasePtr.getNode()->uses()) {
7577       if (Use == Ptr.getNode())
7578         continue;
7579
7580       if (Use->isPredecessorOf(N))
7581         continue;
7582
7583       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7584         OtherUses.clear();
7585         break;
7586       }
7587
7588       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7589       if (Op1.getNode() == BasePtr.getNode())
7590         std::swap(Op0, Op1);
7591       assert(Op0.getNode() == BasePtr.getNode() &&
7592              "Use of ADD/SUB but not an operand");
7593
7594       if (!isa<ConstantSDNode>(Op1)) {
7595         OtherUses.clear();
7596         break;
7597       }
7598
7599       // FIXME: In some cases, we can be smarter about this.
7600       if (Op1.getValueType() != Offset.getValueType()) {
7601         OtherUses.clear();
7602         break;
7603       }
7604
7605       OtherUses.push_back(Use);
7606     }
7607
7608   if (Swapped)
7609     std::swap(BasePtr, Offset);
7610
7611   // Now check for #3 and #4.
7612   bool RealUse = false;
7613
7614   // Caches for hasPredecessorHelper
7615   SmallPtrSet<const SDNode *, 32> Visited;
7616   SmallVector<const SDNode *, 16> Worklist;
7617
7618   for (SDNode *Use : Ptr.getNode()->uses()) {
7619     if (Use == N)
7620       continue;
7621     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7622       return false;
7623
7624     // If Ptr may be folded in addressing mode of other use, then it's
7625     // not profitable to do this transformation.
7626     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7627       RealUse = true;
7628   }
7629
7630   if (!RealUse)
7631     return false;
7632
7633   SDValue Result;
7634   if (isLoad)
7635     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7636                                 BasePtr, Offset, AM);
7637   else
7638     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7639                                  BasePtr, Offset, AM);
7640   ++PreIndexedNodes;
7641   ++NodesCombined;
7642   DEBUG(dbgs() << "\nReplacing.4 ";
7643         N->dump(&DAG);
7644         dbgs() << "\nWith: ";
7645         Result.getNode()->dump(&DAG);
7646         dbgs() << '\n');
7647   WorkListRemover DeadNodes(*this);
7648   if (isLoad) {
7649     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7650     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7651   } else {
7652     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7653   }
7654
7655   // Finally, since the node is now dead, remove it from the graph.
7656   DAG.DeleteNode(N);
7657
7658   if (Swapped)
7659     std::swap(BasePtr, Offset);
7660
7661   // Replace other uses of BasePtr that can be updated to use Ptr
7662   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7663     unsigned OffsetIdx = 1;
7664     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7665       OffsetIdx = 0;
7666     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7667            BasePtr.getNode() && "Expected BasePtr operand");
7668
7669     // We need to replace ptr0 in the following expression:
7670     //   x0 * offset0 + y0 * ptr0 = t0
7671     // knowing that
7672     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7673     //
7674     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7675     // indexed load/store and the expresion that needs to be re-written.
7676     //
7677     // Therefore, we have:
7678     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7679
7680     ConstantSDNode *CN =
7681       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7682     int X0, X1, Y0, Y1;
7683     APInt Offset0 = CN->getAPIntValue();
7684     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7685
7686     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7687     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7688     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7689     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7690
7691     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7692
7693     APInt CNV = Offset0;
7694     if (X0 < 0) CNV = -CNV;
7695     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7696     else CNV = CNV - Offset1;
7697
7698     // We can now generate the new expression.
7699     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7700     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7701
7702     SDValue NewUse = DAG.getNode(Opcode,
7703                                  SDLoc(OtherUses[i]),
7704                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7705     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7706     removeFromWorkList(OtherUses[i]);
7707     DAG.DeleteNode(OtherUses[i]);
7708   }
7709
7710   // Replace the uses of Ptr with uses of the updated base value.
7711   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7712   removeFromWorkList(Ptr.getNode());
7713   DAG.DeleteNode(Ptr.getNode());
7714
7715   return true;
7716 }
7717
7718 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7719 /// add / sub of the base pointer node into a post-indexed load / store.
7720 /// The transformation folded the add / subtract into the new indexed
7721 /// load / store effectively and all of its uses are redirected to the
7722 /// new load / store.
7723 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7724   if (Level < AfterLegalizeDAG)
7725     return false;
7726
7727   bool isLoad = true;
7728   SDValue Ptr;
7729   EVT VT;
7730   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7731     if (LD->isIndexed())
7732       return false;
7733     VT = LD->getMemoryVT();
7734     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7735         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7736       return false;
7737     Ptr = LD->getBasePtr();
7738   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7739     if (ST->isIndexed())
7740       return false;
7741     VT = ST->getMemoryVT();
7742     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7743         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7744       return false;
7745     Ptr = ST->getBasePtr();
7746     isLoad = false;
7747   } else {
7748     return false;
7749   }
7750
7751   if (Ptr.getNode()->hasOneUse())
7752     return false;
7753
7754   for (SDNode *Op : Ptr.getNode()->uses()) {
7755     if (Op == N ||
7756         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7757       continue;
7758
7759     SDValue BasePtr;
7760     SDValue Offset;
7761     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7762     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7763       // Don't create a indexed load / store with zero offset.
7764       if (isa<ConstantSDNode>(Offset) &&
7765           cast<ConstantSDNode>(Offset)->isNullValue())
7766         continue;
7767
7768       // Try turning it into a post-indexed load / store except when
7769       // 1) All uses are load / store ops that use it as base ptr (and
7770       //    it may be folded as addressing mmode).
7771       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7772       //    nor a successor of N. Otherwise, if Op is folded that would
7773       //    create a cycle.
7774
7775       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7776         continue;
7777
7778       // Check for #1.
7779       bool TryNext = false;
7780       for (SDNode *Use : BasePtr.getNode()->uses()) {
7781         if (Use == Ptr.getNode())
7782           continue;
7783
7784         // If all the uses are load / store addresses, then don't do the
7785         // transformation.
7786         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7787           bool RealUse = false;
7788           for (SDNode *UseUse : Use->uses()) {
7789             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7790               RealUse = true;
7791           }
7792
7793           if (!RealUse) {
7794             TryNext = true;
7795             break;
7796           }
7797         }
7798       }
7799
7800       if (TryNext)
7801         continue;
7802
7803       // Check for #2
7804       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7805         SDValue Result = isLoad
7806           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7807                                BasePtr, Offset, AM)
7808           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7809                                 BasePtr, Offset, AM);
7810         ++PostIndexedNodes;
7811         ++NodesCombined;
7812         DEBUG(dbgs() << "\nReplacing.5 ";
7813               N->dump(&DAG);
7814               dbgs() << "\nWith: ";
7815               Result.getNode()->dump(&DAG);
7816               dbgs() << '\n');
7817         WorkListRemover DeadNodes(*this);
7818         if (isLoad) {
7819           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7820           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7821         } else {
7822           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7823         }
7824
7825         // Finally, since the node is now dead, remove it from the graph.
7826         DAG.DeleteNode(N);
7827
7828         // Replace the uses of Use with uses of the updated base value.
7829         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7830                                       Result.getValue(isLoad ? 1 : 0));
7831         removeFromWorkList(Op);
7832         DAG.DeleteNode(Op);
7833         return true;
7834       }
7835     }
7836   }
7837
7838   return false;
7839 }
7840
7841 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7842   LoadSDNode *LD  = cast<LoadSDNode>(N);
7843   SDValue Chain = LD->getChain();
7844   SDValue Ptr   = LD->getBasePtr();
7845
7846   // If load is not volatile and there are no uses of the loaded value (and
7847   // the updated indexed value in case of indexed loads), change uses of the
7848   // chain value into uses of the chain input (i.e. delete the dead load).
7849   if (!LD->isVolatile()) {
7850     if (N->getValueType(1) == MVT::Other) {
7851       // Unindexed loads.
7852       if (!N->hasAnyUseOfValue(0)) {
7853         // It's not safe to use the two value CombineTo variant here. e.g.
7854         // v1, chain2 = load chain1, loc
7855         // v2, chain3 = load chain2, loc
7856         // v3         = add v2, c
7857         // Now we replace use of chain2 with chain1.  This makes the second load
7858         // isomorphic to the one we are deleting, and thus makes this load live.
7859         DEBUG(dbgs() << "\nReplacing.6 ";
7860               N->dump(&DAG);
7861               dbgs() << "\nWith chain: ";
7862               Chain.getNode()->dump(&DAG);
7863               dbgs() << "\n");
7864         WorkListRemover DeadNodes(*this);
7865         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7866
7867         if (N->use_empty()) {
7868           removeFromWorkList(N);
7869           DAG.DeleteNode(N);
7870         }
7871
7872         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7873       }
7874     } else {
7875       // Indexed loads.
7876       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7877       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7878         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7879         DEBUG(dbgs() << "\nReplacing.7 ";
7880               N->dump(&DAG);
7881               dbgs() << "\nWith: ";
7882               Undef.getNode()->dump(&DAG);
7883               dbgs() << " and 2 other values\n");
7884         WorkListRemover DeadNodes(*this);
7885         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7886         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7887                                       DAG.getUNDEF(N->getValueType(1)));
7888         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7889         removeFromWorkList(N);
7890         DAG.DeleteNode(N);
7891         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7892       }
7893     }
7894   }
7895
7896   // If this load is directly stored, replace the load value with the stored
7897   // value.
7898   // TODO: Handle store large -> read small portion.
7899   // TODO: Handle TRUNCSTORE/LOADEXT
7900   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7901     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7902       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7903       if (PrevST->getBasePtr() == Ptr &&
7904           PrevST->getValue().getValueType() == N->getValueType(0))
7905       return CombineTo(N, Chain.getOperand(1), Chain);
7906     }
7907   }
7908
7909   // Try to infer better alignment information than the load already has.
7910   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7911     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7912       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7913         SDValue NewLoad =
7914                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7915                               LD->getValueType(0),
7916                               Chain, Ptr, LD->getPointerInfo(),
7917                               LD->getMemoryVT(),
7918                               LD->isVolatile(), LD->isNonTemporal(), Align,
7919                               LD->getTBAAInfo());
7920         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7921       }
7922     }
7923   }
7924
7925   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7926     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7927 #ifndef NDEBUG
7928   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7929       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7930     UseAA = false;
7931 #endif
7932   if (UseAA && LD->isUnindexed()) {
7933     // Walk up chain skipping non-aliasing memory nodes.
7934     SDValue BetterChain = FindBetterChain(N, Chain);
7935
7936     // If there is a better chain.
7937     if (Chain != BetterChain) {
7938       SDValue ReplLoad;
7939
7940       // Replace the chain to void dependency.
7941       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7942         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7943                                BetterChain, Ptr, LD->getMemOperand());
7944       } else {
7945         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7946                                   LD->getValueType(0),
7947                                   BetterChain, Ptr, LD->getMemoryVT(),
7948                                   LD->getMemOperand());
7949       }
7950
7951       // Create token factor to keep old chain connected.
7952       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7953                                   MVT::Other, Chain, ReplLoad.getValue(1));
7954
7955       // Make sure the new and old chains are cleaned up.
7956       AddToWorkList(Token.getNode());
7957
7958       // Replace uses with load result and token factor. Don't add users
7959       // to work list.
7960       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7961     }
7962   }
7963
7964   // Try transforming N to an indexed load.
7965   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7966     return SDValue(N, 0);
7967
7968   // Try to slice up N to more direct loads if the slices are mapped to
7969   // different register banks or pairing can take place.
7970   if (SliceUpLoad(N))
7971     return SDValue(N, 0);
7972
7973   return SDValue();
7974 }
7975
7976 namespace {
7977 /// \brief Helper structure used to slice a load in smaller loads.
7978 /// Basically a slice is obtained from the following sequence:
7979 /// Origin = load Ty1, Base
7980 /// Shift = srl Ty1 Origin, CstTy Amount
7981 /// Inst = trunc Shift to Ty2
7982 ///
7983 /// Then, it will be rewriten into:
7984 /// Slice = load SliceTy, Base + SliceOffset
7985 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7986 ///
7987 /// SliceTy is deduced from the number of bits that are actually used to
7988 /// build Inst.
7989 struct LoadedSlice {
7990   /// \brief Helper structure used to compute the cost of a slice.
7991   struct Cost {
7992     /// Are we optimizing for code size.
7993     bool ForCodeSize;
7994     /// Various cost.
7995     unsigned Loads;
7996     unsigned Truncates;
7997     unsigned CrossRegisterBanksCopies;
7998     unsigned ZExts;
7999     unsigned Shift;
8000
8001     Cost(bool ForCodeSize = false)
8002         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8003           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8004
8005     /// \brief Get the cost of one isolated slice.
8006     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8007         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8008           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8009       EVT TruncType = LS.Inst->getValueType(0);
8010       EVT LoadedType = LS.getLoadedType();
8011       if (TruncType != LoadedType &&
8012           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8013         ZExts = 1;
8014     }
8015
8016     /// \brief Account for slicing gain in the current cost.
8017     /// Slicing provide a few gains like removing a shift or a
8018     /// truncate. This method allows to grow the cost of the original
8019     /// load with the gain from this slice.
8020     void addSliceGain(const LoadedSlice &LS) {
8021       // Each slice saves a truncate.
8022       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8023       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8024                               LS.Inst->getOperand(0).getValueType()))
8025         ++Truncates;
8026       // If there is a shift amount, this slice gets rid of it.
8027       if (LS.Shift)
8028         ++Shift;
8029       // If this slice can merge a cross register bank copy, account for it.
8030       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8031         ++CrossRegisterBanksCopies;
8032     }
8033
8034     Cost &operator+=(const Cost &RHS) {
8035       Loads += RHS.Loads;
8036       Truncates += RHS.Truncates;
8037       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8038       ZExts += RHS.ZExts;
8039       Shift += RHS.Shift;
8040       return *this;
8041     }
8042
8043     bool operator==(const Cost &RHS) const {
8044       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8045              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8046              ZExts == RHS.ZExts && Shift == RHS.Shift;
8047     }
8048
8049     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8050
8051     bool operator<(const Cost &RHS) const {
8052       // Assume cross register banks copies are as expensive as loads.
8053       // FIXME: Do we want some more target hooks?
8054       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8055       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8056       // Unless we are optimizing for code size, consider the
8057       // expensive operation first.
8058       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8059         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8060       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8061              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8062     }
8063
8064     bool operator>(const Cost &RHS) const { return RHS < *this; }
8065
8066     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8067
8068     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8069   };
8070   // The last instruction that represent the slice. This should be a
8071   // truncate instruction.
8072   SDNode *Inst;
8073   // The original load instruction.
8074   LoadSDNode *Origin;
8075   // The right shift amount in bits from the original load.
8076   unsigned Shift;
8077   // The DAG from which Origin came from.
8078   // This is used to get some contextual information about legal types, etc.
8079   SelectionDAG *DAG;
8080
8081   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8082               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8083       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8084
8085   LoadedSlice(const LoadedSlice &LS)
8086       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8087
8088   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8089   /// \return Result is \p BitWidth and has used bits set to 1 and
8090   ///         not used bits set to 0.
8091   APInt getUsedBits() const {
8092     // Reproduce the trunc(lshr) sequence:
8093     // - Start from the truncated value.
8094     // - Zero extend to the desired bit width.
8095     // - Shift left.
8096     assert(Origin && "No original load to compare against.");
8097     unsigned BitWidth = Origin->getValueSizeInBits(0);
8098     assert(Inst && "This slice is not bound to an instruction");
8099     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8100            "Extracted slice is bigger than the whole type!");
8101     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8102     UsedBits.setAllBits();
8103     UsedBits = UsedBits.zext(BitWidth);
8104     UsedBits <<= Shift;
8105     return UsedBits;
8106   }
8107
8108   /// \brief Get the size of the slice to be loaded in bytes.
8109   unsigned getLoadedSize() const {
8110     unsigned SliceSize = getUsedBits().countPopulation();
8111     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8112     return SliceSize / 8;
8113   }
8114
8115   /// \brief Get the type that will be loaded for this slice.
8116   /// Note: This may not be the final type for the slice.
8117   EVT getLoadedType() const {
8118     assert(DAG && "Missing context");
8119     LLVMContext &Ctxt = *DAG->getContext();
8120     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8121   }
8122
8123   /// \brief Get the alignment of the load used for this slice.
8124   unsigned getAlignment() const {
8125     unsigned Alignment = Origin->getAlignment();
8126     unsigned Offset = getOffsetFromBase();
8127     if (Offset != 0)
8128       Alignment = MinAlign(Alignment, Alignment + Offset);
8129     return Alignment;
8130   }
8131
8132   /// \brief Check if this slice can be rewritten with legal operations.
8133   bool isLegal() const {
8134     // An invalid slice is not legal.
8135     if (!Origin || !Inst || !DAG)
8136       return false;
8137
8138     // Offsets are for indexed load only, we do not handle that.
8139     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8140       return false;
8141
8142     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8143
8144     // Check that the type is legal.
8145     EVT SliceType = getLoadedType();
8146     if (!TLI.isTypeLegal(SliceType))
8147       return false;
8148
8149     // Check that the load is legal for this type.
8150     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8151       return false;
8152
8153     // Check that the offset can be computed.
8154     // 1. Check its type.
8155     EVT PtrType = Origin->getBasePtr().getValueType();
8156     if (PtrType == MVT::Untyped || PtrType.isExtended())
8157       return false;
8158
8159     // 2. Check that it fits in the immediate.
8160     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8161       return false;
8162
8163     // 3. Check that the computation is legal.
8164     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8165       return false;
8166
8167     // Check that the zext is legal if it needs one.
8168     EVT TruncateType = Inst->getValueType(0);
8169     if (TruncateType != SliceType &&
8170         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8171       return false;
8172
8173     return true;
8174   }
8175
8176   /// \brief Get the offset in bytes of this slice in the original chunk of
8177   /// bits.
8178   /// \pre DAG != nullptr.
8179   uint64_t getOffsetFromBase() const {
8180     assert(DAG && "Missing context.");
8181     bool IsBigEndian =
8182         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8183     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8184     uint64_t Offset = Shift / 8;
8185     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8186     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8187            "The size of the original loaded type is not a multiple of a"
8188            " byte.");
8189     // If Offset is bigger than TySizeInBytes, it means we are loading all
8190     // zeros. This should have been optimized before in the process.
8191     assert(TySizeInBytes > Offset &&
8192            "Invalid shift amount for given loaded size");
8193     if (IsBigEndian)
8194       Offset = TySizeInBytes - Offset - getLoadedSize();
8195     return Offset;
8196   }
8197
8198   /// \brief Generate the sequence of instructions to load the slice
8199   /// represented by this object and redirect the uses of this slice to
8200   /// this new sequence of instructions.
8201   /// \pre this->Inst && this->Origin are valid Instructions and this
8202   /// object passed the legal check: LoadedSlice::isLegal returned true.
8203   /// \return The last instruction of the sequence used to load the slice.
8204   SDValue loadSlice() const {
8205     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8206     const SDValue &OldBaseAddr = Origin->getBasePtr();
8207     SDValue BaseAddr = OldBaseAddr;
8208     // Get the offset in that chunk of bytes w.r.t. the endianess.
8209     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8210     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8211     if (Offset) {
8212       // BaseAddr = BaseAddr + Offset.
8213       EVT ArithType = BaseAddr.getValueType();
8214       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8215                               DAG->getConstant(Offset, ArithType));
8216     }
8217
8218     // Create the type of the loaded slice according to its size.
8219     EVT SliceType = getLoadedType();
8220
8221     // Create the load for the slice.
8222     SDValue LastInst = DAG->getLoad(
8223         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8224         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8225         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8226     // If the final type is not the same as the loaded type, this means that
8227     // we have to pad with zero. Create a zero extend for that.
8228     EVT FinalType = Inst->getValueType(0);
8229     if (SliceType != FinalType)
8230       LastInst =
8231           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8232     return LastInst;
8233   }
8234
8235   /// \brief Check if this slice can be merged with an expensive cross register
8236   /// bank copy. E.g.,
8237   /// i = load i32
8238   /// f = bitcast i32 i to float
8239   bool canMergeExpensiveCrossRegisterBankCopy() const {
8240     if (!Inst || !Inst->hasOneUse())
8241       return false;
8242     SDNode *Use = *Inst->use_begin();
8243     if (Use->getOpcode() != ISD::BITCAST)
8244       return false;
8245     assert(DAG && "Missing context");
8246     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8247     EVT ResVT = Use->getValueType(0);
8248     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8249     const TargetRegisterClass *ArgRC =
8250         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8251     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8252       return false;
8253
8254     // At this point, we know that we perform a cross-register-bank copy.
8255     // Check if it is expensive.
8256     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8257     // Assume bitcasts are cheap, unless both register classes do not
8258     // explicitly share a common sub class.
8259     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8260       return false;
8261
8262     // Check if it will be merged with the load.
8263     // 1. Check the alignment constraint.
8264     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8265         ResVT.getTypeForEVT(*DAG->getContext()));
8266
8267     if (RequiredAlignment > getAlignment())
8268       return false;
8269
8270     // 2. Check that the load is a legal operation for that type.
8271     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8272       return false;
8273
8274     // 3. Check that we do not have a zext in the way.
8275     if (Inst->getValueType(0) != getLoadedType())
8276       return false;
8277
8278     return true;
8279   }
8280 };
8281 }
8282
8283 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8284 /// \p UsedBits looks like 0..0 1..1 0..0.
8285 static bool areUsedBitsDense(const APInt &UsedBits) {
8286   // If all the bits are one, this is dense!
8287   if (UsedBits.isAllOnesValue())
8288     return true;
8289
8290   // Get rid of the unused bits on the right.
8291   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8292   // Get rid of the unused bits on the left.
8293   if (NarrowedUsedBits.countLeadingZeros())
8294     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8295   // Check that the chunk of bits is completely used.
8296   return NarrowedUsedBits.isAllOnesValue();
8297 }
8298
8299 /// \brief Check whether or not \p First and \p Second are next to each other
8300 /// in memory. This means that there is no hole between the bits loaded
8301 /// by \p First and the bits loaded by \p Second.
8302 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8303                                      const LoadedSlice &Second) {
8304   assert(First.Origin == Second.Origin && First.Origin &&
8305          "Unable to match different memory origins.");
8306   APInt UsedBits = First.getUsedBits();
8307   assert((UsedBits & Second.getUsedBits()) == 0 &&
8308          "Slices are not supposed to overlap.");
8309   UsedBits |= Second.getUsedBits();
8310   return areUsedBitsDense(UsedBits);
8311 }
8312
8313 /// \brief Adjust the \p GlobalLSCost according to the target
8314 /// paring capabilities and the layout of the slices.
8315 /// \pre \p GlobalLSCost should account for at least as many loads as
8316 /// there is in the slices in \p LoadedSlices.
8317 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8318                                  LoadedSlice::Cost &GlobalLSCost) {
8319   unsigned NumberOfSlices = LoadedSlices.size();
8320   // If there is less than 2 elements, no pairing is possible.
8321   if (NumberOfSlices < 2)
8322     return;
8323
8324   // Sort the slices so that elements that are likely to be next to each
8325   // other in memory are next to each other in the list.
8326   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8327             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8328     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8329     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8330   });
8331   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8332   // First (resp. Second) is the first (resp. Second) potentially candidate
8333   // to be placed in a paired load.
8334   const LoadedSlice *First = nullptr;
8335   const LoadedSlice *Second = nullptr;
8336   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8337                 // Set the beginning of the pair.
8338                                                            First = Second) {
8339
8340     Second = &LoadedSlices[CurrSlice];
8341
8342     // If First is NULL, it means we start a new pair.
8343     // Get to the next slice.
8344     if (!First)
8345       continue;
8346
8347     EVT LoadedType = First->getLoadedType();
8348
8349     // If the types of the slices are different, we cannot pair them.
8350     if (LoadedType != Second->getLoadedType())
8351       continue;
8352
8353     // Check if the target supplies paired loads for this type.
8354     unsigned RequiredAlignment = 0;
8355     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8356       // move to the next pair, this type is hopeless.
8357       Second = nullptr;
8358       continue;
8359     }
8360     // Check if we meet the alignment requirement.
8361     if (RequiredAlignment > First->getAlignment())
8362       continue;
8363
8364     // Check that both loads are next to each other in memory.
8365     if (!areSlicesNextToEachOther(*First, *Second))
8366       continue;
8367
8368     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8369     --GlobalLSCost.Loads;
8370     // Move to the next pair.
8371     Second = nullptr;
8372   }
8373 }
8374
8375 /// \brief Check the profitability of all involved LoadedSlice.
8376 /// Currently, it is considered profitable if there is exactly two
8377 /// involved slices (1) which are (2) next to each other in memory, and
8378 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8379 ///
8380 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8381 /// the elements themselves.
8382 ///
8383 /// FIXME: When the cost model will be mature enough, we can relax
8384 /// constraints (1) and (2).
8385 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8386                                 const APInt &UsedBits, bool ForCodeSize) {
8387   unsigned NumberOfSlices = LoadedSlices.size();
8388   if (StressLoadSlicing)
8389     return NumberOfSlices > 1;
8390
8391   // Check (1).
8392   if (NumberOfSlices != 2)
8393     return false;
8394
8395   // Check (2).
8396   if (!areUsedBitsDense(UsedBits))
8397     return false;
8398
8399   // Check (3).
8400   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8401   // The original code has one big load.
8402   OrigCost.Loads = 1;
8403   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8404     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8405     // Accumulate the cost of all the slices.
8406     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8407     GlobalSlicingCost += SliceCost;
8408
8409     // Account as cost in the original configuration the gain obtained
8410     // with the current slices.
8411     OrigCost.addSliceGain(LS);
8412   }
8413
8414   // If the target supports paired load, adjust the cost accordingly.
8415   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8416   return OrigCost > GlobalSlicingCost;
8417 }
8418
8419 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8420 /// operations, split it in the various pieces being extracted.
8421 ///
8422 /// This sort of thing is introduced by SROA.
8423 /// This slicing takes care not to insert overlapping loads.
8424 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8425 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8426   if (Level < AfterLegalizeDAG)
8427     return false;
8428
8429   LoadSDNode *LD = cast<LoadSDNode>(N);
8430   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8431       !LD->getValueType(0).isInteger())
8432     return false;
8433
8434   // Keep track of already used bits to detect overlapping values.
8435   // In that case, we will just abort the transformation.
8436   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8437
8438   SmallVector<LoadedSlice, 4> LoadedSlices;
8439
8440   // Check if this load is used as several smaller chunks of bits.
8441   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8442   // of computation for each trunc.
8443   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8444        UI != UIEnd; ++UI) {
8445     // Skip the uses of the chain.
8446     if (UI.getUse().getResNo() != 0)
8447       continue;
8448
8449     SDNode *User = *UI;
8450     unsigned Shift = 0;
8451
8452     // Check if this is a trunc(lshr).
8453     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8454         isa<ConstantSDNode>(User->getOperand(1))) {
8455       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8456       User = *User->use_begin();
8457     }
8458
8459     // At this point, User is a Truncate, iff we encountered, trunc or
8460     // trunc(lshr).
8461     if (User->getOpcode() != ISD::TRUNCATE)
8462       return false;
8463
8464     // The width of the type must be a power of 2 and greater than 8-bits.
8465     // Otherwise the load cannot be represented in LLVM IR.
8466     // Moreover, if we shifted with a non-8-bits multiple, the slice
8467     // will be across several bytes. We do not support that.
8468     unsigned Width = User->getValueSizeInBits(0);
8469     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8470       return 0;
8471
8472     // Build the slice for this chain of computations.
8473     LoadedSlice LS(User, LD, Shift, &DAG);
8474     APInt CurrentUsedBits = LS.getUsedBits();
8475
8476     // Check if this slice overlaps with another.
8477     if ((CurrentUsedBits & UsedBits) != 0)
8478       return false;
8479     // Update the bits used globally.
8480     UsedBits |= CurrentUsedBits;
8481
8482     // Check if the new slice would be legal.
8483     if (!LS.isLegal())
8484       return false;
8485
8486     // Record the slice.
8487     LoadedSlices.push_back(LS);
8488   }
8489
8490   // Abort slicing if it does not seem to be profitable.
8491   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8492     return false;
8493
8494   ++SlicedLoads;
8495
8496   // Rewrite each chain to use an independent load.
8497   // By construction, each chain can be represented by a unique load.
8498
8499   // Prepare the argument for the new token factor for all the slices.
8500   SmallVector<SDValue, 8> ArgChains;
8501   for (SmallVectorImpl<LoadedSlice>::const_iterator
8502            LSIt = LoadedSlices.begin(),
8503            LSItEnd = LoadedSlices.end();
8504        LSIt != LSItEnd; ++LSIt) {
8505     SDValue SliceInst = LSIt->loadSlice();
8506     CombineTo(LSIt->Inst, SliceInst, true);
8507     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8508       SliceInst = SliceInst.getOperand(0);
8509     assert(SliceInst->getOpcode() == ISD::LOAD &&
8510            "It takes more than a zext to get to the loaded slice!!");
8511     ArgChains.push_back(SliceInst.getValue(1));
8512   }
8513
8514   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8515                               &ArgChains[0], ArgChains.size());
8516   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8517   return true;
8518 }
8519
8520 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8521 /// load is having specific bytes cleared out.  If so, return the byte size
8522 /// being masked out and the shift amount.
8523 static std::pair<unsigned, unsigned>
8524 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8525   std::pair<unsigned, unsigned> Result(0, 0);
8526
8527   // Check for the structure we're looking for.
8528   if (V->getOpcode() != ISD::AND ||
8529       !isa<ConstantSDNode>(V->getOperand(1)) ||
8530       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8531     return Result;
8532
8533   // Check the chain and pointer.
8534   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8535   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8536
8537   // The store should be chained directly to the load or be an operand of a
8538   // tokenfactor.
8539   if (LD == Chain.getNode())
8540     ; // ok.
8541   else if (Chain->getOpcode() != ISD::TokenFactor)
8542     return Result; // Fail.
8543   else {
8544     bool isOk = false;
8545     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8546       if (Chain->getOperand(i).getNode() == LD) {
8547         isOk = true;
8548         break;
8549       }
8550     if (!isOk) return Result;
8551   }
8552
8553   // This only handles simple types.
8554   if (V.getValueType() != MVT::i16 &&
8555       V.getValueType() != MVT::i32 &&
8556       V.getValueType() != MVT::i64)
8557     return Result;
8558
8559   // Check the constant mask.  Invert it so that the bits being masked out are
8560   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8561   // follow the sign bit for uniformity.
8562   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8563   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8564   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8565   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8566   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8567   if (NotMaskLZ == 64) return Result;  // All zero mask.
8568
8569   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8570   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8571     return Result;
8572
8573   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8574   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8575     NotMaskLZ -= 64-V.getValueSizeInBits();
8576
8577   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8578   switch (MaskedBytes) {
8579   case 1:
8580   case 2:
8581   case 4: break;
8582   default: return Result; // All one mask, or 5-byte mask.
8583   }
8584
8585   // Verify that the first bit starts at a multiple of mask so that the access
8586   // is aligned the same as the access width.
8587   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8588
8589   Result.first = MaskedBytes;
8590   Result.second = NotMaskTZ/8;
8591   return Result;
8592 }
8593
8594
8595 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8596 /// provides a value as specified by MaskInfo.  If so, replace the specified
8597 /// store with a narrower store of truncated IVal.
8598 static SDNode *
8599 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8600                                 SDValue IVal, StoreSDNode *St,
8601                                 DAGCombiner *DC) {
8602   unsigned NumBytes = MaskInfo.first;
8603   unsigned ByteShift = MaskInfo.second;
8604   SelectionDAG &DAG = DC->getDAG();
8605
8606   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8607   // that uses this.  If not, this is not a replacement.
8608   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8609                                   ByteShift*8, (ByteShift+NumBytes)*8);
8610   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8611
8612   // Check that it is legal on the target to do this.  It is legal if the new
8613   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8614   // legalization.
8615   MVT VT = MVT::getIntegerVT(NumBytes*8);
8616   if (!DC->isTypeLegal(VT))
8617     return nullptr;
8618
8619   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8620   // shifted by ByteShift and truncated down to NumBytes.
8621   if (ByteShift)
8622     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8623                        DAG.getConstant(ByteShift*8,
8624                                     DC->getShiftAmountTy(IVal.getValueType())));
8625
8626   // Figure out the offset for the store and the alignment of the access.
8627   unsigned StOffset;
8628   unsigned NewAlign = St->getAlignment();
8629
8630   if (DAG.getTargetLoweringInfo().isLittleEndian())
8631     StOffset = ByteShift;
8632   else
8633     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8634
8635   SDValue Ptr = St->getBasePtr();
8636   if (StOffset) {
8637     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8638                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8639     NewAlign = MinAlign(NewAlign, StOffset);
8640   }
8641
8642   // Truncate down to the new size.
8643   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8644
8645   ++OpsNarrowed;
8646   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8647                       St->getPointerInfo().getWithOffset(StOffset),
8648                       false, false, NewAlign).getNode();
8649 }
8650
8651
8652 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8653 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8654 /// of the loaded bits, try narrowing the load and store if it would end up
8655 /// being a win for performance or code size.
8656 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8657   StoreSDNode *ST  = cast<StoreSDNode>(N);
8658   if (ST->isVolatile())
8659     return SDValue();
8660
8661   SDValue Chain = ST->getChain();
8662   SDValue Value = ST->getValue();
8663   SDValue Ptr   = ST->getBasePtr();
8664   EVT VT = Value.getValueType();
8665
8666   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8667     return SDValue();
8668
8669   unsigned Opc = Value.getOpcode();
8670
8671   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8672   // is a byte mask indicating a consecutive number of bytes, check to see if
8673   // Y is known to provide just those bytes.  If so, we try to replace the
8674   // load + replace + store sequence with a single (narrower) store, which makes
8675   // the load dead.
8676   if (Opc == ISD::OR) {
8677     std::pair<unsigned, unsigned> MaskedLoad;
8678     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8679     if (MaskedLoad.first)
8680       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8681                                                   Value.getOperand(1), ST,this))
8682         return SDValue(NewST, 0);
8683
8684     // Or is commutative, so try swapping X and Y.
8685     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8686     if (MaskedLoad.first)
8687       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8688                                                   Value.getOperand(0), ST,this))
8689         return SDValue(NewST, 0);
8690   }
8691
8692   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8693       Value.getOperand(1).getOpcode() != ISD::Constant)
8694     return SDValue();
8695
8696   SDValue N0 = Value.getOperand(0);
8697   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8698       Chain == SDValue(N0.getNode(), 1)) {
8699     LoadSDNode *LD = cast<LoadSDNode>(N0);
8700     if (LD->getBasePtr() != Ptr ||
8701         LD->getPointerInfo().getAddrSpace() !=
8702         ST->getPointerInfo().getAddrSpace())
8703       return SDValue();
8704
8705     // Find the type to narrow it the load / op / store to.
8706     SDValue N1 = Value.getOperand(1);
8707     unsigned BitWidth = N1.getValueSizeInBits();
8708     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8709     if (Opc == ISD::AND)
8710       Imm ^= APInt::getAllOnesValue(BitWidth);
8711     if (Imm == 0 || Imm.isAllOnesValue())
8712       return SDValue();
8713     unsigned ShAmt = Imm.countTrailingZeros();
8714     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8715     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8716     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8717     while (NewBW < BitWidth &&
8718            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8719              TLI.isNarrowingProfitable(VT, NewVT))) {
8720       NewBW = NextPowerOf2(NewBW);
8721       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8722     }
8723     if (NewBW >= BitWidth)
8724       return SDValue();
8725
8726     // If the lsb changed does not start at the type bitwidth boundary,
8727     // start at the previous one.
8728     if (ShAmt % NewBW)
8729       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8730     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8731                                    std::min(BitWidth, ShAmt + NewBW));
8732     if ((Imm & Mask) == Imm) {
8733       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8734       if (Opc == ISD::AND)
8735         NewImm ^= APInt::getAllOnesValue(NewBW);
8736       uint64_t PtrOff = ShAmt / 8;
8737       // For big endian targets, we need to adjust the offset to the pointer to
8738       // load the correct bytes.
8739       if (TLI.isBigEndian())
8740         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8741
8742       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8743       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8744       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8745         return SDValue();
8746
8747       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8748                                    Ptr.getValueType(), Ptr,
8749                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8750       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8751                                   LD->getChain(), NewPtr,
8752                                   LD->getPointerInfo().getWithOffset(PtrOff),
8753                                   LD->isVolatile(), LD->isNonTemporal(),
8754                                   LD->isInvariant(), NewAlign,
8755                                   LD->getTBAAInfo());
8756       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8757                                    DAG.getConstant(NewImm, NewVT));
8758       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8759                                    NewVal, NewPtr,
8760                                    ST->getPointerInfo().getWithOffset(PtrOff),
8761                                    false, false, NewAlign);
8762
8763       AddToWorkList(NewPtr.getNode());
8764       AddToWorkList(NewLD.getNode());
8765       AddToWorkList(NewVal.getNode());
8766       WorkListRemover DeadNodes(*this);
8767       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8768       ++OpsNarrowed;
8769       return NewST;
8770     }
8771   }
8772
8773   return SDValue();
8774 }
8775
8776 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8777 /// if the load value isn't used by any other operations, then consider
8778 /// transforming the pair to integer load / store operations if the target
8779 /// deems the transformation profitable.
8780 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8781   StoreSDNode *ST  = cast<StoreSDNode>(N);
8782   SDValue Chain = ST->getChain();
8783   SDValue Value = ST->getValue();
8784   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8785       Value.hasOneUse() &&
8786       Chain == SDValue(Value.getNode(), 1)) {
8787     LoadSDNode *LD = cast<LoadSDNode>(Value);
8788     EVT VT = LD->getMemoryVT();
8789     if (!VT.isFloatingPoint() ||
8790         VT != ST->getMemoryVT() ||
8791         LD->isNonTemporal() ||
8792         ST->isNonTemporal() ||
8793         LD->getPointerInfo().getAddrSpace() != 0 ||
8794         ST->getPointerInfo().getAddrSpace() != 0)
8795       return SDValue();
8796
8797     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8798     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8799         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8800         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8801         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8802       return SDValue();
8803
8804     unsigned LDAlign = LD->getAlignment();
8805     unsigned STAlign = ST->getAlignment();
8806     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8807     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8808     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8809       return SDValue();
8810
8811     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8812                                 LD->getChain(), LD->getBasePtr(),
8813                                 LD->getPointerInfo(),
8814                                 false, false, false, LDAlign);
8815
8816     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8817                                  NewLD, ST->getBasePtr(),
8818                                  ST->getPointerInfo(),
8819                                  false, false, STAlign);
8820
8821     AddToWorkList(NewLD.getNode());
8822     AddToWorkList(NewST.getNode());
8823     WorkListRemover DeadNodes(*this);
8824     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8825     ++LdStFP2Int;
8826     return NewST;
8827   }
8828
8829   return SDValue();
8830 }
8831
8832 /// Helper struct to parse and store a memory address as base + index + offset.
8833 /// We ignore sign extensions when it is safe to do so.
8834 /// The following two expressions are not equivalent. To differentiate we need
8835 /// to store whether there was a sign extension involved in the index
8836 /// computation.
8837 ///  (load (i64 add (i64 copyfromreg %c)
8838 ///                 (i64 signextend (add (i8 load %index)
8839 ///                                      (i8 1))))
8840 /// vs
8841 ///
8842 /// (load (i64 add (i64 copyfromreg %c)
8843 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8844 ///                                         (i32 1)))))
8845 struct BaseIndexOffset {
8846   SDValue Base;
8847   SDValue Index;
8848   int64_t Offset;
8849   bool IsIndexSignExt;
8850
8851   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8852
8853   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8854                   bool IsIndexSignExt) :
8855     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8856
8857   bool equalBaseIndex(const BaseIndexOffset &Other) {
8858     return Other.Base == Base && Other.Index == Index &&
8859       Other.IsIndexSignExt == IsIndexSignExt;
8860   }
8861
8862   /// Parses tree in Ptr for base, index, offset addresses.
8863   static BaseIndexOffset match(SDValue Ptr) {
8864     bool IsIndexSignExt = false;
8865
8866     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8867     // instruction, then it could be just the BASE or everything else we don't
8868     // know how to handle. Just use Ptr as BASE and give up.
8869     if (Ptr->getOpcode() != ISD::ADD)
8870       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8871
8872     // We know that we have at least an ADD instruction. Try to pattern match
8873     // the simple case of BASE + OFFSET.
8874     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8875       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8876       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8877                               IsIndexSignExt);
8878     }
8879
8880     // Inside a loop the current BASE pointer is calculated using an ADD and a
8881     // MUL instruction. In this case Ptr is the actual BASE pointer.
8882     // (i64 add (i64 %array_ptr)
8883     //          (i64 mul (i64 %induction_var)
8884     //                   (i64 %element_size)))
8885     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8886       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8887
8888     // Look at Base + Index + Offset cases.
8889     SDValue Base = Ptr->getOperand(0);
8890     SDValue IndexOffset = Ptr->getOperand(1);
8891
8892     // Skip signextends.
8893     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8894       IndexOffset = IndexOffset->getOperand(0);
8895       IsIndexSignExt = true;
8896     }
8897
8898     // Either the case of Base + Index (no offset) or something else.
8899     if (IndexOffset->getOpcode() != ISD::ADD)
8900       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8901
8902     // Now we have the case of Base + Index + offset.
8903     SDValue Index = IndexOffset->getOperand(0);
8904     SDValue Offset = IndexOffset->getOperand(1);
8905
8906     if (!isa<ConstantSDNode>(Offset))
8907       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8908
8909     // Ignore signextends.
8910     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8911       Index = Index->getOperand(0);
8912       IsIndexSignExt = true;
8913     } else IsIndexSignExt = false;
8914
8915     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8916     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8917   }
8918 };
8919
8920 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8921 /// is located in a sequence of memory operations connected by a chain.
8922 struct MemOpLink {
8923   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8924     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8925   // Ptr to the mem node.
8926   LSBaseSDNode *MemNode;
8927   // Offset from the base ptr.
8928   int64_t OffsetFromBase;
8929   // What is the sequence number of this mem node.
8930   // Lowest mem operand in the DAG starts at zero.
8931   unsigned SequenceNum;
8932 };
8933
8934 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8935   EVT MemVT = St->getMemoryVT();
8936   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8937   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8938     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8939
8940   // Don't merge vectors into wider inputs.
8941   if (MemVT.isVector() || !MemVT.isSimple())
8942     return false;
8943
8944   // Perform an early exit check. Do not bother looking at stored values that
8945   // are not constants or loads.
8946   SDValue StoredVal = St->getValue();
8947   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8948   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8949       !IsLoadSrc)
8950     return false;
8951
8952   // Only look at ends of store sequences.
8953   SDValue Chain = SDValue(St, 1);
8954   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8955     return false;
8956
8957   // This holds the base pointer, index, and the offset in bytes from the base
8958   // pointer.
8959   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8960
8961   // We must have a base and an offset.
8962   if (!BasePtr.Base.getNode())
8963     return false;
8964
8965   // Do not handle stores to undef base pointers.
8966   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8967     return false;
8968
8969   // Save the LoadSDNodes that we find in the chain.
8970   // We need to make sure that these nodes do not interfere with
8971   // any of the store nodes.
8972   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8973
8974   // Save the StoreSDNodes that we find in the chain.
8975   SmallVector<MemOpLink, 8> StoreNodes;
8976
8977   // Walk up the chain and look for nodes with offsets from the same
8978   // base pointer. Stop when reaching an instruction with a different kind
8979   // or instruction which has a different base pointer.
8980   unsigned Seq = 0;
8981   StoreSDNode *Index = St;
8982   while (Index) {
8983     // If the chain has more than one use, then we can't reorder the mem ops.
8984     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8985       break;
8986
8987     // Find the base pointer and offset for this memory node.
8988     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8989
8990     // Check that the base pointer is the same as the original one.
8991     if (!Ptr.equalBaseIndex(BasePtr))
8992       break;
8993
8994     // Check that the alignment is the same.
8995     if (Index->getAlignment() != St->getAlignment())
8996       break;
8997
8998     // The memory operands must not be volatile.
8999     if (Index->isVolatile() || Index->isIndexed())
9000       break;
9001
9002     // No truncation.
9003     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9004       if (St->isTruncatingStore())
9005         break;
9006
9007     // The stored memory type must be the same.
9008     if (Index->getMemoryVT() != MemVT)
9009       break;
9010
9011     // We do not allow unaligned stores because we want to prevent overriding
9012     // stores.
9013     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9014       break;
9015
9016     // We found a potential memory operand to merge.
9017     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9018
9019     // Find the next memory operand in the chain. If the next operand in the
9020     // chain is a store then move up and continue the scan with the next
9021     // memory operand. If the next operand is a load save it and use alias
9022     // information to check if it interferes with anything.
9023     SDNode *NextInChain = Index->getChain().getNode();
9024     while (1) {
9025       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9026         // We found a store node. Use it for the next iteration.
9027         Index = STn;
9028         break;
9029       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9030         if (Ldn->isVolatile()) {
9031           Index = nullptr;
9032           break;
9033         }
9034
9035         // Save the load node for later. Continue the scan.
9036         AliasLoadNodes.push_back(Ldn);
9037         NextInChain = Ldn->getChain().getNode();
9038         continue;
9039       } else {
9040         Index = nullptr;
9041         break;
9042       }
9043     }
9044   }
9045
9046   // Check if there is anything to merge.
9047   if (StoreNodes.size() < 2)
9048     return false;
9049
9050   // Sort the memory operands according to their distance from the base pointer.
9051   std::sort(StoreNodes.begin(), StoreNodes.end(),
9052             [](MemOpLink LHS, MemOpLink RHS) {
9053     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9054            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9055             LHS.SequenceNum > RHS.SequenceNum);
9056   });
9057
9058   // Scan the memory operations on the chain and find the first non-consecutive
9059   // store memory address.
9060   unsigned LastConsecutiveStore = 0;
9061   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9062   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9063
9064     // Check that the addresses are consecutive starting from the second
9065     // element in the list of stores.
9066     if (i > 0) {
9067       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9068       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9069         break;
9070     }
9071
9072     bool Alias = false;
9073     // Check if this store interferes with any of the loads that we found.
9074     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9075       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9076         Alias = true;
9077         break;
9078       }
9079     // We found a load that alias with this store. Stop the sequence.
9080     if (Alias)
9081       break;
9082
9083     // Mark this node as useful.
9084     LastConsecutiveStore = i;
9085   }
9086
9087   // The node with the lowest store address.
9088   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9089
9090   // Store the constants into memory as one consecutive store.
9091   if (!IsLoadSrc) {
9092     unsigned LastLegalType = 0;
9093     unsigned LastLegalVectorType = 0;
9094     bool NonZero = false;
9095     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9096       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9097       SDValue StoredVal = St->getValue();
9098
9099       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9100         NonZero |= !C->isNullValue();
9101       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9102         NonZero |= !C->getConstantFPValue()->isNullValue();
9103       } else {
9104         // Non-constant.
9105         break;
9106       }
9107
9108       // Find a legal type for the constant store.
9109       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9110       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9111       if (TLI.isTypeLegal(StoreTy))
9112         LastLegalType = i+1;
9113       // Or check whether a truncstore is legal.
9114       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9115                TargetLowering::TypePromoteInteger) {
9116         EVT LegalizedStoredValueTy =
9117           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9118         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9119           LastLegalType = i+1;
9120       }
9121
9122       // Find a legal type for the vector store.
9123       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9124       if (TLI.isTypeLegal(Ty))
9125         LastLegalVectorType = i + 1;
9126     }
9127
9128     // We only use vectors if the constant is known to be zero and the
9129     // function is not marked with the noimplicitfloat attribute.
9130     if (NonZero || NoVectors)
9131       LastLegalVectorType = 0;
9132
9133     // Check if we found a legal integer type to store.
9134     if (LastLegalType == 0 && LastLegalVectorType == 0)
9135       return false;
9136
9137     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9138     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9139
9140     // Make sure we have something to merge.
9141     if (NumElem < 2)
9142       return false;
9143
9144     unsigned EarliestNodeUsed = 0;
9145     for (unsigned i=0; i < NumElem; ++i) {
9146       // Find a chain for the new wide-store operand. Notice that some
9147       // of the store nodes that we found may not be selected for inclusion
9148       // in the wide store. The chain we use needs to be the chain of the
9149       // earliest store node which is *used* and replaced by the wide store.
9150       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9151         EarliestNodeUsed = i;
9152     }
9153
9154     // The earliest Node in the DAG.
9155     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9156     SDLoc DL(StoreNodes[0].MemNode);
9157
9158     SDValue StoredVal;
9159     if (UseVector) {
9160       // Find a legal type for the vector store.
9161       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9162       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9163       StoredVal = DAG.getConstant(0, Ty);
9164     } else {
9165       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9166       APInt StoreInt(StoreBW, 0);
9167
9168       // Construct a single integer constant which is made of the smaller
9169       // constant inputs.
9170       bool IsLE = TLI.isLittleEndian();
9171       for (unsigned i = 0; i < NumElem ; ++i) {
9172         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9173         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9174         SDValue Val = St->getValue();
9175         StoreInt<<=ElementSizeBytes*8;
9176         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9177           StoreInt|=C->getAPIntValue().zext(StoreBW);
9178         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9179           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9180         } else {
9181           assert(false && "Invalid constant element type");
9182         }
9183       }
9184
9185       // Create the new Load and Store operations.
9186       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9187       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9188     }
9189
9190     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9191                                     FirstInChain->getBasePtr(),
9192                                     FirstInChain->getPointerInfo(),
9193                                     false, false,
9194                                     FirstInChain->getAlignment());
9195
9196     // Replace the first store with the new store
9197     CombineTo(EarliestOp, NewStore);
9198     // Erase all other stores.
9199     for (unsigned i = 0; i < NumElem ; ++i) {
9200       if (StoreNodes[i].MemNode == EarliestOp)
9201         continue;
9202       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9203       // ReplaceAllUsesWith will replace all uses that existed when it was
9204       // called, but graph optimizations may cause new ones to appear. For
9205       // example, the case in pr14333 looks like
9206       //
9207       //  St's chain -> St -> another store -> X
9208       //
9209       // And the only difference from St to the other store is the chain.
9210       // When we change it's chain to be St's chain they become identical,
9211       // get CSEed and the net result is that X is now a use of St.
9212       // Since we know that St is redundant, just iterate.
9213       while (!St->use_empty())
9214         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9215       removeFromWorkList(St);
9216       DAG.DeleteNode(St);
9217     }
9218
9219     return true;
9220   }
9221
9222   // Below we handle the case of multiple consecutive stores that
9223   // come from multiple consecutive loads. We merge them into a single
9224   // wide load and a single wide store.
9225
9226   // Look for load nodes which are used by the stored values.
9227   SmallVector<MemOpLink, 8> LoadNodes;
9228
9229   // Find acceptable loads. Loads need to have the same chain (token factor),
9230   // must not be zext, volatile, indexed, and they must be consecutive.
9231   BaseIndexOffset LdBasePtr;
9232   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9233     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9234     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9235     if (!Ld) break;
9236
9237     // Loads must only have one use.
9238     if (!Ld->hasNUsesOfValue(1, 0))
9239       break;
9240
9241     // Check that the alignment is the same as the stores.
9242     if (Ld->getAlignment() != St->getAlignment())
9243       break;
9244
9245     // The memory operands must not be volatile.
9246     if (Ld->isVolatile() || Ld->isIndexed())
9247       break;
9248
9249     // We do not accept ext loads.
9250     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9251       break;
9252
9253     // The stored memory type must be the same.
9254     if (Ld->getMemoryVT() != MemVT)
9255       break;
9256
9257     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9258     // If this is not the first ptr that we check.
9259     if (LdBasePtr.Base.getNode()) {
9260       // The base ptr must be the same.
9261       if (!LdPtr.equalBaseIndex(LdBasePtr))
9262         break;
9263     } else {
9264       // Check that all other base pointers are the same as this one.
9265       LdBasePtr = LdPtr;
9266     }
9267
9268     // We found a potential memory operand to merge.
9269     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9270   }
9271
9272   if (LoadNodes.size() < 2)
9273     return false;
9274
9275   // Scan the memory operations on the chain and find the first non-consecutive
9276   // load memory address. These variables hold the index in the store node
9277   // array.
9278   unsigned LastConsecutiveLoad = 0;
9279   // This variable refers to the size and not index in the array.
9280   unsigned LastLegalVectorType = 0;
9281   unsigned LastLegalIntegerType = 0;
9282   StartAddress = LoadNodes[0].OffsetFromBase;
9283   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9284   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9285     // All loads much share the same chain.
9286     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9287       break;
9288
9289     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9290     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9291       break;
9292     LastConsecutiveLoad = i;
9293
9294     // Find a legal type for the vector store.
9295     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9296     if (TLI.isTypeLegal(StoreTy))
9297       LastLegalVectorType = i + 1;
9298
9299     // Find a legal type for the integer store.
9300     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9301     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9302     if (TLI.isTypeLegal(StoreTy))
9303       LastLegalIntegerType = i + 1;
9304     // Or check whether a truncstore and extload is legal.
9305     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9306              TargetLowering::TypePromoteInteger) {
9307       EVT LegalizedStoredValueTy =
9308         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9309       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9310           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9311           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9312           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9313         LastLegalIntegerType = i+1;
9314     }
9315   }
9316
9317   // Only use vector types if the vector type is larger than the integer type.
9318   // If they are the same, use integers.
9319   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9320   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9321
9322   // We add +1 here because the LastXXX variables refer to location while
9323   // the NumElem refers to array/index size.
9324   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9325   NumElem = std::min(LastLegalType, NumElem);
9326
9327   if (NumElem < 2)
9328     return false;
9329
9330   // The earliest Node in the DAG.
9331   unsigned EarliestNodeUsed = 0;
9332   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9333   for (unsigned i=1; i<NumElem; ++i) {
9334     // Find a chain for the new wide-store operand. Notice that some
9335     // of the store nodes that we found may not be selected for inclusion
9336     // in the wide store. The chain we use needs to be the chain of the
9337     // earliest store node which is *used* and replaced by the wide store.
9338     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9339       EarliestNodeUsed = i;
9340   }
9341
9342   // Find if it is better to use vectors or integers to load and store
9343   // to memory.
9344   EVT JointMemOpVT;
9345   if (UseVectorTy) {
9346     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9347   } else {
9348     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9349     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9350   }
9351
9352   SDLoc LoadDL(LoadNodes[0].MemNode);
9353   SDLoc StoreDL(StoreNodes[0].MemNode);
9354
9355   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9356   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9357                                 FirstLoad->getChain(),
9358                                 FirstLoad->getBasePtr(),
9359                                 FirstLoad->getPointerInfo(),
9360                                 false, false, false,
9361                                 FirstLoad->getAlignment());
9362
9363   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9364                                   FirstInChain->getBasePtr(),
9365                                   FirstInChain->getPointerInfo(), false, false,
9366                                   FirstInChain->getAlignment());
9367
9368   // Replace one of the loads with the new load.
9369   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9370   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9371                                 SDValue(NewLoad.getNode(), 1));
9372
9373   // Remove the rest of the load chains.
9374   for (unsigned i = 1; i < NumElem ; ++i) {
9375     // Replace all chain users of the old load nodes with the chain of the new
9376     // load node.
9377     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9378     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9379   }
9380
9381   // Replace the first store with the new store.
9382   CombineTo(EarliestOp, NewStore);
9383   // Erase all other stores.
9384   for (unsigned i = 0; i < NumElem ; ++i) {
9385     // Remove all Store nodes.
9386     if (StoreNodes[i].MemNode == EarliestOp)
9387       continue;
9388     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9389     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9390     removeFromWorkList(St);
9391     DAG.DeleteNode(St);
9392   }
9393
9394   return true;
9395 }
9396
9397 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9398   StoreSDNode *ST  = cast<StoreSDNode>(N);
9399   SDValue Chain = ST->getChain();
9400   SDValue Value = ST->getValue();
9401   SDValue Ptr   = ST->getBasePtr();
9402
9403   // If this is a store of a bit convert, store the input value if the
9404   // resultant store does not need a higher alignment than the original.
9405   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9406       ST->isUnindexed()) {
9407     unsigned OrigAlign = ST->getAlignment();
9408     EVT SVT = Value.getOperand(0).getValueType();
9409     unsigned Align = TLI.getDataLayout()->
9410       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9411     if (Align <= OrigAlign &&
9412         ((!LegalOperations && !ST->isVolatile()) ||
9413          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9414       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9415                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9416                           ST->isNonTemporal(), OrigAlign,
9417                           ST->getTBAAInfo());
9418   }
9419
9420   // Turn 'store undef, Ptr' -> nothing.
9421   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9422     return Chain;
9423
9424   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9425   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9426     // NOTE: If the original store is volatile, this transform must not increase
9427     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9428     // processor operation but an i64 (which is not legal) requires two.  So the
9429     // transform should not be done in this case.
9430     if (Value.getOpcode() != ISD::TargetConstantFP) {
9431       SDValue Tmp;
9432       switch (CFP->getSimpleValueType(0).SimpleTy) {
9433       default: llvm_unreachable("Unknown FP type");
9434       case MVT::f16:    // We don't do this for these yet.
9435       case MVT::f80:
9436       case MVT::f128:
9437       case MVT::ppcf128:
9438         break;
9439       case MVT::f32:
9440         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9441             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9442           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9443                               bitcastToAPInt().getZExtValue(), MVT::i32);
9444           return DAG.getStore(Chain, SDLoc(N), Tmp,
9445                               Ptr, ST->getMemOperand());
9446         }
9447         break;
9448       case MVT::f64:
9449         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9450              !ST->isVolatile()) ||
9451             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9452           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9453                                 getZExtValue(), MVT::i64);
9454           return DAG.getStore(Chain, SDLoc(N), Tmp,
9455                               Ptr, ST->getMemOperand());
9456         }
9457
9458         if (!ST->isVolatile() &&
9459             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9460           // Many FP stores are not made apparent until after legalize, e.g. for
9461           // argument passing.  Since this is so common, custom legalize the
9462           // 64-bit integer store into two 32-bit stores.
9463           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9464           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9465           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9466           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9467
9468           unsigned Alignment = ST->getAlignment();
9469           bool isVolatile = ST->isVolatile();
9470           bool isNonTemporal = ST->isNonTemporal();
9471           const MDNode *TBAAInfo = ST->getTBAAInfo();
9472
9473           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9474                                      Ptr, ST->getPointerInfo(),
9475                                      isVolatile, isNonTemporal,
9476                                      ST->getAlignment(), TBAAInfo);
9477           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9478                             DAG.getConstant(4, Ptr.getValueType()));
9479           Alignment = MinAlign(Alignment, 4U);
9480           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9481                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9482                                      isVolatile, isNonTemporal,
9483                                      Alignment, TBAAInfo);
9484           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9485                              St0, St1);
9486         }
9487
9488         break;
9489       }
9490     }
9491   }
9492
9493   // Try to infer better alignment information than the store already has.
9494   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9495     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9496       if (Align > ST->getAlignment())
9497         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9498                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9499                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9500                                  ST->getTBAAInfo());
9501     }
9502   }
9503
9504   // Try transforming a pair floating point load / store ops to integer
9505   // load / store ops.
9506   SDValue NewST = TransformFPLoadStorePair(N);
9507   if (NewST.getNode())
9508     return NewST;
9509
9510   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9511     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9512 #ifndef NDEBUG
9513   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9514       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9515     UseAA = false;
9516 #endif
9517   if (UseAA && ST->isUnindexed()) {
9518     // Walk up chain skipping non-aliasing memory nodes.
9519     SDValue BetterChain = FindBetterChain(N, Chain);
9520
9521     // If there is a better chain.
9522     if (Chain != BetterChain) {
9523       SDValue ReplStore;
9524
9525       // Replace the chain to avoid dependency.
9526       if (ST->isTruncatingStore()) {
9527         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9528                                       ST->getMemoryVT(), ST->getMemOperand());
9529       } else {
9530         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9531                                  ST->getMemOperand());
9532       }
9533
9534       // Create token to keep both nodes around.
9535       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9536                                   MVT::Other, Chain, ReplStore);
9537
9538       // Make sure the new and old chains are cleaned up.
9539       AddToWorkList(Token.getNode());
9540
9541       // Don't add users to work list.
9542       return CombineTo(N, Token, false);
9543     }
9544   }
9545
9546   // Try transforming N to an indexed store.
9547   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9548     return SDValue(N, 0);
9549
9550   // FIXME: is there such a thing as a truncating indexed store?
9551   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9552       Value.getValueType().isInteger()) {
9553     // See if we can simplify the input to this truncstore with knowledge that
9554     // only the low bits are being used.  For example:
9555     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9556     SDValue Shorter =
9557       GetDemandedBits(Value,
9558                       APInt::getLowBitsSet(
9559                         Value.getValueType().getScalarType().getSizeInBits(),
9560                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9561     AddToWorkList(Value.getNode());
9562     if (Shorter.getNode())
9563       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9564                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9565
9566     // Otherwise, see if we can simplify the operation with
9567     // SimplifyDemandedBits, which only works if the value has a single use.
9568     if (SimplifyDemandedBits(Value,
9569                         APInt::getLowBitsSet(
9570                           Value.getValueType().getScalarType().getSizeInBits(),
9571                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9572       return SDValue(N, 0);
9573   }
9574
9575   // If this is a load followed by a store to the same location, then the store
9576   // is dead/noop.
9577   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9578     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9579         ST->isUnindexed() && !ST->isVolatile() &&
9580         // There can't be any side effects between the load and store, such as
9581         // a call or store.
9582         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9583       // The store is dead, remove it.
9584       return Chain;
9585     }
9586   }
9587
9588   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9589   // truncating store.  We can do this even if this is already a truncstore.
9590   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9591       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9592       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9593                             ST->getMemoryVT())) {
9594     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9595                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9596   }
9597
9598   // Only perform this optimization before the types are legal, because we
9599   // don't want to perform this optimization on every DAGCombine invocation.
9600   if (!LegalTypes) {
9601     bool EverChanged = false;
9602
9603     do {
9604       // There can be multiple store sequences on the same chain.
9605       // Keep trying to merge store sequences until we are unable to do so
9606       // or until we merge the last store on the chain.
9607       bool Changed = MergeConsecutiveStores(ST);
9608       EverChanged |= Changed;
9609       if (!Changed) break;
9610     } while (ST->getOpcode() != ISD::DELETED_NODE);
9611
9612     if (EverChanged)
9613       return SDValue(N, 0);
9614   }
9615
9616   return ReduceLoadOpStoreWidth(N);
9617 }
9618
9619 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9620   SDValue InVec = N->getOperand(0);
9621   SDValue InVal = N->getOperand(1);
9622   SDValue EltNo = N->getOperand(2);
9623   SDLoc dl(N);
9624
9625   // If the inserted element is an UNDEF, just use the input vector.
9626   if (InVal.getOpcode() == ISD::UNDEF)
9627     return InVec;
9628
9629   EVT VT = InVec.getValueType();
9630
9631   // If we can't generate a legal BUILD_VECTOR, exit
9632   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9633     return SDValue();
9634
9635   // Check that we know which element is being inserted
9636   if (!isa<ConstantSDNode>(EltNo))
9637     return SDValue();
9638   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9639
9640   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9641   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9642   // vector elements.
9643   SmallVector<SDValue, 8> Ops;
9644   // Do not combine these two vectors if the output vector will not replace
9645   // the input vector.
9646   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9647     Ops.append(InVec.getNode()->op_begin(),
9648                InVec.getNode()->op_end());
9649   } else if (InVec.getOpcode() == ISD::UNDEF) {
9650     unsigned NElts = VT.getVectorNumElements();
9651     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9652   } else {
9653     return SDValue();
9654   }
9655
9656   // Insert the element
9657   if (Elt < Ops.size()) {
9658     // All the operands of BUILD_VECTOR must have the same type;
9659     // we enforce that here.
9660     EVT OpVT = Ops[0].getValueType();
9661     if (InVal.getValueType() != OpVT)
9662       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9663                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9664                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9665     Ops[Elt] = InVal;
9666   }
9667
9668   // Return the new vector
9669   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9670                      VT, &Ops[0], Ops.size());
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[0], Ops.size());
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,
10071                            &Opnds[0], Opnds.size());
10072   AddToWorkList(BV.getNode());
10073
10074   return DAG.getNode(Opcode, dl, VT, BV);
10075 }
10076
10077 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10078   unsigned NumInScalars = N->getNumOperands();
10079   SDLoc dl(N);
10080   EVT VT = N->getValueType(0);
10081
10082   // A vector built entirely of undefs is undef.
10083   if (ISD::allOperandsUndef(N))
10084     return DAG.getUNDEF(VT);
10085
10086   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10087   if (V.getNode())
10088     return V;
10089
10090   V = reduceBuildVecConvertToConvertBuildVec(N);
10091   if (V.getNode())
10092     return V;
10093
10094   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10095   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10096   // at most two distinct vectors, turn this into a shuffle node.
10097
10098   // May only combine to shuffle after legalize if shuffle is legal.
10099   if (LegalOperations &&
10100       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10101     return SDValue();
10102
10103   SDValue VecIn1, VecIn2;
10104   for (unsigned i = 0; i != NumInScalars; ++i) {
10105     // Ignore undef inputs.
10106     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10107
10108     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10109     // constant index, bail out.
10110     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10111         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10112       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10113       break;
10114     }
10115
10116     // We allow up to two distinct input vectors.
10117     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10118     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10119       continue;
10120
10121     if (!VecIn1.getNode()) {
10122       VecIn1 = ExtractedFromVec;
10123     } else if (!VecIn2.getNode()) {
10124       VecIn2 = ExtractedFromVec;
10125     } else {
10126       // Too many inputs.
10127       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10128       break;
10129     }
10130   }
10131
10132     // If everything is good, we can make a shuffle operation.
10133   if (VecIn1.getNode()) {
10134     SmallVector<int, 8> Mask;
10135     for (unsigned i = 0; i != NumInScalars; ++i) {
10136       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10137         Mask.push_back(-1);
10138         continue;
10139       }
10140
10141       // If extracting from the first vector, just use the index directly.
10142       SDValue Extract = N->getOperand(i);
10143       SDValue ExtVal = Extract.getOperand(1);
10144       if (Extract.getOperand(0) == VecIn1) {
10145         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10146         if (ExtIndex > VT.getVectorNumElements())
10147           return SDValue();
10148
10149         Mask.push_back(ExtIndex);
10150         continue;
10151       }
10152
10153       // Otherwise, use InIdx + VecSize
10154       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10155       Mask.push_back(Idx+NumInScalars);
10156     }
10157
10158     // We can't generate a shuffle node with mismatched input and output types.
10159     // Attempt to transform a single input vector to the correct type.
10160     if ((VT != VecIn1.getValueType())) {
10161       // We don't support shuffeling between TWO values of different types.
10162       if (VecIn2.getNode())
10163         return SDValue();
10164
10165       // We only support widening of vectors which are half the size of the
10166       // output registers. For example XMM->YMM widening on X86 with AVX.
10167       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10168         return SDValue();
10169
10170       // If the input vector type has a different base type to the output
10171       // vector type, bail out.
10172       if (VecIn1.getValueType().getVectorElementType() !=
10173           VT.getVectorElementType())
10174         return SDValue();
10175
10176       // Widen the input vector by adding undef values.
10177       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10178                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10179     }
10180
10181     // If VecIn2 is unused then change it to undef.
10182     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10183
10184     // Check that we were able to transform all incoming values to the same
10185     // type.
10186     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10187         VecIn1.getValueType() != VT)
10188           return SDValue();
10189
10190     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10191     if (!isTypeLegal(VT))
10192       return SDValue();
10193
10194     // Return the new VECTOR_SHUFFLE node.
10195     SDValue Ops[2];
10196     Ops[0] = VecIn1;
10197     Ops[1] = VecIn2;
10198     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10199   }
10200
10201   return SDValue();
10202 }
10203
10204 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10205   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10206   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10207   // inputs come from at most two distinct vectors, turn this into a shuffle
10208   // node.
10209
10210   // If we only have one input vector, we don't need to do any concatenation.
10211   if (N->getNumOperands() == 1)
10212     return N->getOperand(0);
10213
10214   // Check if all of the operands are undefs.
10215   EVT VT = N->getValueType(0);
10216   if (ISD::allOperandsUndef(N))
10217     return DAG.getUNDEF(VT);
10218
10219   // Optimize concat_vectors where one of the vectors is undef.
10220   if (N->getNumOperands() == 2 &&
10221       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10222     SDValue In = N->getOperand(0);
10223     assert(In.getValueType().isVector() && "Must concat vectors");
10224
10225     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10226     if (In->getOpcode() == ISD::BITCAST &&
10227         !In->getOperand(0)->getValueType(0).isVector()) {
10228       SDValue Scalar = In->getOperand(0);
10229       EVT SclTy = Scalar->getValueType(0);
10230
10231       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10232         return SDValue();
10233
10234       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10235                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10236       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10237         return SDValue();
10238
10239       SDLoc dl = SDLoc(N);
10240       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10241       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10242     }
10243   }
10244
10245   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10246   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10247   if (N->getNumOperands() == 2 &&
10248       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10249       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10250     EVT VT = N->getValueType(0);
10251     SDValue N0 = N->getOperand(0);
10252     SDValue N1 = N->getOperand(1);
10253     SmallVector<SDValue, 8> Opnds;
10254     unsigned BuildVecNumElts =  N0.getNumOperands();
10255
10256     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10257       Opnds.push_back(N0.getOperand(i));
10258     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10259       Opnds.push_back(N1.getOperand(i));
10260
10261     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10262                        Opnds.size());
10263   }
10264
10265   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10266   // nodes often generate nop CONCAT_VECTOR nodes.
10267   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10268   // place the incoming vectors at the exact same location.
10269   SDValue SingleSource = SDValue();
10270   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10271
10272   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10273     SDValue Op = N->getOperand(i);
10274
10275     if (Op.getOpcode() == ISD::UNDEF)
10276       continue;
10277
10278     // Check if this is the identity extract:
10279     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10280       return SDValue();
10281
10282     // Find the single incoming vector for the extract_subvector.
10283     if (SingleSource.getNode()) {
10284       if (Op.getOperand(0) != SingleSource)
10285         return SDValue();
10286     } else {
10287       SingleSource = Op.getOperand(0);
10288
10289       // Check the source type is the same as the type of the result.
10290       // If not, this concat may extend the vector, so we can not
10291       // optimize it away.
10292       if (SingleSource.getValueType() != N->getValueType(0))
10293         return SDValue();
10294     }
10295
10296     unsigned IdentityIndex = i * PartNumElem;
10297     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10298     // The extract index must be constant.
10299     if (!CS)
10300       return SDValue();
10301
10302     // Check that we are reading from the identity index.
10303     if (CS->getZExtValue() != IdentityIndex)
10304       return SDValue();
10305   }
10306
10307   if (SingleSource.getNode())
10308     return SingleSource;
10309
10310   return SDValue();
10311 }
10312
10313 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10314   EVT NVT = N->getValueType(0);
10315   SDValue V = N->getOperand(0);
10316
10317   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10318     // Combine:
10319     //    (extract_subvec (concat V1, V2, ...), i)
10320     // Into:
10321     //    Vi if possible
10322     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10323     // type.
10324     if (V->getOperand(0).getValueType() != NVT)
10325       return SDValue();
10326     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10327     unsigned NumElems = NVT.getVectorNumElements();
10328     assert((Idx % NumElems) == 0 &&
10329            "IDX in concat is not a multiple of the result vector length.");
10330     return V->getOperand(Idx / NumElems);
10331   }
10332
10333   // Skip bitcasting
10334   if (V->getOpcode() == ISD::BITCAST)
10335     V = V.getOperand(0);
10336
10337   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10338     SDLoc dl(N);
10339     // Handle only simple case where vector being inserted and vector
10340     // being extracted are of same type, and are half size of larger vectors.
10341     EVT BigVT = V->getOperand(0).getValueType();
10342     EVT SmallVT = V->getOperand(1).getValueType();
10343     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10344       return SDValue();
10345
10346     // Only handle cases where both indexes are constants with the same type.
10347     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10348     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10349
10350     if (InsIdx && ExtIdx &&
10351         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10352         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10353       // Combine:
10354       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10355       // Into:
10356       //    indices are equal or bit offsets are equal => V1
10357       //    otherwise => (extract_subvec V1, ExtIdx)
10358       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10359           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10360         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10361       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10362                          DAG.getNode(ISD::BITCAST, dl,
10363                                      N->getOperand(0).getValueType(),
10364                                      V->getOperand(0)), N->getOperand(1));
10365     }
10366   }
10367
10368   return SDValue();
10369 }
10370
10371 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10372 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10373   EVT VT = N->getValueType(0);
10374   unsigned NumElts = VT.getVectorNumElements();
10375
10376   SDValue N0 = N->getOperand(0);
10377   SDValue N1 = N->getOperand(1);
10378   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10379
10380   SmallVector<SDValue, 4> Ops;
10381   EVT ConcatVT = N0.getOperand(0).getValueType();
10382   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10383   unsigned NumConcats = NumElts / NumElemsPerConcat;
10384
10385   // Look at every vector that's inserted. We're looking for exact
10386   // subvector-sized copies from a concatenated vector
10387   for (unsigned I = 0; I != NumConcats; ++I) {
10388     // Make sure we're dealing with a copy.
10389     unsigned Begin = I * NumElemsPerConcat;
10390     bool AllUndef = true, NoUndef = true;
10391     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10392       if (SVN->getMaskElt(J) >= 0)
10393         AllUndef = false;
10394       else
10395         NoUndef = false;
10396     }
10397
10398     if (NoUndef) {
10399       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10400         return SDValue();
10401
10402       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10403         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10404           return SDValue();
10405
10406       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10407       if (FirstElt < N0.getNumOperands())
10408         Ops.push_back(N0.getOperand(FirstElt));
10409       else
10410         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10411
10412     } else if (AllUndef) {
10413       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10414     } else { // Mixed with general masks and undefs, can't do optimization.
10415       return SDValue();
10416     }
10417   }
10418
10419   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10420                      Ops.size());
10421 }
10422
10423 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10424   EVT VT = N->getValueType(0);
10425   unsigned NumElts = VT.getVectorNumElements();
10426
10427   SDValue N0 = N->getOperand(0);
10428   SDValue N1 = N->getOperand(1);
10429
10430   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10431
10432   // Canonicalize shuffle undef, undef -> undef
10433   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10434     return DAG.getUNDEF(VT);
10435
10436   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10437
10438   // Canonicalize shuffle v, v -> v, undef
10439   if (N0 == N1) {
10440     SmallVector<int, 8> NewMask;
10441     for (unsigned i = 0; i != NumElts; ++i) {
10442       int Idx = SVN->getMaskElt(i);
10443       if (Idx >= (int)NumElts) Idx -= NumElts;
10444       NewMask.push_back(Idx);
10445     }
10446     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10447                                 &NewMask[0]);
10448   }
10449
10450   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10451   if (N0.getOpcode() == ISD::UNDEF) {
10452     SmallVector<int, 8> NewMask;
10453     for (unsigned i = 0; i != NumElts; ++i) {
10454       int Idx = SVN->getMaskElt(i);
10455       if (Idx >= 0) {
10456         if (Idx >= (int)NumElts)
10457           Idx -= NumElts;
10458         else
10459           Idx = -1; // remove reference to lhs
10460       }
10461       NewMask.push_back(Idx);
10462     }
10463     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10464                                 &NewMask[0]);
10465   }
10466
10467   // Remove references to rhs if it is undef
10468   if (N1.getOpcode() == ISD::UNDEF) {
10469     bool Changed = false;
10470     SmallVector<int, 8> NewMask;
10471     for (unsigned i = 0; i != NumElts; ++i) {
10472       int Idx = SVN->getMaskElt(i);
10473       if (Idx >= (int)NumElts) {
10474         Idx = -1;
10475         Changed = true;
10476       }
10477       NewMask.push_back(Idx);
10478     }
10479     if (Changed)
10480       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10481   }
10482
10483   // If it is a splat, check if the argument vector is another splat or a
10484   // build_vector with all scalar elements the same.
10485   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10486     SDNode *V = N0.getNode();
10487
10488     // If this is a bit convert that changes the element type of the vector but
10489     // not the number of vector elements, look through it.  Be careful not to
10490     // look though conversions that change things like v4f32 to v2f64.
10491     if (V->getOpcode() == ISD::BITCAST) {
10492       SDValue ConvInput = V->getOperand(0);
10493       if (ConvInput.getValueType().isVector() &&
10494           ConvInput.getValueType().getVectorNumElements() == NumElts)
10495         V = ConvInput.getNode();
10496     }
10497
10498     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10499       assert(V->getNumOperands() == NumElts &&
10500              "BUILD_VECTOR has wrong number of operands");
10501       SDValue Base;
10502       bool AllSame = true;
10503       for (unsigned i = 0; i != NumElts; ++i) {
10504         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10505           Base = V->getOperand(i);
10506           break;
10507         }
10508       }
10509       // Splat of <u, u, u, u>, return <u, u, u, u>
10510       if (!Base.getNode())
10511         return N0;
10512       for (unsigned i = 0; i != NumElts; ++i) {
10513         if (V->getOperand(i) != Base) {
10514           AllSame = false;
10515           break;
10516         }
10517       }
10518       // Splat of <x, x, x, x>, return <x, x, x, x>
10519       if (AllSame)
10520         return N0;
10521     }
10522   }
10523
10524   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10525       Level < AfterLegalizeVectorOps &&
10526       (N1.getOpcode() == ISD::UNDEF ||
10527       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10528        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10529     SDValue V = partitionShuffleOfConcats(N, DAG);
10530
10531     if (V.getNode())
10532       return V;
10533   }
10534
10535   // If this shuffle node is simply a swizzle of another shuffle node,
10536   // and it reverses the swizzle of the previous shuffle then we can
10537   // optimize shuffle(shuffle(x, undef), undef) -> x.
10538   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10539       N1.getOpcode() == ISD::UNDEF) {
10540
10541     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10542
10543     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10544     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10545       return SDValue();
10546
10547     // The incoming shuffle must be of the same type as the result of the
10548     // current shuffle.
10549     assert(OtherSV->getOperand(0).getValueType() == VT &&
10550            "Shuffle types don't match");
10551
10552     for (unsigned i = 0; i != NumElts; ++i) {
10553       int Idx = SVN->getMaskElt(i);
10554       assert(Idx < (int)NumElts && "Index references undef operand");
10555       // Next, this index comes from the first value, which is the incoming
10556       // shuffle. Adopt the incoming index.
10557       if (Idx >= 0)
10558         Idx = OtherSV->getMaskElt(Idx);
10559
10560       // The combined shuffle must map each index to itself.
10561       if (Idx >= 0 && (unsigned)Idx != i)
10562         return SDValue();
10563     }
10564
10565     return OtherSV->getOperand(0);
10566   }
10567
10568   return SDValue();
10569 }
10570
10571 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10572   SDValue N0 = N->getOperand(0);
10573   SDValue N2 = N->getOperand(2);
10574
10575   // If the input vector is a concatenation, and the insert replaces
10576   // one of the halves, we can optimize into a single concat_vectors.
10577   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10578       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10579     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10580     EVT VT = N->getValueType(0);
10581
10582     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10583     // (concat_vectors Z, Y)
10584     if (InsIdx == 0)
10585       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10586                          N->getOperand(1), N0.getOperand(1));
10587
10588     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10589     // (concat_vectors X, Z)
10590     if (InsIdx == VT.getVectorNumElements()/2)
10591       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10592                          N0.getOperand(0), N->getOperand(1));
10593   }
10594
10595   return SDValue();
10596 }
10597
10598 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10599 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10600 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10601 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10602 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10603   EVT VT = N->getValueType(0);
10604   SDLoc dl(N);
10605   SDValue LHS = N->getOperand(0);
10606   SDValue RHS = N->getOperand(1);
10607   if (N->getOpcode() == ISD::AND) {
10608     if (RHS.getOpcode() == ISD::BITCAST)
10609       RHS = RHS.getOperand(0);
10610     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10611       SmallVector<int, 8> Indices;
10612       unsigned NumElts = RHS.getNumOperands();
10613       for (unsigned i = 0; i != NumElts; ++i) {
10614         SDValue Elt = RHS.getOperand(i);
10615         if (!isa<ConstantSDNode>(Elt))
10616           return SDValue();
10617
10618         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10619           Indices.push_back(i);
10620         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10621           Indices.push_back(NumElts);
10622         else
10623           return SDValue();
10624       }
10625
10626       // Let's see if the target supports this vector_shuffle.
10627       EVT RVT = RHS.getValueType();
10628       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10629         return SDValue();
10630
10631       // Return the new VECTOR_SHUFFLE node.
10632       EVT EltVT = RVT.getVectorElementType();
10633       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10634                                      DAG.getConstant(0, EltVT));
10635       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10636                                  RVT, &ZeroOps[0], ZeroOps.size());
10637       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10638       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10639       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10640     }
10641   }
10642
10643   return SDValue();
10644 }
10645
10646 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10647 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10648   assert(N->getValueType(0).isVector() &&
10649          "SimplifyVBinOp only works on vectors!");
10650
10651   SDValue LHS = N->getOperand(0);
10652   SDValue RHS = N->getOperand(1);
10653   SDValue Shuffle = XformToShuffleWithZero(N);
10654   if (Shuffle.getNode()) return Shuffle;
10655
10656   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10657   // this operation.
10658   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10659       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10660     // Check if both vectors are constants. If not bail out.
10661     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10662           cast<BuildVectorSDNode>(RHS)->isConstant()))
10663       return SDValue();
10664
10665     SmallVector<SDValue, 8> Ops;
10666     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10667       SDValue LHSOp = LHS.getOperand(i);
10668       SDValue RHSOp = RHS.getOperand(i);
10669
10670       // Can't fold divide by zero.
10671       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10672           N->getOpcode() == ISD::FDIV) {
10673         if ((RHSOp.getOpcode() == ISD::Constant &&
10674              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10675             (RHSOp.getOpcode() == ISD::ConstantFP &&
10676              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10677           break;
10678       }
10679
10680       EVT VT = LHSOp.getValueType();
10681       EVT RVT = RHSOp.getValueType();
10682       if (RVT != VT) {
10683         // Integer BUILD_VECTOR operands may have types larger than the element
10684         // size (e.g., when the element type is not legal).  Prior to type
10685         // legalization, the types may not match between the two BUILD_VECTORS.
10686         // Truncate one of the operands to make them match.
10687         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10688           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10689         } else {
10690           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10691           VT = RVT;
10692         }
10693       }
10694       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10695                                    LHSOp, RHSOp);
10696       if (FoldOp.getOpcode() != ISD::UNDEF &&
10697           FoldOp.getOpcode() != ISD::Constant &&
10698           FoldOp.getOpcode() != ISD::ConstantFP)
10699         break;
10700       Ops.push_back(FoldOp);
10701       AddToWorkList(FoldOp.getNode());
10702     }
10703
10704     if (Ops.size() == LHS.getNumOperands())
10705       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10706                          LHS.getValueType(), &Ops[0], Ops.size());
10707   }
10708
10709   return SDValue();
10710 }
10711
10712 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10713 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10714   assert(N->getValueType(0).isVector() &&
10715          "SimplifyVUnaryOp only works on vectors!");
10716
10717   SDValue N0 = N->getOperand(0);
10718
10719   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10720     return SDValue();
10721
10722   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10723   SmallVector<SDValue, 8> Ops;
10724   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10725     SDValue Op = N0.getOperand(i);
10726     if (Op.getOpcode() != ISD::UNDEF &&
10727         Op.getOpcode() != ISD::ConstantFP)
10728       break;
10729     EVT EltVT = Op.getValueType();
10730     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10731     if (FoldOp.getOpcode() != ISD::UNDEF &&
10732         FoldOp.getOpcode() != ISD::ConstantFP)
10733       break;
10734     Ops.push_back(FoldOp);
10735     AddToWorkList(FoldOp.getNode());
10736   }
10737
10738   if (Ops.size() != N0.getNumOperands())
10739     return SDValue();
10740
10741   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10742                      N0.getValueType(), &Ops[0], Ops.size());
10743 }
10744
10745 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10746                                     SDValue N1, SDValue N2){
10747   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10748
10749   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10750                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10751
10752   // If we got a simplified select_cc node back from SimplifySelectCC, then
10753   // break it down into a new SETCC node, and a new SELECT node, and then return
10754   // the SELECT node, since we were called with a SELECT node.
10755   if (SCC.getNode()) {
10756     // Check to see if we got a select_cc back (to turn into setcc/select).
10757     // Otherwise, just return whatever node we got back, like fabs.
10758     if (SCC.getOpcode() == ISD::SELECT_CC) {
10759       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10760                                   N0.getValueType(),
10761                                   SCC.getOperand(0), SCC.getOperand(1),
10762                                   SCC.getOperand(4));
10763       AddToWorkList(SETCC.getNode());
10764       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10765                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10766     }
10767
10768     return SCC;
10769   }
10770   return SDValue();
10771 }
10772
10773 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10774 /// are the two values being selected between, see if we can simplify the
10775 /// select.  Callers of this should assume that TheSelect is deleted if this
10776 /// returns true.  As such, they should return the appropriate thing (e.g. the
10777 /// node) back to the top-level of the DAG combiner loop to avoid it being
10778 /// looked at.
10779 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10780                                     SDValue RHS) {
10781
10782   // Cannot simplify select with vector condition
10783   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10784
10785   // If this is a select from two identical things, try to pull the operation
10786   // through the select.
10787   if (LHS.getOpcode() != RHS.getOpcode() ||
10788       !LHS.hasOneUse() || !RHS.hasOneUse())
10789     return false;
10790
10791   // If this is a load and the token chain is identical, replace the select
10792   // of two loads with a load through a select of the address to load from.
10793   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10794   // constants have been dropped into the constant pool.
10795   if (LHS.getOpcode() == ISD::LOAD) {
10796     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10797     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10798
10799     // Token chains must be identical.
10800     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10801         // Do not let this transformation reduce the number of volatile loads.
10802         LLD->isVolatile() || RLD->isVolatile() ||
10803         // If this is an EXTLOAD, the VT's must match.
10804         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10805         // If this is an EXTLOAD, the kind of extension must match.
10806         (LLD->getExtensionType() != RLD->getExtensionType() &&
10807          // The only exception is if one of the extensions is anyext.
10808          LLD->getExtensionType() != ISD::EXTLOAD &&
10809          RLD->getExtensionType() != ISD::EXTLOAD) ||
10810         // FIXME: this discards src value information.  This is
10811         // over-conservative. It would be beneficial to be able to remember
10812         // both potential memory locations.  Since we are discarding
10813         // src value info, don't do the transformation if the memory
10814         // locations are not in the default address space.
10815         LLD->getPointerInfo().getAddrSpace() != 0 ||
10816         RLD->getPointerInfo().getAddrSpace() != 0 ||
10817         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10818                                       LLD->getBasePtr().getValueType()))
10819       return false;
10820
10821     // Check that the select condition doesn't reach either load.  If so,
10822     // folding this will induce a cycle into the DAG.  If not, this is safe to
10823     // xform, so create a select of the addresses.
10824     SDValue Addr;
10825     if (TheSelect->getOpcode() == ISD::SELECT) {
10826       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10827       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10828           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10829         return false;
10830       // The loads must not depend on one another.
10831       if (LLD->isPredecessorOf(RLD) ||
10832           RLD->isPredecessorOf(LLD))
10833         return false;
10834       Addr = DAG.getSelect(SDLoc(TheSelect),
10835                            LLD->getBasePtr().getValueType(),
10836                            TheSelect->getOperand(0), LLD->getBasePtr(),
10837                            RLD->getBasePtr());
10838     } else {  // Otherwise SELECT_CC
10839       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10840       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10841
10842       if ((LLD->hasAnyUseOfValue(1) &&
10843            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10844           (RLD->hasAnyUseOfValue(1) &&
10845            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10846         return false;
10847
10848       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10849                          LLD->getBasePtr().getValueType(),
10850                          TheSelect->getOperand(0),
10851                          TheSelect->getOperand(1),
10852                          LLD->getBasePtr(), RLD->getBasePtr(),
10853                          TheSelect->getOperand(4));
10854     }
10855
10856     SDValue Load;
10857     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10858       Load = DAG.getLoad(TheSelect->getValueType(0),
10859                          SDLoc(TheSelect),
10860                          // FIXME: Discards pointer and TBAA info.
10861                          LLD->getChain(), Addr, MachinePointerInfo(),
10862                          LLD->isVolatile(), LLD->isNonTemporal(),
10863                          LLD->isInvariant(), LLD->getAlignment());
10864     } else {
10865       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10866                             RLD->getExtensionType() : LLD->getExtensionType(),
10867                             SDLoc(TheSelect),
10868                             TheSelect->getValueType(0),
10869                             // FIXME: Discards pointer and TBAA info.
10870                             LLD->getChain(), Addr, MachinePointerInfo(),
10871                             LLD->getMemoryVT(), LLD->isVolatile(),
10872                             LLD->isNonTemporal(), LLD->getAlignment());
10873     }
10874
10875     // Users of the select now use the result of the load.
10876     CombineTo(TheSelect, Load);
10877
10878     // Users of the old loads now use the new load's chain.  We know the
10879     // old-load value is dead now.
10880     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10881     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10882     return true;
10883   }
10884
10885   return false;
10886 }
10887
10888 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10889 /// where 'cond' is the comparison specified by CC.
10890 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10891                                       SDValue N2, SDValue N3,
10892                                       ISD::CondCode CC, bool NotExtCompare) {
10893   // (x ? y : y) -> y.
10894   if (N2 == N3) return N2;
10895
10896   EVT VT = N2.getValueType();
10897   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10898   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10899   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10900
10901   // Determine if the condition we're dealing with is constant
10902   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10903                               N0, N1, CC, DL, false);
10904   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10905   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10906
10907   // fold select_cc true, x, y -> x
10908   if (SCCC && !SCCC->isNullValue())
10909     return N2;
10910   // fold select_cc false, x, y -> y
10911   if (SCCC && SCCC->isNullValue())
10912     return N3;
10913
10914   // Check to see if we can simplify the select into an fabs node
10915   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10916     // Allow either -0.0 or 0.0
10917     if (CFP->getValueAPF().isZero()) {
10918       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10919       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10920           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10921           N2 == N3.getOperand(0))
10922         return DAG.getNode(ISD::FABS, DL, VT, N0);
10923
10924       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10925       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10926           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10927           N2.getOperand(0) == N3)
10928         return DAG.getNode(ISD::FABS, DL, VT, N3);
10929     }
10930   }
10931
10932   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10933   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10934   // in it.  This is a win when the constant is not otherwise available because
10935   // it replaces two constant pool loads with one.  We only do this if the FP
10936   // type is known to be legal, because if it isn't, then we are before legalize
10937   // types an we want the other legalization to happen first (e.g. to avoid
10938   // messing with soft float) and if the ConstantFP is not legal, because if
10939   // it is legal, we may not need to store the FP constant in a constant pool.
10940   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10941     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10942       if (TLI.isTypeLegal(N2.getValueType()) &&
10943           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10944                TargetLowering::Legal &&
10945            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
10946            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
10947           // If both constants have multiple uses, then we won't need to do an
10948           // extra load, they are likely around in registers for other users.
10949           (TV->hasOneUse() || FV->hasOneUse())) {
10950         Constant *Elts[] = {
10951           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10952           const_cast<ConstantFP*>(TV->getConstantFPValue())
10953         };
10954         Type *FPTy = Elts[0]->getType();
10955         const DataLayout &TD = *TLI.getDataLayout();
10956
10957         // Create a ConstantArray of the two constants.
10958         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10959         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10960                                             TD.getPrefTypeAlignment(FPTy));
10961         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10962
10963         // Get the offsets to the 0 and 1 element of the array so that we can
10964         // select between them.
10965         SDValue Zero = DAG.getIntPtrConstant(0);
10966         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10967         SDValue One = DAG.getIntPtrConstant(EltSize);
10968
10969         SDValue Cond = DAG.getSetCC(DL,
10970                                     getSetCCResultType(N0.getValueType()),
10971                                     N0, N1, CC);
10972         AddToWorkList(Cond.getNode());
10973         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10974                                           Cond, One, Zero);
10975         AddToWorkList(CstOffset.getNode());
10976         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10977                             CstOffset);
10978         AddToWorkList(CPIdx.getNode());
10979         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10980                            MachinePointerInfo::getConstantPool(), false,
10981                            false, false, Alignment);
10982
10983       }
10984     }
10985
10986   // Check to see if we can perform the "gzip trick", transforming
10987   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10988   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10989       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
10990        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
10991     EVT XType = N0.getValueType();
10992     EVT AType = N2.getValueType();
10993     if (XType.bitsGE(AType)) {
10994       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10995       // single-bit constant.
10996       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10997         unsigned ShCtV = N2C->getAPIntValue().logBase2();
10998         ShCtV = XType.getSizeInBits()-ShCtV-1;
10999         SDValue ShCt = DAG.getConstant(ShCtV,
11000                                        getShiftAmountTy(N0.getValueType()));
11001         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11002                                     XType, N0, ShCt);
11003         AddToWorkList(Shift.getNode());
11004
11005         if (XType.bitsGT(AType)) {
11006           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11007           AddToWorkList(Shift.getNode());
11008         }
11009
11010         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11011       }
11012
11013       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11014                                   XType, N0,
11015                                   DAG.getConstant(XType.getSizeInBits()-1,
11016                                          getShiftAmountTy(N0.getValueType())));
11017       AddToWorkList(Shift.getNode());
11018
11019       if (XType.bitsGT(AType)) {
11020         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11021         AddToWorkList(Shift.getNode());
11022       }
11023
11024       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11025     }
11026   }
11027
11028   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11029   // where y is has a single bit set.
11030   // A plaintext description would be, we can turn the SELECT_CC into an AND
11031   // when the condition can be materialized as an all-ones register.  Any
11032   // single bit-test can be materialized as an all-ones register with
11033   // shift-left and shift-right-arith.
11034   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11035       N0->getValueType(0) == VT &&
11036       N1C && N1C->isNullValue() &&
11037       N2C && N2C->isNullValue()) {
11038     SDValue AndLHS = N0->getOperand(0);
11039     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11040     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11041       // Shift the tested bit over the sign bit.
11042       APInt AndMask = ConstAndRHS->getAPIntValue();
11043       SDValue ShlAmt =
11044         DAG.getConstant(AndMask.countLeadingZeros(),
11045                         getShiftAmountTy(AndLHS.getValueType()));
11046       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11047
11048       // Now arithmetic right shift it all the way over, so the result is either
11049       // all-ones, or zero.
11050       SDValue ShrAmt =
11051         DAG.getConstant(AndMask.getBitWidth()-1,
11052                         getShiftAmountTy(Shl.getValueType()));
11053       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11054
11055       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11056     }
11057   }
11058
11059   // fold select C, 16, 0 -> shl C, 4
11060   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11061     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11062       TargetLowering::ZeroOrOneBooleanContent) {
11063
11064     // If the caller doesn't want us to simplify this into a zext of a compare,
11065     // don't do it.
11066     if (NotExtCompare && N2C->getAPIntValue() == 1)
11067       return SDValue();
11068
11069     // Get a SetCC of the condition
11070     // NOTE: Don't create a SETCC if it's not legal on this target.
11071     if (!LegalOperations ||
11072         TLI.isOperationLegal(ISD::SETCC,
11073           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11074       SDValue Temp, SCC;
11075       // cast from setcc result type to select result type
11076       if (LegalTypes) {
11077         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11078                             N0, N1, CC);
11079         if (N2.getValueType().bitsLT(SCC.getValueType()))
11080           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11081                                         N2.getValueType());
11082         else
11083           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11084                              N2.getValueType(), SCC);
11085       } else {
11086         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11087         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11088                            N2.getValueType(), SCC);
11089       }
11090
11091       AddToWorkList(SCC.getNode());
11092       AddToWorkList(Temp.getNode());
11093
11094       if (N2C->getAPIntValue() == 1)
11095         return Temp;
11096
11097       // shl setcc result by log2 n2c
11098       return DAG.getNode(
11099           ISD::SHL, DL, N2.getValueType(), Temp,
11100           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11101                           getShiftAmountTy(Temp.getValueType())));
11102     }
11103   }
11104
11105   // Check to see if this is the equivalent of setcc
11106   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11107   // otherwise, go ahead with the folds.
11108   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11109     EVT XType = N0.getValueType();
11110     if (!LegalOperations ||
11111         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11112       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11113       if (Res.getValueType() != VT)
11114         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11115       return Res;
11116     }
11117
11118     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11119     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11120         (!LegalOperations ||
11121          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11122       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11123       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11124                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11125                                        getShiftAmountTy(Ctlz.getValueType())));
11126     }
11127     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11128     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11129       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11130                                   XType, DAG.getConstant(0, XType), N0);
11131       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11132       return DAG.getNode(ISD::SRL, DL, XType,
11133                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11134                          DAG.getConstant(XType.getSizeInBits()-1,
11135                                          getShiftAmountTy(XType)));
11136     }
11137     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11138     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11139       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11140                                  DAG.getConstant(XType.getSizeInBits()-1,
11141                                          getShiftAmountTy(N0.getValueType())));
11142       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11143     }
11144   }
11145
11146   // Check to see if this is an integer abs.
11147   // select_cc setg[te] X,  0,  X, -X ->
11148   // select_cc setgt    X, -1,  X, -X ->
11149   // select_cc setl[te] X,  0, -X,  X ->
11150   // select_cc setlt    X,  1, -X,  X ->
11151   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11152   if (N1C) {
11153     ConstantSDNode *SubC = nullptr;
11154     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11155          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11156         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11157       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11158     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11159               (N1C->isOne() && CC == ISD::SETLT)) &&
11160              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11161       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11162
11163     EVT XType = N0.getValueType();
11164     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11165       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11166                                   N0,
11167                                   DAG.getConstant(XType.getSizeInBits()-1,
11168                                          getShiftAmountTy(N0.getValueType())));
11169       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11170                                 XType, N0, Shift);
11171       AddToWorkList(Shift.getNode());
11172       AddToWorkList(Add.getNode());
11173       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11174     }
11175   }
11176
11177   return SDValue();
11178 }
11179
11180 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11181 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11182                                    SDValue N1, ISD::CondCode Cond,
11183                                    SDLoc DL, bool foldBooleans) {
11184   TargetLowering::DAGCombinerInfo
11185     DagCombineInfo(DAG, Level, false, this);
11186   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11187 }
11188
11189 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11190 /// return a DAG expression to select that will generate the same value by
11191 /// multiplying by a magic number.  See:
11192 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11193 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11194   const APInt *Divisor;
11195   if (N->getValueType(0).isVector()) {
11196     // Handle splat vectors.
11197     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11198     if (ConstantSDNode *C = BV->getConstantSplatValue())
11199       Divisor = &C->getAPIntValue();
11200     else
11201       return SDValue();
11202   } else {
11203     Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11204   }
11205
11206   // Avoid division by zero.
11207   if (!*Divisor)
11208     return SDValue();
11209
11210   std::vector<SDNode*> Built;
11211   SDValue S = TLI.BuildSDIV(N, *Divisor, DAG, LegalOperations, &Built);
11212
11213   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11214        ii != ee; ++ii)
11215     AddToWorkList(*ii);
11216   return S;
11217 }
11218
11219 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11220 /// return a DAG expression to select that will generate the same value by
11221 /// multiplying by a magic number.  See:
11222 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11223 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11224   const APInt *Divisor;
11225   if (N->getValueType(0).isVector()) {
11226     // Handle splat vectors.
11227     BuildVectorSDNode *BV = cast<BuildVectorSDNode>(N->getOperand(1));
11228     if (ConstantSDNode *C = BV->getConstantSplatValue())
11229       Divisor = &C->getAPIntValue();
11230     else
11231       return SDValue();
11232   } else {
11233     Divisor = &cast<ConstantSDNode>(N->getOperand(1))->getAPIntValue();
11234   }
11235
11236   // Avoid division by zero.
11237   if (!*Divisor)
11238     return SDValue();
11239
11240   std::vector<SDNode*> Built;
11241   SDValue S = TLI.BuildUDIV(N, *Divisor, DAG, LegalOperations, &Built);
11242
11243   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11244        ii != ee; ++ii)
11245     AddToWorkList(*ii);
11246   return S;
11247 }
11248
11249 /// FindBaseOffset - Return true if base is a frame index, which is known not
11250 // to alias with anything but itself.  Provides base object and offset as
11251 // results.
11252 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11253                            const GlobalValue *&GV, const void *&CV) {
11254   // Assume it is a primitive operation.
11255   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11256
11257   // If it's an adding a simple constant then integrate the offset.
11258   if (Base.getOpcode() == ISD::ADD) {
11259     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11260       Base = Base.getOperand(0);
11261       Offset += C->getZExtValue();
11262     }
11263   }
11264
11265   // Return the underlying GlobalValue, and update the Offset.  Return false
11266   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11267   // by multiple nodes with different offsets.
11268   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11269     GV = G->getGlobal();
11270     Offset += G->getOffset();
11271     return false;
11272   }
11273
11274   // Return the underlying Constant value, and update the Offset.  Return false
11275   // for ConstantSDNodes since the same constant pool entry may be represented
11276   // by multiple nodes with different offsets.
11277   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11278     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11279                                          : (const void *)C->getConstVal();
11280     Offset += C->getOffset();
11281     return false;
11282   }
11283   // If it's any of the following then it can't alias with anything but itself.
11284   return isa<FrameIndexSDNode>(Base);
11285 }
11286
11287 /// isAlias - Return true if there is any possibility that the two addresses
11288 /// overlap.
11289 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11290   // If they are the same then they must be aliases.
11291   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11292
11293   // If they are both volatile then they cannot be reordered.
11294   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11295
11296   // Gather base node and offset information.
11297   SDValue Base1, Base2;
11298   int64_t Offset1, Offset2;
11299   const GlobalValue *GV1, *GV2;
11300   const void *CV1, *CV2;
11301   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11302                                       Base1, Offset1, GV1, CV1);
11303   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11304                                       Base2, Offset2, GV2, CV2);
11305
11306   // If they have a same base address then check to see if they overlap.
11307   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11308     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11309              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11310
11311   // It is possible for different frame indices to alias each other, mostly
11312   // when tail call optimization reuses return address slots for arguments.
11313   // To catch this case, look up the actual index of frame indices to compute
11314   // the real alias relationship.
11315   if (isFrameIndex1 && isFrameIndex2) {
11316     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11317     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11318     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11319     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11320              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11321   }
11322
11323   // Otherwise, if we know what the bases are, and they aren't identical, then
11324   // we know they cannot alias.
11325   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11326     return false;
11327
11328   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11329   // compared to the size and offset of the access, we may be able to prove they
11330   // do not alias.  This check is conservative for now to catch cases created by
11331   // splitting vector types.
11332   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11333       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11334       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11335        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11336       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11337     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11338     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11339
11340     // There is no overlap between these relatively aligned accesses of similar
11341     // size, return no alias.
11342     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11343         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11344       return false;
11345   }
11346
11347   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11348     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11349 #ifndef NDEBUG
11350   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11351       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11352     UseAA = false;
11353 #endif
11354   if (UseAA &&
11355       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11356     // Use alias analysis information.
11357     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11358                                  Op1->getSrcValueOffset());
11359     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11360         Op0->getSrcValueOffset() - MinOffset;
11361     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11362         Op1->getSrcValueOffset() - MinOffset;
11363     AliasAnalysis::AliasResult AAResult =
11364         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11365                                          Overlap1,
11366                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11367                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11368                                          Overlap2,
11369                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11370     if (AAResult == AliasAnalysis::NoAlias)
11371       return false;
11372   }
11373
11374   // Otherwise we have to assume they alias.
11375   return true;
11376 }
11377
11378 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11379 /// looking for aliasing nodes and adding them to the Aliases vector.
11380 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11381                                    SmallVectorImpl<SDValue> &Aliases) {
11382   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11383   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11384
11385   // Get alias information for node.
11386   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11387
11388   // Starting off.
11389   Chains.push_back(OriginalChain);
11390   unsigned Depth = 0;
11391
11392   // Look at each chain and determine if it is an alias.  If so, add it to the
11393   // aliases list.  If not, then continue up the chain looking for the next
11394   // candidate.
11395   while (!Chains.empty()) {
11396     SDValue Chain = Chains.back();
11397     Chains.pop_back();
11398
11399     // For TokenFactor nodes, look at each operand and only continue up the
11400     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11401     // find more and revert to original chain since the xform is unlikely to be
11402     // profitable.
11403     //
11404     // FIXME: The depth check could be made to return the last non-aliasing
11405     // chain we found before we hit a tokenfactor rather than the original
11406     // chain.
11407     if (Depth > 6 || Aliases.size() == 2) {
11408       Aliases.clear();
11409       Aliases.push_back(OriginalChain);
11410       return;
11411     }
11412
11413     // Don't bother if we've been before.
11414     if (!Visited.insert(Chain.getNode()))
11415       continue;
11416
11417     switch (Chain.getOpcode()) {
11418     case ISD::EntryToken:
11419       // Entry token is ideal chain operand, but handled in FindBetterChain.
11420       break;
11421
11422     case ISD::LOAD:
11423     case ISD::STORE: {
11424       // Get alias information for Chain.
11425       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11426           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11427
11428       // If chain is alias then stop here.
11429       if (!(IsLoad && IsOpLoad) &&
11430           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11431         Aliases.push_back(Chain);
11432       } else {
11433         // Look further up the chain.
11434         Chains.push_back(Chain.getOperand(0));
11435         ++Depth;
11436       }
11437       break;
11438     }
11439
11440     case ISD::TokenFactor:
11441       // We have to check each of the operands of the token factor for "small"
11442       // token factors, so we queue them up.  Adding the operands to the queue
11443       // (stack) in reverse order maintains the original order and increases the
11444       // likelihood that getNode will find a matching token factor (CSE.)
11445       if (Chain.getNumOperands() > 16) {
11446         Aliases.push_back(Chain);
11447         break;
11448       }
11449       for (unsigned n = Chain.getNumOperands(); n;)
11450         Chains.push_back(Chain.getOperand(--n));
11451       ++Depth;
11452       break;
11453
11454     default:
11455       // For all other instructions we will just have to take what we can get.
11456       Aliases.push_back(Chain);
11457       break;
11458     }
11459   }
11460
11461   // We need to be careful here to also search for aliases through the
11462   // value operand of a store, etc. Consider the following situation:
11463   //   Token1 = ...
11464   //   L1 = load Token1, %52
11465   //   S1 = store Token1, L1, %51
11466   //   L2 = load Token1, %52+8
11467   //   S2 = store Token1, L2, %51+8
11468   //   Token2 = Token(S1, S2)
11469   //   L3 = load Token2, %53
11470   //   S3 = store Token2, L3, %52
11471   //   L4 = load Token2, %53+8
11472   //   S4 = store Token2, L4, %52+8
11473   // If we search for aliases of S3 (which loads address %52), and we look
11474   // only through the chain, then we'll miss the trivial dependence on L1
11475   // (which also loads from %52). We then might change all loads and
11476   // stores to use Token1 as their chain operand, which could result in
11477   // copying %53 into %52 before copying %52 into %51 (which should
11478   // happen first).
11479   //
11480   // The problem is, however, that searching for such data dependencies
11481   // can become expensive, and the cost is not directly related to the
11482   // chain depth. Instead, we'll rule out such configurations here by
11483   // insisting that we've visited all chain users (except for users
11484   // of the original chain, which is not necessary). When doing this,
11485   // we need to look through nodes we don't care about (otherwise, things
11486   // like register copies will interfere with trivial cases).
11487
11488   SmallVector<const SDNode *, 16> Worklist;
11489   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11490        IE = Visited.end(); I != IE; ++I)
11491     if (*I != OriginalChain.getNode())
11492       Worklist.push_back(*I);
11493
11494   while (!Worklist.empty()) {
11495     const SDNode *M = Worklist.pop_back_val();
11496
11497     // We have already visited M, and want to make sure we've visited any uses
11498     // of M that we care about. For uses that we've not visisted, and don't
11499     // care about, queue them to the worklist.
11500
11501     for (SDNode::use_iterator UI = M->use_begin(),
11502          UIE = M->use_end(); UI != UIE; ++UI)
11503       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11504         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11505           // We've not visited this use, and we care about it (it could have an
11506           // ordering dependency with the original node).
11507           Aliases.clear();
11508           Aliases.push_back(OriginalChain);
11509           return;
11510         }
11511
11512         // We've not visited this use, but we don't care about it. Mark it as
11513         // visited and enqueue it to the worklist.
11514         Worklist.push_back(*UI);
11515       }
11516   }
11517 }
11518
11519 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11520 /// for a better chain (aliasing node.)
11521 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11522   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11523
11524   // Accumulate all the aliases to this node.
11525   GatherAllAliases(N, OldChain, Aliases);
11526
11527   // If no operands then chain to entry token.
11528   if (Aliases.size() == 0)
11529     return DAG.getEntryNode();
11530
11531   // If a single operand then chain to it.  We don't need to revisit it.
11532   if (Aliases.size() == 1)
11533     return Aliases[0];
11534
11535   // Construct a custom tailored token factor.
11536   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11537                      &Aliases[0], Aliases.size());
11538 }
11539
11540 // SelectionDAG::Combine - This is the entry point for the file.
11541 //
11542 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11543                            CodeGenOpt::Level OptLevel) {
11544   /// run - This is the main entry point to this class.
11545   ///
11546   DAGCombiner(*this, AA, OptLevel).Run(Level);
11547 }