[SDAG] Rather than using a narrow test against the one dummy node on the
[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       // Skip handle nodes as they can't usefully be combined and confuse the
131       // zero-use deletion strategy.
132       if (N->getOpcode() == ISD::HANDLENODE)
133         return;
134
135       WorkListContents.insert(N);
136       WorkListOrder.push_back(N);
137     }
138
139     /// removeFromWorkList - remove all instances of N from the worklist.
140     ///
141     void removeFromWorkList(SDNode *N) {
142       WorkListContents.erase(N);
143     }
144
145     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
146                       bool AddTo = true);
147
148     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
149       return CombineTo(N, &Res, 1, AddTo);
150     }
151
152     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
153                       bool AddTo = true) {
154       SDValue To[] = { Res0, Res1 };
155       return CombineTo(N, To, 2, AddTo);
156     }
157
158     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
159
160   private:
161
162     /// SimplifyDemandedBits - Check the specified integer node value to see if
163     /// it can be simplified or if things it uses can be simplified by bit
164     /// propagation.  If so, return true.
165     bool SimplifyDemandedBits(SDValue Op) {
166       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
167       APInt Demanded = APInt::getAllOnesValue(BitWidth);
168       return SimplifyDemandedBits(Op, Demanded);
169     }
170
171     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
172
173     bool CombineToPreIndexedLoadStore(SDNode *N);
174     bool CombineToPostIndexedLoadStore(SDNode *N);
175     bool SliceUpLoad(SDNode *N);
176
177     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
178     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
179     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
180     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
181     SDValue PromoteIntBinOp(SDValue Op);
182     SDValue PromoteIntShiftOp(SDValue Op);
183     SDValue PromoteExtend(SDValue Op);
184     bool PromoteLoad(SDValue Op);
185
186     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
187                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
188                          ISD::NodeType ExtType);
189
190     /// combine - call the node-specific routine that knows how to fold each
191     /// particular type of node. If that doesn't do anything, try the
192     /// target-specific DAG combines.
193     SDValue combine(SDNode *N);
194
195     // Visitation implementation - Implement dag node combining for different
196     // node types.  The semantics are as follows:
197     // Return Value:
198     //   SDValue.getNode() == 0 - No change was made
199     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
200     //   otherwise              - N should be replaced by the returned Operand.
201     //
202     SDValue visitTokenFactor(SDNode *N);
203     SDValue visitMERGE_VALUES(SDNode *N);
204     SDValue visitADD(SDNode *N);
205     SDValue visitSUB(SDNode *N);
206     SDValue visitADDC(SDNode *N);
207     SDValue visitSUBC(SDNode *N);
208     SDValue visitADDE(SDNode *N);
209     SDValue visitSUBE(SDNode *N);
210     SDValue visitMUL(SDNode *N);
211     SDValue visitSDIV(SDNode *N);
212     SDValue visitUDIV(SDNode *N);
213     SDValue visitSREM(SDNode *N);
214     SDValue visitUREM(SDNode *N);
215     SDValue visitMULHU(SDNode *N);
216     SDValue visitMULHS(SDNode *N);
217     SDValue visitSMUL_LOHI(SDNode *N);
218     SDValue visitUMUL_LOHI(SDNode *N);
219     SDValue visitSMULO(SDNode *N);
220     SDValue visitUMULO(SDNode *N);
221     SDValue visitSDIVREM(SDNode *N);
222     SDValue visitUDIVREM(SDNode *N);
223     SDValue visitAND(SDNode *N);
224     SDValue visitOR(SDNode *N);
225     SDValue visitXOR(SDNode *N);
226     SDValue SimplifyVBinOp(SDNode *N);
227     SDValue SimplifyVUnaryOp(SDNode *N);
228     SDValue visitSHL(SDNode *N);
229     SDValue visitSRA(SDNode *N);
230     SDValue visitSRL(SDNode *N);
231     SDValue visitRotate(SDNode *N);
232     SDValue visitCTLZ(SDNode *N);
233     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234     SDValue visitCTTZ(SDNode *N);
235     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236     SDValue visitCTPOP(SDNode *N);
237     SDValue visitSELECT(SDNode *N);
238     SDValue visitVSELECT(SDNode *N);
239     SDValue visitSELECT_CC(SDNode *N);
240     SDValue visitSETCC(SDNode *N);
241     SDValue visitSIGN_EXTEND(SDNode *N);
242     SDValue visitZERO_EXTEND(SDNode *N);
243     SDValue visitANY_EXTEND(SDNode *N);
244     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245     SDValue visitTRUNCATE(SDNode *N);
246     SDValue visitBITCAST(SDNode *N);
247     SDValue visitBUILD_PAIR(SDNode *N);
248     SDValue visitFADD(SDNode *N);
249     SDValue visitFSUB(SDNode *N);
250     SDValue visitFMUL(SDNode *N);
251     SDValue visitFMA(SDNode *N);
252     SDValue visitFDIV(SDNode *N);
253     SDValue visitFREM(SDNode *N);
254     SDValue visitFCOPYSIGN(SDNode *N);
255     SDValue visitSINT_TO_FP(SDNode *N);
256     SDValue visitUINT_TO_FP(SDNode *N);
257     SDValue visitFP_TO_SINT(SDNode *N);
258     SDValue visitFP_TO_UINT(SDNode *N);
259     SDValue visitFP_ROUND(SDNode *N);
260     SDValue visitFP_ROUND_INREG(SDNode *N);
261     SDValue visitFP_EXTEND(SDNode *N);
262     SDValue visitFNEG(SDNode *N);
263     SDValue visitFABS(SDNode *N);
264     SDValue visitFCEIL(SDNode *N);
265     SDValue visitFTRUNC(SDNode *N);
266     SDValue visitFFLOOR(SDNode *N);
267     SDValue visitBRCOND(SDNode *N);
268     SDValue visitBR_CC(SDNode *N);
269     SDValue visitLOAD(SDNode *N);
270     SDValue visitSTORE(SDNode *N);
271     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273     SDValue visitBUILD_VECTOR(SDNode *N);
274     SDValue visitCONCAT_VECTORS(SDNode *N);
275     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276     SDValue visitVECTOR_SHUFFLE(SDNode *N);
277     SDValue visitINSERT_SUBVECTOR(SDNode *N);
278
279     SDValue XformToShuffleWithZero(SDNode *N);
280     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
281
282     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
283
284     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288                              SDValue N3, ISD::CondCode CC,
289                              bool NotExtCompare = false);
290     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291                           SDLoc DL, bool foldBooleans = true);
292
293     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
294                            SDValue &CC) const;
295     bool isOneUseSetCC(SDValue N) const;
296
297     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
298                                          unsigned HiOp);
299     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
300     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
301     SDValue BuildSDIV(SDNode *N);
302     SDValue BuildUDIV(SDNode *N);
303     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
304                                bool DemandHighBits = true);
305     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
306     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
307                               SDValue InnerPos, SDValue InnerNeg,
308                               unsigned PosOpcode, unsigned NegOpcode,
309                               SDLoc DL);
310     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
311     SDValue ReduceLoadWidth(SDNode *N);
312     SDValue ReduceLoadOpStoreWidth(SDNode *N);
313     SDValue TransformFPLoadStorePair(SDNode *N);
314     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
315     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
316
317     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
318
319     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
320     /// looking for aliasing nodes and adding them to the Aliases vector.
321     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
322                           SmallVectorImpl<SDValue> &Aliases);
323
324     /// isAlias - Return true if there is any possibility that the two addresses
325     /// overlap.
326     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
327
328     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
329     /// looking for a better chain (aliasing node.)
330     SDValue FindBetterChain(SDNode *N, SDValue Chain);
331
332     /// Merge consecutive store operations into a wide store.
333     /// This optimization uses wide integers or vectors when possible.
334     /// \return True if some memory operations were changed.
335     bool MergeConsecutiveStores(StoreSDNode *N);
336
337     /// \brief Try to transform a truncation where C is a constant:
338     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
339     ///
340     /// \p N needs to be a truncation and its first operand an AND. Other
341     /// requirements are checked by the function (e.g. that trunc is
342     /// single-use) and if missed an empty SDValue is returned.
343     SDValue distributeTruncateThroughAnd(SDNode *N);
344
345   public:
346     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
347         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
348           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
349       AttributeSet FnAttrs =
350           DAG.getMachineFunction().getFunction()->getAttributes();
351       ForCodeSize =
352           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
353                                Attribute::OptimizeForSize) ||
354           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
355     }
356
357     /// Run - runs the dag combiner on all nodes in the work list
358     void Run(CombineLevel AtLevel);
359
360     SelectionDAG &getDAG() const { return DAG; }
361
362     /// getShiftAmountTy - Returns a type large enough to hold any valid
363     /// shift amount - before type legalization these can be huge.
364     EVT getShiftAmountTy(EVT LHSTy) {
365       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
366       if (LHSTy.isVector())
367         return LHSTy;
368       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
369                         : TLI.getPointerTy();
370     }
371
372     /// isTypeLegal - This method returns true if we are running before type
373     /// legalization or if the specified VT is legal.
374     bool isTypeLegal(const EVT &VT) {
375       if (!LegalTypes) return true;
376       return TLI.isTypeLegal(VT);
377     }
378
379     /// getSetCCResultType - Convenience wrapper around
380     /// TargetLowering::getSetCCResultType
381     EVT getSetCCResultType(EVT VT) const {
382       return TLI.getSetCCResultType(*DAG.getContext(), VT);
383     }
384   };
385 }
386
387
388 namespace {
389 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
390 /// nodes from the worklist.
391 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
392   DAGCombiner &DC;
393 public:
394   explicit WorkListRemover(DAGCombiner &dc)
395     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
396
397   void NodeDeleted(SDNode *N, SDNode *E) override {
398     DC.removeFromWorkList(N);
399   }
400 };
401 }
402
403 //===----------------------------------------------------------------------===//
404 //  TargetLowering::DAGCombinerInfo implementation
405 //===----------------------------------------------------------------------===//
406
407 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
408   ((DAGCombiner*)DC)->AddToWorkList(N);
409 }
410
411 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
412   ((DAGCombiner*)DC)->removeFromWorkList(N);
413 }
414
415 SDValue TargetLowering::DAGCombinerInfo::
416 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
417   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
418 }
419
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
422   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
423 }
424
425
426 SDValue TargetLowering::DAGCombinerInfo::
427 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
428   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
429 }
430
431 void TargetLowering::DAGCombinerInfo::
432 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
433   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
434 }
435
436 //===----------------------------------------------------------------------===//
437 // Helper Functions
438 //===----------------------------------------------------------------------===//
439
440 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
441 /// specified expression for the same cost as the expression itself, or 2 if we
442 /// can compute the negated form more cheaply than the expression itself.
443 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
444                                const TargetLowering &TLI,
445                                const TargetOptions *Options,
446                                unsigned Depth = 0) {
447   // fneg is removable even if it has multiple uses.
448   if (Op.getOpcode() == ISD::FNEG) return 2;
449
450   // Don't allow anything with multiple uses.
451   if (!Op.hasOneUse()) return 0;
452
453   // Don't recurse exponentially.
454   if (Depth > 6) return 0;
455
456   switch (Op.getOpcode()) {
457   default: return false;
458   case ISD::ConstantFP:
459     // Don't invert constant FP values after legalize.  The negated constant
460     // isn't necessarily legal.
461     return LegalOperations ? 0 : 1;
462   case ISD::FADD:
463     // FIXME: determine better conditions for this xform.
464     if (!Options->UnsafeFPMath) return 0;
465
466     // After operation legalization, it might not be legal to create new FSUBs.
467     if (LegalOperations &&
468         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
469       return 0;
470
471     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
472     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
473                                     Options, Depth + 1))
474       return V;
475     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
476     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
477                               Depth + 1);
478   case ISD::FSUB:
479     // We can't turn -(A-B) into B-A when we honor signed zeros.
480     if (!Options->UnsafeFPMath) return 0;
481
482     // fold (fneg (fsub A, B)) -> (fsub B, A)
483     return 1;
484
485   case ISD::FMUL:
486   case ISD::FDIV:
487     if (Options->HonorSignDependentRoundingFPMath()) return 0;
488
489     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
490     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
491                                     Options, Depth + 1))
492       return V;
493
494     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
495                               Depth + 1);
496
497   case ISD::FP_EXTEND:
498   case ISD::FP_ROUND:
499   case ISD::FSIN:
500     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
501                               Depth + 1);
502   }
503 }
504
505 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
506 /// returns the newly negated expression.
507 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
508                                     bool LegalOperations, unsigned Depth = 0) {
509   // fneg is removable even if it has multiple uses.
510   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
511
512   // Don't allow anything with multiple uses.
513   assert(Op.hasOneUse() && "Unknown reuse!");
514
515   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
516   switch (Op.getOpcode()) {
517   default: llvm_unreachable("Unknown code");
518   case ISD::ConstantFP: {
519     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
520     V.changeSign();
521     return DAG.getConstantFP(V, Op.getValueType());
522   }
523   case ISD::FADD:
524     // FIXME: determine better conditions for this xform.
525     assert(DAG.getTarget().Options.UnsafeFPMath);
526
527     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
528     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
529                            DAG.getTargetLoweringInfo(),
530                            &DAG.getTarget().Options, Depth+1))
531       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
532                          GetNegatedExpression(Op.getOperand(0), DAG,
533                                               LegalOperations, Depth+1),
534                          Op.getOperand(1));
535     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
536     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537                        GetNegatedExpression(Op.getOperand(1), DAG,
538                                             LegalOperations, Depth+1),
539                        Op.getOperand(0));
540   case ISD::FSUB:
541     // We can't turn -(A-B) into B-A when we honor signed zeros.
542     assert(DAG.getTarget().Options.UnsafeFPMath);
543
544     // fold (fneg (fsub 0, B)) -> B
545     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
546       if (N0CFP->getValueAPF().isZero())
547         return Op.getOperand(1);
548
549     // fold (fneg (fsub A, B)) -> (fsub B, A)
550     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551                        Op.getOperand(1), Op.getOperand(0));
552
553   case ISD::FMUL:
554   case ISD::FDIV:
555     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
556
557     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
558     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
559                            DAG.getTargetLoweringInfo(),
560                            &DAG.getTarget().Options, Depth+1))
561       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
562                          GetNegatedExpression(Op.getOperand(0), DAG,
563                                               LegalOperations, Depth+1),
564                          Op.getOperand(1));
565
566     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
567     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
568                        Op.getOperand(0),
569                        GetNegatedExpression(Op.getOperand(1), DAG,
570                                             LegalOperations, Depth+1));
571
572   case ISD::FP_EXTEND:
573   case ISD::FSIN:
574     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
575                        GetNegatedExpression(Op.getOperand(0), DAG,
576                                             LegalOperations, Depth+1));
577   case ISD::FP_ROUND:
578       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
579                          GetNegatedExpression(Op.getOperand(0), DAG,
580                                               LegalOperations, Depth+1),
581                          Op.getOperand(1));
582   }
583 }
584
585 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
586 // that selects between the target values used for true and false, making it
587 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
588 // the appropriate nodes based on the type of node we are checking. This
589 // simplifies life a bit for the callers.
590 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
591                                     SDValue &CC) const {
592   if (N.getOpcode() == ISD::SETCC) {
593     LHS = N.getOperand(0);
594     RHS = N.getOperand(1);
595     CC  = N.getOperand(2);
596     return true;
597   }
598
599   if (N.getOpcode() != ISD::SELECT_CC ||
600       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
601       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
602     return false;
603
604   LHS = N.getOperand(0);
605   RHS = N.getOperand(1);
606   CC  = N.getOperand(4);
607   return true;
608 }
609
610 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
611 // one use.  If this is true, it allows the users to invert the operation for
612 // free when it is profitable to do so.
613 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
614   SDValue N0, N1, N2;
615   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
616     return true;
617   return false;
618 }
619
620 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
621 /// elements are all the same constant or undefined.
622 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
623   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
624   if (!C)
625     return false;
626
627   APInt SplatUndef;
628   unsigned SplatBitSize;
629   bool HasAnyUndefs;
630   EVT EltVT = N->getValueType(0).getVectorElementType();
631   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
632                              HasAnyUndefs) &&
633           EltVT.getSizeInBits() >= SplatBitSize);
634 }
635
636 // \brief Returns the SDNode if it is a constant BuildVector or constant.
637 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638   if (isa<ConstantSDNode>(N))
639     return N.getNode();
640   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641   if(BV && BV->isConstant())
642     return BV;
643   return nullptr;
644 }
645
646 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
647 // int.
648 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
649   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
650     return CN;
651
652   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
653     BitVector UndefElements;
654     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
655
656     // BuildVectors can truncate their operands. Ignore that case here.
657     // FIXME: We blindly ignore splats which include undef which is overly
658     // pessimistic.
659     if (CN && UndefElements.none() &&
660         CN->getValueType(0) == N.getValueType().getScalarType())
661       return CN;
662   }
663
664   return nullptr;
665 }
666
667 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
668                                     SDValue N0, SDValue N1) {
669   EVT VT = N0.getValueType();
670   if (N0.getOpcode() == Opc) {
671     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
672       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
673         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
674         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
675         if (!OpNode.getNode())
676           return SDValue();
677         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
678       }
679       if (N0.hasOneUse()) {
680         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
681         // use
682         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
683         if (!OpNode.getNode())
684           return SDValue();
685         AddToWorkList(OpNode.getNode());
686         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
687       }
688     }
689   }
690
691   if (N1.getOpcode() == Opc) {
692     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
693       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
694         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
695         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
696         if (!OpNode.getNode())
697           return SDValue();
698         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
699       }
700       if (N1.hasOneUse()) {
701         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
702         // use
703         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
704         if (!OpNode.getNode())
705           return SDValue();
706         AddToWorkList(OpNode.getNode());
707         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
708       }
709     }
710   }
711
712   return SDValue();
713 }
714
715 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
716                                bool AddTo) {
717   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
718   ++NodesCombined;
719   DEBUG(dbgs() << "\nReplacing.1 ";
720         N->dump(&DAG);
721         dbgs() << "\nWith: ";
722         To[0].getNode()->dump(&DAG);
723         dbgs() << " and " << NumTo-1 << " other values\n";
724         for (unsigned i = 0, e = NumTo; i != e; ++i)
725           assert((!To[i].getNode() ||
726                   N->getValueType(i) == To[i].getValueType()) &&
727                  "Cannot combine value to value of different type!"));
728   WorkListRemover DeadNodes(*this);
729   DAG.ReplaceAllUsesWith(N, To);
730   if (AddTo) {
731     // Push the new nodes and any users onto the worklist
732     for (unsigned i = 0, e = NumTo; i != e; ++i) {
733       if (To[i].getNode()) {
734         AddToWorkList(To[i].getNode());
735         AddUsersToWorkList(To[i].getNode());
736       }
737     }
738   }
739
740   // Finally, if the node is now dead, remove it from the graph.  The node
741   // may not be dead if the replacement process recursively simplified to
742   // something else needing this node.
743   if (N->use_empty()) {
744     // Nodes can be reintroduced into the worklist.  Make sure we do not
745     // process a node that has been replaced.
746     removeFromWorkList(N);
747
748     // Finally, since the node is now dead, remove it from the graph.
749     DAG.DeleteNode(N);
750   }
751   return SDValue(N, 0);
752 }
753
754 void DAGCombiner::
755 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
756   // Replace all uses.  If any nodes become isomorphic to other nodes and
757   // are deleted, make sure to remove them from our worklist.
758   WorkListRemover DeadNodes(*this);
759   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
760
761   // Push the new node and any (possibly new) users onto the worklist.
762   AddToWorkList(TLO.New.getNode());
763   AddUsersToWorkList(TLO.New.getNode());
764
765   // Finally, if the node is now dead, remove it from the graph.  The node
766   // may not be dead if the replacement process recursively simplified to
767   // something else needing this node.
768   if (TLO.Old.getNode()->use_empty()) {
769     removeFromWorkList(TLO.Old.getNode());
770
771     // If the operands of this node are only used by the node, they will now
772     // be dead.  Make sure to visit them first to delete dead nodes early.
773     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
774       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
775         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
776
777     DAG.DeleteNode(TLO.Old.getNode());
778   }
779 }
780
781 /// SimplifyDemandedBits - Check the specified integer node value to see if
782 /// it can be simplified or if things it uses can be simplified by bit
783 /// propagation.  If so, return true.
784 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
785   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
786   APInt KnownZero, KnownOne;
787   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
788     return false;
789
790   // Revisit the node.
791   AddToWorkList(Op.getNode());
792
793   // Replace the old value with the new one.
794   ++NodesCombined;
795   DEBUG(dbgs() << "\nReplacing.2 ";
796         TLO.Old.getNode()->dump(&DAG);
797         dbgs() << "\nWith: ";
798         TLO.New.getNode()->dump(&DAG);
799         dbgs() << '\n');
800
801   CommitTargetLoweringOpt(TLO);
802   return true;
803 }
804
805 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
806   SDLoc dl(Load);
807   EVT VT = Load->getValueType(0);
808   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
809
810   DEBUG(dbgs() << "\nReplacing.9 ";
811         Load->dump(&DAG);
812         dbgs() << "\nWith: ";
813         Trunc.getNode()->dump(&DAG);
814         dbgs() << '\n');
815   WorkListRemover DeadNodes(*this);
816   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
817   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
818   removeFromWorkList(Load);
819   DAG.DeleteNode(Load);
820   AddToWorkList(Trunc.getNode());
821 }
822
823 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
824   Replace = false;
825   SDLoc dl(Op);
826   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
827     EVT MemVT = LD->getMemoryVT();
828     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
829       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
830                                                   : ISD::EXTLOAD)
831       : LD->getExtensionType();
832     Replace = true;
833     return DAG.getExtLoad(ExtType, dl, PVT,
834                           LD->getChain(), LD->getBasePtr(),
835                           MemVT, LD->getMemOperand());
836   }
837
838   unsigned Opc = Op.getOpcode();
839   switch (Opc) {
840   default: break;
841   case ISD::AssertSext:
842     return DAG.getNode(ISD::AssertSext, dl, PVT,
843                        SExtPromoteOperand(Op.getOperand(0), PVT),
844                        Op.getOperand(1));
845   case ISD::AssertZext:
846     return DAG.getNode(ISD::AssertZext, dl, PVT,
847                        ZExtPromoteOperand(Op.getOperand(0), PVT),
848                        Op.getOperand(1));
849   case ISD::Constant: {
850     unsigned ExtOpc =
851       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
852     return DAG.getNode(ExtOpc, dl, PVT, Op);
853   }
854   }
855
856   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
857     return SDValue();
858   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
859 }
860
861 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
862   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
863     return SDValue();
864   EVT OldVT = Op.getValueType();
865   SDLoc dl(Op);
866   bool Replace = false;
867   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
868   if (!NewOp.getNode())
869     return SDValue();
870   AddToWorkList(NewOp.getNode());
871
872   if (Replace)
873     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
874   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
875                      DAG.getValueType(OldVT));
876 }
877
878 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
879   EVT OldVT = Op.getValueType();
880   SDLoc dl(Op);
881   bool Replace = false;
882   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
883   if (!NewOp.getNode())
884     return SDValue();
885   AddToWorkList(NewOp.getNode());
886
887   if (Replace)
888     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
889   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
890 }
891
892 /// PromoteIntBinOp - Promote the specified integer binary operation if the
893 /// target indicates it is beneficial. e.g. On x86, it's usually better to
894 /// promote i16 operations to i32 since i16 instructions are longer.
895 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
896   if (!LegalOperations)
897     return SDValue();
898
899   EVT VT = Op.getValueType();
900   if (VT.isVector() || !VT.isInteger())
901     return SDValue();
902
903   // If operation type is 'undesirable', e.g. i16 on x86, consider
904   // promoting it.
905   unsigned Opc = Op.getOpcode();
906   if (TLI.isTypeDesirableForOp(Opc, VT))
907     return SDValue();
908
909   EVT PVT = VT;
910   // Consult target whether it is a good idea to promote this operation and
911   // what's the right type to promote it to.
912   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
913     assert(PVT != VT && "Don't know what type to promote to!");
914
915     bool Replace0 = false;
916     SDValue N0 = Op.getOperand(0);
917     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
918     if (!NN0.getNode())
919       return SDValue();
920
921     bool Replace1 = false;
922     SDValue N1 = Op.getOperand(1);
923     SDValue NN1;
924     if (N0 == N1)
925       NN1 = NN0;
926     else {
927       NN1 = PromoteOperand(N1, PVT, Replace1);
928       if (!NN1.getNode())
929         return SDValue();
930     }
931
932     AddToWorkList(NN0.getNode());
933     if (NN1.getNode())
934       AddToWorkList(NN1.getNode());
935
936     if (Replace0)
937       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
938     if (Replace1)
939       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
940
941     DEBUG(dbgs() << "\nPromoting ";
942           Op.getNode()->dump(&DAG));
943     SDLoc dl(Op);
944     return DAG.getNode(ISD::TRUNCATE, dl, VT,
945                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
946   }
947   return SDValue();
948 }
949
950 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
951 /// target indicates it is beneficial. e.g. On x86, it's usually better to
952 /// promote i16 operations to i32 since i16 instructions are longer.
953 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
954   if (!LegalOperations)
955     return SDValue();
956
957   EVT VT = Op.getValueType();
958   if (VT.isVector() || !VT.isInteger())
959     return SDValue();
960
961   // If operation type is 'undesirable', e.g. i16 on x86, consider
962   // promoting it.
963   unsigned Opc = Op.getOpcode();
964   if (TLI.isTypeDesirableForOp(Opc, VT))
965     return SDValue();
966
967   EVT PVT = VT;
968   // Consult target whether it is a good idea to promote this operation and
969   // what's the right type to promote it to.
970   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
971     assert(PVT != VT && "Don't know what type to promote to!");
972
973     bool Replace = false;
974     SDValue N0 = Op.getOperand(0);
975     if (Opc == ISD::SRA)
976       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
977     else if (Opc == ISD::SRL)
978       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
979     else
980       N0 = PromoteOperand(N0, PVT, Replace);
981     if (!N0.getNode())
982       return SDValue();
983
984     AddToWorkList(N0.getNode());
985     if (Replace)
986       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
987
988     DEBUG(dbgs() << "\nPromoting ";
989           Op.getNode()->dump(&DAG));
990     SDLoc dl(Op);
991     return DAG.getNode(ISD::TRUNCATE, dl, VT,
992                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
993   }
994   return SDValue();
995 }
996
997 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
998   if (!LegalOperations)
999     return SDValue();
1000
1001   EVT VT = Op.getValueType();
1002   if (VT.isVector() || !VT.isInteger())
1003     return SDValue();
1004
1005   // If operation type is 'undesirable', e.g. i16 on x86, consider
1006   // promoting it.
1007   unsigned Opc = Op.getOpcode();
1008   if (TLI.isTypeDesirableForOp(Opc, VT))
1009     return SDValue();
1010
1011   EVT PVT = VT;
1012   // Consult target whether it is a good idea to promote this operation and
1013   // what's the right type to promote it to.
1014   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015     assert(PVT != VT && "Don't know what type to promote to!");
1016     // fold (aext (aext x)) -> (aext x)
1017     // fold (aext (zext x)) -> (zext x)
1018     // fold (aext (sext x)) -> (sext x)
1019     DEBUG(dbgs() << "\nPromoting ";
1020           Op.getNode()->dump(&DAG));
1021     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1022   }
1023   return SDValue();
1024 }
1025
1026 bool DAGCombiner::PromoteLoad(SDValue Op) {
1027   if (!LegalOperations)
1028     return false;
1029
1030   EVT VT = Op.getValueType();
1031   if (VT.isVector() || !VT.isInteger())
1032     return false;
1033
1034   // If operation type is 'undesirable', e.g. i16 on x86, consider
1035   // promoting it.
1036   unsigned Opc = Op.getOpcode();
1037   if (TLI.isTypeDesirableForOp(Opc, VT))
1038     return false;
1039
1040   EVT PVT = VT;
1041   // Consult target whether it is a good idea to promote this operation and
1042   // what's the right type to promote it to.
1043   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1044     assert(PVT != VT && "Don't know what type to promote to!");
1045
1046     SDLoc dl(Op);
1047     SDNode *N = Op.getNode();
1048     LoadSDNode *LD = cast<LoadSDNode>(N);
1049     EVT MemVT = LD->getMemoryVT();
1050     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1051       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1052                                                   : ISD::EXTLOAD)
1053       : LD->getExtensionType();
1054     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1055                                    LD->getChain(), LD->getBasePtr(),
1056                                    MemVT, LD->getMemOperand());
1057     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1058
1059     DEBUG(dbgs() << "\nPromoting ";
1060           N->dump(&DAG);
1061           dbgs() << "\nTo: ";
1062           Result.getNode()->dump(&DAG);
1063           dbgs() << '\n');
1064     WorkListRemover DeadNodes(*this);
1065     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1066     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1067     removeFromWorkList(N);
1068     DAG.DeleteNode(N);
1069     AddToWorkList(Result.getNode());
1070     return true;
1071   }
1072   return false;
1073 }
1074
1075
1076 //===----------------------------------------------------------------------===//
1077 //  Main DAG Combiner implementation
1078 //===----------------------------------------------------------------------===//
1079
1080 void DAGCombiner::Run(CombineLevel AtLevel) {
1081   // set the instance variables, so that the various visit routines may use it.
1082   Level = AtLevel;
1083   LegalOperations = Level >= AfterLegalizeVectorOps;
1084   LegalTypes = Level >= AfterLegalizeTypes;
1085
1086   // Add all the dag nodes to the worklist.
1087   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1088        E = DAG.allnodes_end(); I != E; ++I)
1089     AddToWorkList(I);
1090
1091   // Create a dummy node (which is not added to allnodes), that adds a reference
1092   // to the root node, preventing it from being deleted, and tracking any
1093   // changes of the root.
1094   HandleSDNode Dummy(DAG.getRoot());
1095
1096   // The root of the dag may dangle to deleted nodes until the dag combiner is
1097   // done.  Set it to null to avoid confusion.
1098   DAG.setRoot(SDValue());
1099
1100   // while the worklist isn't empty, find a node and
1101   // try and combine it.
1102   while (!WorkListContents.empty()) {
1103     SDNode *N;
1104     // The WorkListOrder holds the SDNodes in order, but it may contain
1105     // duplicates.
1106     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1107     // worklist *should* contain, and check the node we want to visit is should
1108     // actually be visited.
1109     do {
1110       N = WorkListOrder.pop_back_val();
1111     } while (!WorkListContents.erase(N));
1112
1113     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1114     // N is deleted from the DAG, since they too may now be dead or may have a
1115     // reduced number of uses, allowing other xforms.
1116     if (N->use_empty()) {
1117       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1118         AddToWorkList(N->getOperand(i).getNode());
1119
1120       DAG.DeleteNode(N);
1121       continue;
1122     }
1123
1124     SDValue RV = combine(N);
1125
1126     if (!RV.getNode())
1127       continue;
1128
1129     ++NodesCombined;
1130
1131     // If we get back the same node we passed in, rather than a new node or
1132     // zero, we know that the node must have defined multiple values and
1133     // CombineTo was used.  Since CombineTo takes care of the worklist
1134     // mechanics for us, we have no work to do in this case.
1135     if (RV.getNode() == N)
1136       continue;
1137
1138     assert(N->getOpcode() != ISD::DELETED_NODE &&
1139            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1140            "Node was deleted but visit returned new node!");
1141
1142     DEBUG(dbgs() << "\nReplacing.3 ";
1143           N->dump(&DAG);
1144           dbgs() << "\nWith: ";
1145           RV.getNode()->dump(&DAG);
1146           dbgs() << '\n');
1147
1148     // Transfer debug value.
1149     DAG.TransferDbgValues(SDValue(N, 0), RV);
1150     WorkListRemover DeadNodes(*this);
1151     if (N->getNumValues() == RV.getNode()->getNumValues())
1152       DAG.ReplaceAllUsesWith(N, RV.getNode());
1153     else {
1154       assert(N->getValueType(0) == RV.getValueType() &&
1155              N->getNumValues() == 1 && "Type mismatch");
1156       SDValue OpV = RV;
1157       DAG.ReplaceAllUsesWith(N, &OpV);
1158     }
1159
1160     // Push the new node and any users onto the worklist
1161     AddToWorkList(RV.getNode());
1162     AddUsersToWorkList(RV.getNode());
1163
1164     // Add any uses of the old node to the worklist in case this node is the
1165     // last one that uses them.  They may become dead after this node is
1166     // deleted.
1167     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1168       AddToWorkList(N->getOperand(i).getNode());
1169
1170     // Finally, if the node is now dead, remove it from the graph.  The node
1171     // may not be dead if the replacement process recursively simplified to
1172     // something else needing this node.
1173     if (N->use_empty()) {
1174       // Nodes can be reintroduced into the worklist.  Make sure we do not
1175       // process a node that has been replaced.
1176       removeFromWorkList(N);
1177
1178       // Finally, since the node is now dead, remove it from the graph.
1179       DAG.DeleteNode(N);
1180     }
1181   }
1182
1183   // If the root changed (e.g. it was a dead load, update the root).
1184   DAG.setRoot(Dummy.getValue());
1185   DAG.RemoveDeadNodes();
1186 }
1187
1188 SDValue DAGCombiner::visit(SDNode *N) {
1189   switch (N->getOpcode()) {
1190   default: break;
1191   case ISD::TokenFactor:        return visitTokenFactor(N);
1192   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1193   case ISD::ADD:                return visitADD(N);
1194   case ISD::SUB:                return visitSUB(N);
1195   case ISD::ADDC:               return visitADDC(N);
1196   case ISD::SUBC:               return visitSUBC(N);
1197   case ISD::ADDE:               return visitADDE(N);
1198   case ISD::SUBE:               return visitSUBE(N);
1199   case ISD::MUL:                return visitMUL(N);
1200   case ISD::SDIV:               return visitSDIV(N);
1201   case ISD::UDIV:               return visitUDIV(N);
1202   case ISD::SREM:               return visitSREM(N);
1203   case ISD::UREM:               return visitUREM(N);
1204   case ISD::MULHU:              return visitMULHU(N);
1205   case ISD::MULHS:              return visitMULHS(N);
1206   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1207   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1208   case ISD::SMULO:              return visitSMULO(N);
1209   case ISD::UMULO:              return visitUMULO(N);
1210   case ISD::SDIVREM:            return visitSDIVREM(N);
1211   case ISD::UDIVREM:            return visitUDIVREM(N);
1212   case ISD::AND:                return visitAND(N);
1213   case ISD::OR:                 return visitOR(N);
1214   case ISD::XOR:                return visitXOR(N);
1215   case ISD::SHL:                return visitSHL(N);
1216   case ISD::SRA:                return visitSRA(N);
1217   case ISD::SRL:                return visitSRL(N);
1218   case ISD::ROTR:
1219   case ISD::ROTL:               return visitRotate(N);
1220   case ISD::CTLZ:               return visitCTLZ(N);
1221   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1222   case ISD::CTTZ:               return visitCTTZ(N);
1223   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1224   case ISD::CTPOP:              return visitCTPOP(N);
1225   case ISD::SELECT:             return visitSELECT(N);
1226   case ISD::VSELECT:            return visitVSELECT(N);
1227   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1228   case ISD::SETCC:              return visitSETCC(N);
1229   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1230   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1231   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1232   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1233   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1234   case ISD::BITCAST:            return visitBITCAST(N);
1235   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1236   case ISD::FADD:               return visitFADD(N);
1237   case ISD::FSUB:               return visitFSUB(N);
1238   case ISD::FMUL:               return visitFMUL(N);
1239   case ISD::FMA:                return visitFMA(N);
1240   case ISD::FDIV:               return visitFDIV(N);
1241   case ISD::FREM:               return visitFREM(N);
1242   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1243   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1244   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1245   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1246   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1247   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1248   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1249   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1250   case ISD::FNEG:               return visitFNEG(N);
1251   case ISD::FABS:               return visitFABS(N);
1252   case ISD::FFLOOR:             return visitFFLOOR(N);
1253   case ISD::FCEIL:              return visitFCEIL(N);
1254   case ISD::FTRUNC:             return visitFTRUNC(N);
1255   case ISD::BRCOND:             return visitBRCOND(N);
1256   case ISD::BR_CC:              return visitBR_CC(N);
1257   case ISD::LOAD:               return visitLOAD(N);
1258   case ISD::STORE:              return visitSTORE(N);
1259   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1260   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1261   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1262   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1263   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1264   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1265   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1266   }
1267   return SDValue();
1268 }
1269
1270 SDValue DAGCombiner::combine(SDNode *N) {
1271   SDValue RV = visit(N);
1272
1273   // If nothing happened, try a target-specific DAG combine.
1274   if (!RV.getNode()) {
1275     assert(N->getOpcode() != ISD::DELETED_NODE &&
1276            "Node was deleted but visit returned NULL!");
1277
1278     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1279         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1280
1281       // Expose the DAG combiner to the target combiner impls.
1282       TargetLowering::DAGCombinerInfo
1283         DagCombineInfo(DAG, Level, false, this);
1284
1285       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1286     }
1287   }
1288
1289   // If nothing happened still, try promoting the operation.
1290   if (!RV.getNode()) {
1291     switch (N->getOpcode()) {
1292     default: break;
1293     case ISD::ADD:
1294     case ISD::SUB:
1295     case ISD::MUL:
1296     case ISD::AND:
1297     case ISD::OR:
1298     case ISD::XOR:
1299       RV = PromoteIntBinOp(SDValue(N, 0));
1300       break;
1301     case ISD::SHL:
1302     case ISD::SRA:
1303     case ISD::SRL:
1304       RV = PromoteIntShiftOp(SDValue(N, 0));
1305       break;
1306     case ISD::SIGN_EXTEND:
1307     case ISD::ZERO_EXTEND:
1308     case ISD::ANY_EXTEND:
1309       RV = PromoteExtend(SDValue(N, 0));
1310       break;
1311     case ISD::LOAD:
1312       if (PromoteLoad(SDValue(N, 0)))
1313         RV = SDValue(N, 0);
1314       break;
1315     }
1316   }
1317
1318   // If N is a commutative binary node, try commuting it to enable more
1319   // sdisel CSE.
1320   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1321       N->getNumValues() == 1) {
1322     SDValue N0 = N->getOperand(0);
1323     SDValue N1 = N->getOperand(1);
1324
1325     // Constant operands are canonicalized to RHS.
1326     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1327       SDValue Ops[] = {N1, N0};
1328       SDNode *CSENode;
1329       if (const BinaryWithFlagsSDNode *BinNode =
1330               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1331         CSENode = DAG.getNodeIfExists(
1332             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1333             BinNode->hasNoSignedWrap(), BinNode->isExact());
1334       } else {
1335         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1336       }
1337       if (CSENode)
1338         return SDValue(CSENode, 0);
1339     }
1340   }
1341
1342   return RV;
1343 }
1344
1345 /// getInputChainForNode - Given a node, return its input chain if it has one,
1346 /// otherwise return a null sd operand.
1347 static SDValue getInputChainForNode(SDNode *N) {
1348   if (unsigned NumOps = N->getNumOperands()) {
1349     if (N->getOperand(0).getValueType() == MVT::Other)
1350       return N->getOperand(0);
1351     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1352       return N->getOperand(NumOps-1);
1353     for (unsigned i = 1; i < NumOps-1; ++i)
1354       if (N->getOperand(i).getValueType() == MVT::Other)
1355         return N->getOperand(i);
1356   }
1357   return SDValue();
1358 }
1359
1360 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1361   // If N has two operands, where one has an input chain equal to the other,
1362   // the 'other' chain is redundant.
1363   if (N->getNumOperands() == 2) {
1364     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1365       return N->getOperand(0);
1366     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1367       return N->getOperand(1);
1368   }
1369
1370   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1371   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1372   SmallPtrSet<SDNode*, 16> SeenOps;
1373   bool Changed = false;             // If we should replace this token factor.
1374
1375   // Start out with this token factor.
1376   TFs.push_back(N);
1377
1378   // Iterate through token factors.  The TFs grows when new token factors are
1379   // encountered.
1380   for (unsigned i = 0; i < TFs.size(); ++i) {
1381     SDNode *TF = TFs[i];
1382
1383     // Check each of the operands.
1384     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1385       SDValue Op = TF->getOperand(i);
1386
1387       switch (Op.getOpcode()) {
1388       case ISD::EntryToken:
1389         // Entry tokens don't need to be added to the list. They are
1390         // rededundant.
1391         Changed = true;
1392         break;
1393
1394       case ISD::TokenFactor:
1395         if (Op.hasOneUse() &&
1396             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1397           // Queue up for processing.
1398           TFs.push_back(Op.getNode());
1399           // Clean up in case the token factor is removed.
1400           AddToWorkList(Op.getNode());
1401           Changed = true;
1402           break;
1403         }
1404         // Fall thru
1405
1406       default:
1407         // Only add if it isn't already in the list.
1408         if (SeenOps.insert(Op.getNode()))
1409           Ops.push_back(Op);
1410         else
1411           Changed = true;
1412         break;
1413       }
1414     }
1415   }
1416
1417   SDValue Result;
1418
1419   // If we've change things around then replace token factor.
1420   if (Changed) {
1421     if (Ops.empty()) {
1422       // The entry token is the only possible outcome.
1423       Result = DAG.getEntryNode();
1424     } else {
1425       // New and improved token factor.
1426       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1427     }
1428
1429     // Don't add users to work list.
1430     return CombineTo(N, Result, false);
1431   }
1432
1433   return Result;
1434 }
1435
1436 /// MERGE_VALUES can always be eliminated.
1437 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1438   WorkListRemover DeadNodes(*this);
1439   // Replacing results may cause a different MERGE_VALUES to suddenly
1440   // be CSE'd with N, and carry its uses with it. Iterate until no
1441   // uses remain, to ensure that the node can be safely deleted.
1442   // First add the users of this node to the work list so that they
1443   // can be tried again once they have new operands.
1444   AddUsersToWorkList(N);
1445   do {
1446     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1447       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1448   } while (!N->use_empty());
1449   removeFromWorkList(N);
1450   DAG.DeleteNode(N);
1451   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1452 }
1453
1454 static
1455 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1456                               SelectionDAG &DAG) {
1457   EVT VT = N0.getValueType();
1458   SDValue N00 = N0.getOperand(0);
1459   SDValue N01 = N0.getOperand(1);
1460   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1461
1462   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1463       isa<ConstantSDNode>(N00.getOperand(1))) {
1464     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1465     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1466                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1467                                  N00.getOperand(0), N01),
1468                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1469                                  N00.getOperand(1), N01));
1470     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1471   }
1472
1473   return SDValue();
1474 }
1475
1476 SDValue DAGCombiner::visitADD(SDNode *N) {
1477   SDValue N0 = N->getOperand(0);
1478   SDValue N1 = N->getOperand(1);
1479   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1480   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1481   EVT VT = N0.getValueType();
1482
1483   // fold vector ops
1484   if (VT.isVector()) {
1485     SDValue FoldedVOp = SimplifyVBinOp(N);
1486     if (FoldedVOp.getNode()) return FoldedVOp;
1487
1488     // fold (add x, 0) -> x, vector edition
1489     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1490       return N0;
1491     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1492       return N1;
1493   }
1494
1495   // fold (add x, undef) -> undef
1496   if (N0.getOpcode() == ISD::UNDEF)
1497     return N0;
1498   if (N1.getOpcode() == ISD::UNDEF)
1499     return N1;
1500   // fold (add c1, c2) -> c1+c2
1501   if (N0C && N1C)
1502     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1503   // canonicalize constant to RHS
1504   if (N0C && !N1C)
1505     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1506   // fold (add x, 0) -> x
1507   if (N1C && N1C->isNullValue())
1508     return N0;
1509   // fold (add Sym, c) -> Sym+c
1510   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1511     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1512         GA->getOpcode() == ISD::GlobalAddress)
1513       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1514                                   GA->getOffset() +
1515                                     (uint64_t)N1C->getSExtValue());
1516   // fold ((c1-A)+c2) -> (c1+c2)-A
1517   if (N1C && N0.getOpcode() == ISD::SUB)
1518     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1519       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1520                          DAG.getConstant(N1C->getAPIntValue()+
1521                                          N0C->getAPIntValue(), VT),
1522                          N0.getOperand(1));
1523   // reassociate add
1524   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1525   if (RADD.getNode())
1526     return RADD;
1527   // fold ((0-A) + B) -> B-A
1528   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1529       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1530     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1531   // fold (A + (0-B)) -> A-B
1532   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1533       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1534     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1535   // fold (A+(B-A)) -> B
1536   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1537     return N1.getOperand(0);
1538   // fold ((B-A)+A) -> B
1539   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1540     return N0.getOperand(0);
1541   // fold (A+(B-(A+C))) to (B-C)
1542   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1543       N0 == N1.getOperand(1).getOperand(0))
1544     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1545                        N1.getOperand(1).getOperand(1));
1546   // fold (A+(B-(C+A))) to (B-C)
1547   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1548       N0 == N1.getOperand(1).getOperand(1))
1549     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1550                        N1.getOperand(1).getOperand(0));
1551   // fold (A+((B-A)+or-C)) to (B+or-C)
1552   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1553       N1.getOperand(0).getOpcode() == ISD::SUB &&
1554       N0 == N1.getOperand(0).getOperand(1))
1555     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1556                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1557
1558   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1559   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1560     SDValue N00 = N0.getOperand(0);
1561     SDValue N01 = N0.getOperand(1);
1562     SDValue N10 = N1.getOperand(0);
1563     SDValue N11 = N1.getOperand(1);
1564
1565     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1566       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1567                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1568                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1569   }
1570
1571   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1572     return SDValue(N, 0);
1573
1574   // fold (a+b) -> (a|b) iff a and b share no bits.
1575   if (VT.isInteger() && !VT.isVector()) {
1576     APInt LHSZero, LHSOne;
1577     APInt RHSZero, RHSOne;
1578     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1579
1580     if (LHSZero.getBoolValue()) {
1581       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1582
1583       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1584       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1585       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1586         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1587           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1588       }
1589     }
1590   }
1591
1592   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1593   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1594     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1595     if (Result.getNode()) return Result;
1596   }
1597   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1598     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1599     if (Result.getNode()) return Result;
1600   }
1601
1602   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1603   if (N1.getOpcode() == ISD::SHL &&
1604       N1.getOperand(0).getOpcode() == ISD::SUB)
1605     if (ConstantSDNode *C =
1606           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1607       if (C->getAPIntValue() == 0)
1608         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1609                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1610                                        N1.getOperand(0).getOperand(1),
1611                                        N1.getOperand(1)));
1612   if (N0.getOpcode() == ISD::SHL &&
1613       N0.getOperand(0).getOpcode() == ISD::SUB)
1614     if (ConstantSDNode *C =
1615           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1616       if (C->getAPIntValue() == 0)
1617         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1618                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1619                                        N0.getOperand(0).getOperand(1),
1620                                        N0.getOperand(1)));
1621
1622   if (N1.getOpcode() == ISD::AND) {
1623     SDValue AndOp0 = N1.getOperand(0);
1624     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1625     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1626     unsigned DestBits = VT.getScalarType().getSizeInBits();
1627
1628     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1629     // and similar xforms where the inner op is either ~0 or 0.
1630     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1631       SDLoc DL(N);
1632       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1633     }
1634   }
1635
1636   // add (sext i1), X -> sub X, (zext i1)
1637   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1638       N0.getOperand(0).getValueType() == MVT::i1 &&
1639       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1640     SDLoc DL(N);
1641     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1642     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1643   }
1644
1645   return SDValue();
1646 }
1647
1648 SDValue DAGCombiner::visitADDC(SDNode *N) {
1649   SDValue N0 = N->getOperand(0);
1650   SDValue N1 = N->getOperand(1);
1651   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1652   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1653   EVT VT = N0.getValueType();
1654
1655   // If the flag result is dead, turn this into an ADD.
1656   if (!N->hasAnyUseOfValue(1))
1657     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1658                      DAG.getNode(ISD::CARRY_FALSE,
1659                                  SDLoc(N), MVT::Glue));
1660
1661   // canonicalize constant to RHS.
1662   if (N0C && !N1C)
1663     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1664
1665   // fold (addc x, 0) -> x + no carry out
1666   if (N1C && N1C->isNullValue())
1667     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1668                                         SDLoc(N), MVT::Glue));
1669
1670   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1671   APInt LHSZero, LHSOne;
1672   APInt RHSZero, RHSOne;
1673   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1674
1675   if (LHSZero.getBoolValue()) {
1676     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1677
1678     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1679     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1680     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1681       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1682                        DAG.getNode(ISD::CARRY_FALSE,
1683                                    SDLoc(N), MVT::Glue));
1684   }
1685
1686   return SDValue();
1687 }
1688
1689 SDValue DAGCombiner::visitADDE(SDNode *N) {
1690   SDValue N0 = N->getOperand(0);
1691   SDValue N1 = N->getOperand(1);
1692   SDValue CarryIn = N->getOperand(2);
1693   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1694   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1695
1696   // canonicalize constant to RHS
1697   if (N0C && !N1C)
1698     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1699                        N1, N0, CarryIn);
1700
1701   // fold (adde x, y, false) -> (addc x, y)
1702   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1703     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1704
1705   return SDValue();
1706 }
1707
1708 // Since it may not be valid to emit a fold to zero for vector initializers
1709 // check if we can before folding.
1710 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1711                              SelectionDAG &DAG,
1712                              bool LegalOperations, bool LegalTypes) {
1713   if (!VT.isVector())
1714     return DAG.getConstant(0, VT);
1715   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1716     return DAG.getConstant(0, VT);
1717   return SDValue();
1718 }
1719
1720 SDValue DAGCombiner::visitSUB(SDNode *N) {
1721   SDValue N0 = N->getOperand(0);
1722   SDValue N1 = N->getOperand(1);
1723   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1724   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1725   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1726     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1727   EVT VT = N0.getValueType();
1728
1729   // fold vector ops
1730   if (VT.isVector()) {
1731     SDValue FoldedVOp = SimplifyVBinOp(N);
1732     if (FoldedVOp.getNode()) return FoldedVOp;
1733
1734     // fold (sub x, 0) -> x, vector edition
1735     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1736       return N0;
1737   }
1738
1739   // fold (sub x, x) -> 0
1740   // FIXME: Refactor this and xor and other similar operations together.
1741   if (N0 == N1)
1742     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1743   // fold (sub c1, c2) -> c1-c2
1744   if (N0C && N1C)
1745     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1746   // fold (sub x, c) -> (add x, -c)
1747   if (N1C)
1748     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1749                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1750   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1751   if (N0C && N0C->isAllOnesValue())
1752     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1753   // fold A-(A-B) -> B
1754   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1755     return N1.getOperand(1);
1756   // fold (A+B)-A -> B
1757   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1758     return N0.getOperand(1);
1759   // fold (A+B)-B -> A
1760   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1761     return N0.getOperand(0);
1762   // fold C2-(A+C1) -> (C2-C1)-A
1763   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1764     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1765                                    VT);
1766     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1767                        N1.getOperand(0));
1768   }
1769   // fold ((A+(B+or-C))-B) -> A+or-C
1770   if (N0.getOpcode() == ISD::ADD &&
1771       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1772        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1773       N0.getOperand(1).getOperand(0) == N1)
1774     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1775                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1776   // fold ((A+(C+B))-B) -> A+C
1777   if (N0.getOpcode() == ISD::ADD &&
1778       N0.getOperand(1).getOpcode() == ISD::ADD &&
1779       N0.getOperand(1).getOperand(1) == N1)
1780     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1781                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1782   // fold ((A-(B-C))-C) -> A-B
1783   if (N0.getOpcode() == ISD::SUB &&
1784       N0.getOperand(1).getOpcode() == ISD::SUB &&
1785       N0.getOperand(1).getOperand(1) == N1)
1786     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1787                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1788
1789   // If either operand of a sub is undef, the result is undef
1790   if (N0.getOpcode() == ISD::UNDEF)
1791     return N0;
1792   if (N1.getOpcode() == ISD::UNDEF)
1793     return N1;
1794
1795   // If the relocation model supports it, consider symbol offsets.
1796   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1797     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1798       // fold (sub Sym, c) -> Sym-c
1799       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1800         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1801                                     GA->getOffset() -
1802                                       (uint64_t)N1C->getSExtValue());
1803       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1804       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1805         if (GA->getGlobal() == GB->getGlobal())
1806           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1807                                  VT);
1808     }
1809
1810   return SDValue();
1811 }
1812
1813 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1814   SDValue N0 = N->getOperand(0);
1815   SDValue N1 = N->getOperand(1);
1816   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1817   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1818   EVT VT = N0.getValueType();
1819
1820   // If the flag result is dead, turn this into an SUB.
1821   if (!N->hasAnyUseOfValue(1))
1822     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1823                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1824                                  MVT::Glue));
1825
1826   // fold (subc x, x) -> 0 + no borrow
1827   if (N0 == N1)
1828     return CombineTo(N, DAG.getConstant(0, VT),
1829                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1830                                  MVT::Glue));
1831
1832   // fold (subc x, 0) -> x + no borrow
1833   if (N1C && N1C->isNullValue())
1834     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1835                                         MVT::Glue));
1836
1837   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1838   if (N0C && N0C->isAllOnesValue())
1839     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1840                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1841                                  MVT::Glue));
1842
1843   return SDValue();
1844 }
1845
1846 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1847   SDValue N0 = N->getOperand(0);
1848   SDValue N1 = N->getOperand(1);
1849   SDValue CarryIn = N->getOperand(2);
1850
1851   // fold (sube x, y, false) -> (subc x, y)
1852   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1853     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1854
1855   return SDValue();
1856 }
1857
1858 SDValue DAGCombiner::visitMUL(SDNode *N) {
1859   SDValue N0 = N->getOperand(0);
1860   SDValue N1 = N->getOperand(1);
1861   EVT VT = N0.getValueType();
1862
1863   // fold (mul x, undef) -> 0
1864   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1865     return DAG.getConstant(0, VT);
1866
1867   bool N0IsConst = false;
1868   bool N1IsConst = false;
1869   APInt ConstValue0, ConstValue1;
1870   // fold vector ops
1871   if (VT.isVector()) {
1872     SDValue FoldedVOp = SimplifyVBinOp(N);
1873     if (FoldedVOp.getNode()) return FoldedVOp;
1874
1875     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1876     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1877   } else {
1878     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1879     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1880                             : APInt();
1881     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1882     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1883                             : APInt();
1884   }
1885
1886   // fold (mul c1, c2) -> c1*c2
1887   if (N0IsConst && N1IsConst)
1888     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1889
1890   // canonicalize constant to RHS
1891   if (N0IsConst && !N1IsConst)
1892     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1893   // fold (mul x, 0) -> 0
1894   if (N1IsConst && ConstValue1 == 0)
1895     return N1;
1896   // We require a splat of the entire scalar bit width for non-contiguous
1897   // bit patterns.
1898   bool IsFullSplat =
1899     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1900   // fold (mul x, 1) -> x
1901   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1902     return N0;
1903   // fold (mul x, -1) -> 0-x
1904   if (N1IsConst && ConstValue1.isAllOnesValue())
1905     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906                        DAG.getConstant(0, VT), N0);
1907   // fold (mul x, (1 << c)) -> x << c
1908   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1909     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1910                        DAG.getConstant(ConstValue1.logBase2(),
1911                                        getShiftAmountTy(N0.getValueType())));
1912   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1913   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1914     unsigned Log2Val = (-ConstValue1).logBase2();
1915     // FIXME: If the input is something that is easily negated (e.g. a
1916     // single-use add), we should put the negate there.
1917     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1918                        DAG.getConstant(0, VT),
1919                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1920                             DAG.getConstant(Log2Val,
1921                                       getShiftAmountTy(N0.getValueType()))));
1922   }
1923
1924   APInt Val;
1925   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1926   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1927       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1928                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1929     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1930                              N1, N0.getOperand(1));
1931     AddToWorkList(C3.getNode());
1932     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933                        N0.getOperand(0), C3);
1934   }
1935
1936   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1937   // use.
1938   {
1939     SDValue Sh(nullptr,0), Y(nullptr,0);
1940     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1941     if (N0.getOpcode() == ISD::SHL &&
1942         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1943                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1944         N0.getNode()->hasOneUse()) {
1945       Sh = N0; Y = N1;
1946     } else if (N1.getOpcode() == ISD::SHL &&
1947                isa<ConstantSDNode>(N1.getOperand(1)) &&
1948                N1.getNode()->hasOneUse()) {
1949       Sh = N1; Y = N0;
1950     }
1951
1952     if (Sh.getNode()) {
1953       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1954                                 Sh.getOperand(0), Y);
1955       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1956                          Mul, Sh.getOperand(1));
1957     }
1958   }
1959
1960   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1961   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1962       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1963                      isa<ConstantSDNode>(N0.getOperand(1))))
1964     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1965                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1966                                    N0.getOperand(0), N1),
1967                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1968                                    N0.getOperand(1), N1));
1969
1970   // reassociate mul
1971   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1972   if (RMUL.getNode())
1973     return RMUL;
1974
1975   return SDValue();
1976 }
1977
1978 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1979   SDValue N0 = N->getOperand(0);
1980   SDValue N1 = N->getOperand(1);
1981   ConstantSDNode *N0C = isConstOrConstSplat(N0);
1982   ConstantSDNode *N1C = isConstOrConstSplat(N1);
1983   EVT VT = N->getValueType(0);
1984
1985   // fold vector ops
1986   if (VT.isVector()) {
1987     SDValue FoldedVOp = SimplifyVBinOp(N);
1988     if (FoldedVOp.getNode()) return FoldedVOp;
1989   }
1990
1991   // fold (sdiv c1, c2) -> c1/c2
1992   if (N0C && N1C && !N1C->isNullValue())
1993     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1994   // fold (sdiv X, 1) -> X
1995   if (N1C && N1C->getAPIntValue() == 1LL)
1996     return N0;
1997   // fold (sdiv X, -1) -> 0-X
1998   if (N1C && N1C->isAllOnesValue())
1999     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000                        DAG.getConstant(0, VT), N0);
2001   // If we know the sign bits of both operands are zero, strength reduce to a
2002   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2003   if (!VT.isVector()) {
2004     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2005       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2006                          N0, N1);
2007   }
2008
2009   // fold (sdiv X, pow2) -> simple ops after legalize
2010   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2011                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2012     // If dividing by powers of two is cheap, then don't perform the following
2013     // fold.
2014     if (TLI.isPow2DivCheap())
2015       return SDValue();
2016
2017     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2018
2019     // Splat the sign bit into the register
2020     SDValue SGN =
2021         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2022                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2023                                     getShiftAmountTy(N0.getValueType())));
2024     AddToWorkList(SGN.getNode());
2025
2026     // Add (N0 < 0) ? abs2 - 1 : 0;
2027     SDValue SRL =
2028         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2029                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2030                                     getShiftAmountTy(SGN.getValueType())));
2031     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2032     AddToWorkList(SRL.getNode());
2033     AddToWorkList(ADD.getNode());    // Divide by pow2
2034     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2035                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2036
2037     // If we're dividing by a positive value, we're done.  Otherwise, we must
2038     // negate the result.
2039     if (N1C->getAPIntValue().isNonNegative())
2040       return SRA;
2041
2042     AddToWorkList(SRA.getNode());
2043     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2044   }
2045
2046   // if integer divide is expensive and we satisfy the requirements, emit an
2047   // alternate sequence.
2048   if (N1C && !TLI.isIntDivCheap()) {
2049     SDValue Op = BuildSDIV(N);
2050     if (Op.getNode()) return Op;
2051   }
2052
2053   // undef / X -> 0
2054   if (N0.getOpcode() == ISD::UNDEF)
2055     return DAG.getConstant(0, VT);
2056   // X / undef -> undef
2057   if (N1.getOpcode() == ISD::UNDEF)
2058     return N1;
2059
2060   return SDValue();
2061 }
2062
2063 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2064   SDValue N0 = N->getOperand(0);
2065   SDValue N1 = N->getOperand(1);
2066   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2067   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2068   EVT VT = N->getValueType(0);
2069
2070   // fold vector ops
2071   if (VT.isVector()) {
2072     SDValue FoldedVOp = SimplifyVBinOp(N);
2073     if (FoldedVOp.getNode()) return FoldedVOp;
2074   }
2075
2076   // fold (udiv c1, c2) -> c1/c2
2077   if (N0C && N1C && !N1C->isNullValue())
2078     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2079   // fold (udiv x, (1 << c)) -> x >>u c
2080   if (N1C && N1C->getAPIntValue().isPowerOf2())
2081     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2082                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2083                                        getShiftAmountTy(N0.getValueType())));
2084   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2085   if (N1.getOpcode() == ISD::SHL) {
2086     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2087       if (SHC->getAPIntValue().isPowerOf2()) {
2088         EVT ADDVT = N1.getOperand(1).getValueType();
2089         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2090                                   N1.getOperand(1),
2091                                   DAG.getConstant(SHC->getAPIntValue()
2092                                                                   .logBase2(),
2093                                                   ADDVT));
2094         AddToWorkList(Add.getNode());
2095         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2096       }
2097     }
2098   }
2099   // fold (udiv x, c) -> alternate
2100   if (N1C && !TLI.isIntDivCheap()) {
2101     SDValue Op = BuildUDIV(N);
2102     if (Op.getNode()) return Op;
2103   }
2104
2105   // undef / X -> 0
2106   if (N0.getOpcode() == ISD::UNDEF)
2107     return DAG.getConstant(0, VT);
2108   // X / undef -> undef
2109   if (N1.getOpcode() == ISD::UNDEF)
2110     return N1;
2111
2112   return SDValue();
2113 }
2114
2115 SDValue DAGCombiner::visitSREM(SDNode *N) {
2116   SDValue N0 = N->getOperand(0);
2117   SDValue N1 = N->getOperand(1);
2118   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2120   EVT VT = N->getValueType(0);
2121
2122   // fold (srem c1, c2) -> c1%c2
2123   if (N0C && N1C && !N1C->isNullValue())
2124     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2125   // If we know the sign bits of both operands are zero, strength reduce to a
2126   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2127   if (!VT.isVector()) {
2128     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2129       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2130   }
2131
2132   // If X/C can be simplified by the division-by-constant logic, lower
2133   // X%C to the equivalent of X-X/C*C.
2134   if (N1C && !N1C->isNullValue()) {
2135     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2136     AddToWorkList(Div.getNode());
2137     SDValue OptimizedDiv = combine(Div.getNode());
2138     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2139       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2140                                 OptimizedDiv, N1);
2141       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2142       AddToWorkList(Mul.getNode());
2143       return Sub;
2144     }
2145   }
2146
2147   // undef % X -> 0
2148   if (N0.getOpcode() == ISD::UNDEF)
2149     return DAG.getConstant(0, VT);
2150   // X % undef -> undef
2151   if (N1.getOpcode() == ISD::UNDEF)
2152     return N1;
2153
2154   return SDValue();
2155 }
2156
2157 SDValue DAGCombiner::visitUREM(SDNode *N) {
2158   SDValue N0 = N->getOperand(0);
2159   SDValue N1 = N->getOperand(1);
2160   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2161   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2162   EVT VT = N->getValueType(0);
2163
2164   // fold (urem c1, c2) -> c1%c2
2165   if (N0C && N1C && !N1C->isNullValue())
2166     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2167   // fold (urem x, pow2) -> (and x, pow2-1)
2168   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2169     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2170                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2171   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2172   if (N1.getOpcode() == ISD::SHL) {
2173     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174       if (SHC->getAPIntValue().isPowerOf2()) {
2175         SDValue Add =
2176           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2177                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2178                                  VT));
2179         AddToWorkList(Add.getNode());
2180         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2181       }
2182     }
2183   }
2184
2185   // If X/C can be simplified by the division-by-constant logic, lower
2186   // X%C to the equivalent of X-X/C*C.
2187   if (N1C && !N1C->isNullValue()) {
2188     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2189     AddToWorkList(Div.getNode());
2190     SDValue OptimizedDiv = combine(Div.getNode());
2191     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2192       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2193                                 OptimizedDiv, N1);
2194       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2195       AddToWorkList(Mul.getNode());
2196       return Sub;
2197     }
2198   }
2199
2200   // undef % X -> 0
2201   if (N0.getOpcode() == ISD::UNDEF)
2202     return DAG.getConstant(0, VT);
2203   // X % undef -> undef
2204   if (N1.getOpcode() == ISD::UNDEF)
2205     return N1;
2206
2207   return SDValue();
2208 }
2209
2210 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2211   SDValue N0 = N->getOperand(0);
2212   SDValue N1 = N->getOperand(1);
2213   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2214   EVT VT = N->getValueType(0);
2215   SDLoc DL(N);
2216
2217   // fold (mulhs x, 0) -> 0
2218   if (N1C && N1C->isNullValue())
2219     return N1;
2220   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2221   if (N1C && N1C->getAPIntValue() == 1)
2222     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2223                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2224                                        getShiftAmountTy(N0.getValueType())));
2225   // fold (mulhs x, undef) -> 0
2226   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2227     return DAG.getConstant(0, VT);
2228
2229   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2230   // plus a shift.
2231   if (VT.isSimple() && !VT.isVector()) {
2232     MVT Simple = VT.getSimpleVT();
2233     unsigned SimpleSize = Simple.getSizeInBits();
2234     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2235     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2236       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2237       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2238       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2239       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2240             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2241       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2242     }
2243   }
2244
2245   return SDValue();
2246 }
2247
2248 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2249   SDValue N0 = N->getOperand(0);
2250   SDValue N1 = N->getOperand(1);
2251   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2252   EVT VT = N->getValueType(0);
2253   SDLoc DL(N);
2254
2255   // fold (mulhu x, 0) -> 0
2256   if (N1C && N1C->isNullValue())
2257     return N1;
2258   // fold (mulhu x, 1) -> 0
2259   if (N1C && N1C->getAPIntValue() == 1)
2260     return DAG.getConstant(0, N0.getValueType());
2261   // fold (mulhu x, undef) -> 0
2262   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2263     return DAG.getConstant(0, VT);
2264
2265   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2266   // plus a shift.
2267   if (VT.isSimple() && !VT.isVector()) {
2268     MVT Simple = VT.getSimpleVT();
2269     unsigned SimpleSize = Simple.getSizeInBits();
2270     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2271     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2272       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2273       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2274       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2275       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2276             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2277       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2278     }
2279   }
2280
2281   return SDValue();
2282 }
2283
2284 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2285 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2286 /// that are being performed. Return true if a simplification was made.
2287 ///
2288 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2289                                                 unsigned HiOp) {
2290   // If the high half is not needed, just compute the low half.
2291   bool HiExists = N->hasAnyUseOfValue(1);
2292   if (!HiExists &&
2293       (!LegalOperations ||
2294        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2295     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2296                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2297     return CombineTo(N, Res, Res);
2298   }
2299
2300   // If the low half is not needed, just compute the high half.
2301   bool LoExists = N->hasAnyUseOfValue(0);
2302   if (!LoExists &&
2303       (!LegalOperations ||
2304        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2305     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2306                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2307     return CombineTo(N, Res, Res);
2308   }
2309
2310   // If both halves are used, return as it is.
2311   if (LoExists && HiExists)
2312     return SDValue();
2313
2314   // If the two computed results can be simplified separately, separate them.
2315   if (LoExists) {
2316     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2317                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2318     AddToWorkList(Lo.getNode());
2319     SDValue LoOpt = combine(Lo.getNode());
2320     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2321         (!LegalOperations ||
2322          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2323       return CombineTo(N, LoOpt, LoOpt);
2324   }
2325
2326   if (HiExists) {
2327     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2328                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2329     AddToWorkList(Hi.getNode());
2330     SDValue HiOpt = combine(Hi.getNode());
2331     if (HiOpt.getNode() && HiOpt != Hi &&
2332         (!LegalOperations ||
2333          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2334       return CombineTo(N, HiOpt, HiOpt);
2335   }
2336
2337   return SDValue();
2338 }
2339
2340 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2341   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2342   if (Res.getNode()) return Res;
2343
2344   EVT VT = N->getValueType(0);
2345   SDLoc DL(N);
2346
2347   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2348   // plus a shift.
2349   if (VT.isSimple() && !VT.isVector()) {
2350     MVT Simple = VT.getSimpleVT();
2351     unsigned SimpleSize = Simple.getSizeInBits();
2352     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2355       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2356       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2357       // Compute the high part as N1.
2358       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2359             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2360       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2361       // Compute the low part as N0.
2362       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2363       return CombineTo(N, Lo, Hi);
2364     }
2365   }
2366
2367   return SDValue();
2368 }
2369
2370 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2371   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2372   if (Res.getNode()) return Res;
2373
2374   EVT VT = N->getValueType(0);
2375   SDLoc DL(N);
2376
2377   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2378   // plus a shift.
2379   if (VT.isSimple() && !VT.isVector()) {
2380     MVT Simple = VT.getSimpleVT();
2381     unsigned SimpleSize = Simple.getSizeInBits();
2382     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2385       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2386       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2387       // Compute the high part as N1.
2388       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2389             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2390       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2391       // Compute the low part as N0.
2392       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2393       return CombineTo(N, Lo, Hi);
2394     }
2395   }
2396
2397   return SDValue();
2398 }
2399
2400 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2401   // (smulo x, 2) -> (saddo x, x)
2402   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2403     if (C2->getAPIntValue() == 2)
2404       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2405                          N->getOperand(0), N->getOperand(0));
2406
2407   return SDValue();
2408 }
2409
2410 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2411   // (umulo x, 2) -> (uaddo x, x)
2412   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2413     if (C2->getAPIntValue() == 2)
2414       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2415                          N->getOperand(0), N->getOperand(0));
2416
2417   return SDValue();
2418 }
2419
2420 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2421   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2422   if (Res.getNode()) return Res;
2423
2424   return SDValue();
2425 }
2426
2427 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2428   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2429   if (Res.getNode()) return Res;
2430
2431   return SDValue();
2432 }
2433
2434 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2435 /// two operands of the same opcode, try to simplify it.
2436 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2437   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2438   EVT VT = N0.getValueType();
2439   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2440
2441   // Bail early if none of these transforms apply.
2442   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2443
2444   // For each of OP in AND/OR/XOR:
2445   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2446   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2447   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2448   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2449   //
2450   // do not sink logical op inside of a vector extend, since it may combine
2451   // into a vsetcc.
2452   EVT Op0VT = N0.getOperand(0).getValueType();
2453   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2454        N0.getOpcode() == ISD::SIGN_EXTEND ||
2455        // Avoid infinite looping with PromoteIntBinOp.
2456        (N0.getOpcode() == ISD::ANY_EXTEND &&
2457         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2458        (N0.getOpcode() == ISD::TRUNCATE &&
2459         (!TLI.isZExtFree(VT, Op0VT) ||
2460          !TLI.isTruncateFree(Op0VT, VT)) &&
2461         TLI.isTypeLegal(Op0VT))) &&
2462       !VT.isVector() &&
2463       Op0VT == N1.getOperand(0).getValueType() &&
2464       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2465     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2466                                  N0.getOperand(0).getValueType(),
2467                                  N0.getOperand(0), N1.getOperand(0));
2468     AddToWorkList(ORNode.getNode());
2469     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2470   }
2471
2472   // For each of OP in SHL/SRL/SRA/AND...
2473   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2474   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2475   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2476   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2477        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2478       N0.getOperand(1) == N1.getOperand(1)) {
2479     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2480                                  N0.getOperand(0).getValueType(),
2481                                  N0.getOperand(0), N1.getOperand(0));
2482     AddToWorkList(ORNode.getNode());
2483     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2484                        ORNode, N0.getOperand(1));
2485   }
2486
2487   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2488   // Only perform this optimization after type legalization and before
2489   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2490   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2491   // we don't want to undo this promotion.
2492   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2493   // on scalars.
2494   if ((N0.getOpcode() == ISD::BITCAST ||
2495        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2496       Level == AfterLegalizeTypes) {
2497     SDValue In0 = N0.getOperand(0);
2498     SDValue In1 = N1.getOperand(0);
2499     EVT In0Ty = In0.getValueType();
2500     EVT In1Ty = In1.getValueType();
2501     SDLoc DL(N);
2502     // If both incoming values are integers, and the original types are the
2503     // same.
2504     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2505       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2506       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2507       AddToWorkList(Op.getNode());
2508       return BC;
2509     }
2510   }
2511
2512   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2513   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2514   // If both shuffles use the same mask, and both shuffle within a single
2515   // vector, then it is worthwhile to move the swizzle after the operation.
2516   // The type-legalizer generates this pattern when loading illegal
2517   // vector types from memory. In many cases this allows additional shuffle
2518   // optimizations.
2519   // There are other cases where moving the shuffle after the xor/and/or
2520   // is profitable even if shuffles don't perform a swizzle.
2521   // If both shuffles use the same mask, and both shuffles have the same first
2522   // or second operand, then it might still be profitable to move the shuffle
2523   // after the xor/and/or operation.
2524   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2525     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2526     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2527
2528     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2529            "Inputs to shuffles are not the same type");
2530
2531     // Check that both shuffles use the same mask. The masks are known to be of
2532     // the same length because the result vector type is the same.
2533     // Check also that shuffles have only one use to avoid introducing extra
2534     // instructions.
2535     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2536         SVN0->getMask().equals(SVN1->getMask())) {
2537       SDValue ShOp = N0->getOperand(1);
2538
2539       // Don't try to fold this node if it requires introducing a
2540       // build vector of all zeros that might be illegal at this stage.
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 (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2549       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2550       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2551       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2552         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2553                                       N0->getOperand(0), N1->getOperand(0));
2554         AddToWorkList(NewNode.getNode());
2555         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2556                                     &SVN0->getMask()[0]);
2557       }
2558
2559       // Don't try to fold this node if it requires introducing a
2560       // build vector of all zeros that might be illegal at this stage.
2561       ShOp = N0->getOperand(0);
2562       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2563         if (!LegalTypes)
2564           ShOp = DAG.getConstant(0, VT);
2565         else
2566           ShOp = SDValue();
2567       }
2568
2569       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2570       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2571       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2572       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2573         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2574                                       N0->getOperand(1), N1->getOperand(1));
2575         AddToWorkList(NewNode.getNode());
2576         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2577                                     &SVN0->getMask()[0]);
2578       }
2579     }
2580   }
2581
2582   return SDValue();
2583 }
2584
2585 SDValue DAGCombiner::visitAND(SDNode *N) {
2586   SDValue N0 = N->getOperand(0);
2587   SDValue N1 = N->getOperand(1);
2588   SDValue LL, LR, RL, RR, CC0, CC1;
2589   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2590   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2591   EVT VT = N1.getValueType();
2592   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2593
2594   // fold vector ops
2595   if (VT.isVector()) {
2596     SDValue FoldedVOp = SimplifyVBinOp(N);
2597     if (FoldedVOp.getNode()) return FoldedVOp;
2598
2599     // fold (and x, 0) -> 0, vector edition
2600     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2601       return N0;
2602     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2603       return N1;
2604
2605     // fold (and x, -1) -> x, vector edition
2606     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2607       return N1;
2608     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2609       return N0;
2610   }
2611
2612   // fold (and x, undef) -> 0
2613   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2614     return DAG.getConstant(0, VT);
2615   // fold (and c1, c2) -> c1&c2
2616   if (N0C && N1C)
2617     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2618   // canonicalize constant to RHS
2619   if (N0C && !N1C)
2620     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2621   // fold (and x, -1) -> x
2622   if (N1C && N1C->isAllOnesValue())
2623     return N0;
2624   // if (and x, c) is known to be zero, return 0
2625   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2626                                    APInt::getAllOnesValue(BitWidth)))
2627     return DAG.getConstant(0, VT);
2628   // reassociate and
2629   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2630   if (RAND.getNode())
2631     return RAND;
2632   // fold (and (or x, C), D) -> D if (C & D) == D
2633   if (N1C && N0.getOpcode() == ISD::OR)
2634     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2635       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2636         return N1;
2637   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2638   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2639     SDValue N0Op0 = N0.getOperand(0);
2640     APInt Mask = ~N1C->getAPIntValue();
2641     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2642     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2643       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2644                                  N0.getValueType(), N0Op0);
2645
2646       // Replace uses of the AND with uses of the Zero extend node.
2647       CombineTo(N, Zext);
2648
2649       // We actually want to replace all uses of the any_extend with the
2650       // zero_extend, to avoid duplicating things.  This will later cause this
2651       // AND to be folded.
2652       CombineTo(N0.getNode(), Zext);
2653       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2654     }
2655   }
2656   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2657   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2658   // already be zero by virtue of the width of the base type of the load.
2659   //
2660   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2661   // more cases.
2662   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2663        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2664       N0.getOpcode() == ISD::LOAD) {
2665     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2666                                          N0 : N0.getOperand(0) );
2667
2668     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2669     // This can be a pure constant or a vector splat, in which case we treat the
2670     // vector as a scalar and use the splat value.
2671     APInt Constant = APInt::getNullValue(1);
2672     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2673       Constant = C->getAPIntValue();
2674     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2675       APInt SplatValue, SplatUndef;
2676       unsigned SplatBitSize;
2677       bool HasAnyUndefs;
2678       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2679                                              SplatBitSize, HasAnyUndefs);
2680       if (IsSplat) {
2681         // Undef bits can contribute to a possible optimisation if set, so
2682         // set them.
2683         SplatValue |= SplatUndef;
2684
2685         // The splat value may be something like "0x00FFFFFF", which means 0 for
2686         // the first vector value and FF for the rest, repeating. We need a mask
2687         // that will apply equally to all members of the vector, so AND all the
2688         // lanes of the constant together.
2689         EVT VT = Vector->getValueType(0);
2690         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2691
2692         // If the splat value has been compressed to a bitlength lower
2693         // than the size of the vector lane, we need to re-expand it to
2694         // the lane size.
2695         if (BitWidth > SplatBitSize)
2696           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2697                SplatBitSize < BitWidth;
2698                SplatBitSize = SplatBitSize * 2)
2699             SplatValue |= SplatValue.shl(SplatBitSize);
2700
2701         Constant = APInt::getAllOnesValue(BitWidth);
2702         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2703           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2704       }
2705     }
2706
2707     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2708     // actually legal and isn't going to get expanded, else this is a false
2709     // optimisation.
2710     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2711                                                     Load->getMemoryVT());
2712
2713     // Resize the constant to the same size as the original memory access before
2714     // extension. If it is still the AllOnesValue then this AND is completely
2715     // unneeded.
2716     Constant =
2717       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2718
2719     bool B;
2720     switch (Load->getExtensionType()) {
2721     default: B = false; break;
2722     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2723     case ISD::ZEXTLOAD:
2724     case ISD::NON_EXTLOAD: B = true; break;
2725     }
2726
2727     if (B && Constant.isAllOnesValue()) {
2728       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2729       // preserve semantics once we get rid of the AND.
2730       SDValue NewLoad(Load, 0);
2731       if (Load->getExtensionType() == ISD::EXTLOAD) {
2732         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2733                               Load->getValueType(0), SDLoc(Load),
2734                               Load->getChain(), Load->getBasePtr(),
2735                               Load->getOffset(), Load->getMemoryVT(),
2736                               Load->getMemOperand());
2737         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2738         if (Load->getNumValues() == 3) {
2739           // PRE/POST_INC loads have 3 values.
2740           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2741                            NewLoad.getValue(2) };
2742           CombineTo(Load, To, 3, true);
2743         } else {
2744           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2745         }
2746       }
2747
2748       // Fold the AND away, taking care not to fold to the old load node if we
2749       // replaced it.
2750       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2751
2752       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2753     }
2754   }
2755   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2756   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2757     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2758     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2759
2760     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2761         LL.getValueType().isInteger()) {
2762       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2763       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2764         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2765                                      LR.getValueType(), LL, RL);
2766         AddToWorkList(ORNode.getNode());
2767         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2768       }
2769       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2770       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2771         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2772                                       LR.getValueType(), LL, RL);
2773         AddToWorkList(ANDNode.getNode());
2774         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2775       }
2776       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2777       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2778         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2779                                      LR.getValueType(), LL, RL);
2780         AddToWorkList(ORNode.getNode());
2781         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2782       }
2783     }
2784     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2785     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2786         Op0 == Op1 && LL.getValueType().isInteger() &&
2787       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2788                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2789                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2790                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2791       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2792                                     LL, DAG.getConstant(1, LL.getValueType()));
2793       AddToWorkList(ADDNode.getNode());
2794       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2795                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2796     }
2797     // canonicalize equivalent to ll == rl
2798     if (LL == RR && LR == RL) {
2799       Op1 = ISD::getSetCCSwappedOperands(Op1);
2800       std::swap(RL, RR);
2801     }
2802     if (LL == RL && LR == RR) {
2803       bool isInteger = LL.getValueType().isInteger();
2804       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2805       if (Result != ISD::SETCC_INVALID &&
2806           (!LegalOperations ||
2807            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2808             TLI.isOperationLegal(ISD::SETCC,
2809                             getSetCCResultType(N0.getSimpleValueType())))))
2810         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2811                             LL, LR, Result);
2812     }
2813   }
2814
2815   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2816   if (N0.getOpcode() == N1.getOpcode()) {
2817     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2818     if (Tmp.getNode()) return Tmp;
2819   }
2820
2821   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2822   // fold (and (sra)) -> (and (srl)) when possible.
2823   if (!VT.isVector() &&
2824       SimplifyDemandedBits(SDValue(N, 0)))
2825     return SDValue(N, 0);
2826
2827   // fold (zext_inreg (extload x)) -> (zextload x)
2828   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2829     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2830     EVT MemVT = LN0->getMemoryVT();
2831     // If we zero all the possible extended bits, then we can turn this into
2832     // a zextload if we are running before legalize or the operation is legal.
2833     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2834     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2835                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2836         ((!LegalOperations && !LN0->isVolatile()) ||
2837          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2838       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2839                                        LN0->getChain(), LN0->getBasePtr(),
2840                                        MemVT, LN0->getMemOperand());
2841       AddToWorkList(N);
2842       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2843       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2844     }
2845   }
2846   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2847   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2848       N0.hasOneUse()) {
2849     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2850     EVT MemVT = LN0->getMemoryVT();
2851     // If we zero all the possible extended bits, then we can turn this into
2852     // a zextload if we are running before legalize or the operation is legal.
2853     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2854     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2855                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2856         ((!LegalOperations && !LN0->isVolatile()) ||
2857          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2858       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2859                                        LN0->getChain(), LN0->getBasePtr(),
2860                                        MemVT, LN0->getMemOperand());
2861       AddToWorkList(N);
2862       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2863       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2864     }
2865   }
2866
2867   // fold (and (load x), 255) -> (zextload x, i8)
2868   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2869   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2870   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2871               (N0.getOpcode() == ISD::ANY_EXTEND &&
2872                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2873     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2874     LoadSDNode *LN0 = HasAnyExt
2875       ? cast<LoadSDNode>(N0.getOperand(0))
2876       : cast<LoadSDNode>(N0);
2877     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2878         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2879       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2880       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2881         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2882         EVT LoadedVT = LN0->getMemoryVT();
2883
2884         if (ExtVT == LoadedVT &&
2885             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2886           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2887
2888           SDValue NewLoad =
2889             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2890                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2891                            LN0->getMemOperand());
2892           AddToWorkList(N);
2893           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2894           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2895         }
2896
2897         // Do not change the width of a volatile load.
2898         // Do not generate loads of non-round integer types since these can
2899         // be expensive (and would be wrong if the type is not byte sized).
2900         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2901             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2902           EVT PtrType = LN0->getOperand(1).getValueType();
2903
2904           unsigned Alignment = LN0->getAlignment();
2905           SDValue NewPtr = LN0->getBasePtr();
2906
2907           // For big endian targets, we need to add an offset to the pointer
2908           // to load the correct bytes.  For little endian systems, we merely
2909           // need to read fewer bytes from the same pointer.
2910           if (TLI.isBigEndian()) {
2911             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2912             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2913             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2914             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2915                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2916             Alignment = MinAlign(Alignment, PtrOff);
2917           }
2918
2919           AddToWorkList(NewPtr.getNode());
2920
2921           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2922           SDValue Load =
2923             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2924                            LN0->getChain(), NewPtr,
2925                            LN0->getPointerInfo(),
2926                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2927                            Alignment, LN0->getTBAAInfo());
2928           AddToWorkList(N);
2929           CombineTo(LN0, Load, Load.getValue(1));
2930           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2931         }
2932       }
2933     }
2934   }
2935
2936   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2937       VT.getSizeInBits() <= 64) {
2938     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2939       APInt ADDC = ADDI->getAPIntValue();
2940       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2941         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2942         // immediate for an add, but it is legal if its top c2 bits are set,
2943         // transform the ADD so the immediate doesn't need to be materialized
2944         // in a register.
2945         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2946           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2947                                              SRLI->getZExtValue());
2948           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2949             ADDC |= Mask;
2950             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2951               SDValue NewAdd =
2952                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2953                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2954               CombineTo(N0.getNode(), NewAdd);
2955               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2956             }
2957           }
2958         }
2959       }
2960     }
2961   }
2962
2963   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2964   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2965     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2966                                        N0.getOperand(1), false);
2967     if (BSwap.getNode())
2968       return BSwap;
2969   }
2970
2971   return SDValue();
2972 }
2973
2974 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2975 ///
2976 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2977                                         bool DemandHighBits) {
2978   if (!LegalOperations)
2979     return SDValue();
2980
2981   EVT VT = N->getValueType(0);
2982   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2983     return SDValue();
2984   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2985     return SDValue();
2986
2987   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2988   bool LookPassAnd0 = false;
2989   bool LookPassAnd1 = false;
2990   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2991       std::swap(N0, N1);
2992   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2993       std::swap(N0, N1);
2994   if (N0.getOpcode() == ISD::AND) {
2995     if (!N0.getNode()->hasOneUse())
2996       return SDValue();
2997     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2998     if (!N01C || N01C->getZExtValue() != 0xFF00)
2999       return SDValue();
3000     N0 = N0.getOperand(0);
3001     LookPassAnd0 = true;
3002   }
3003
3004   if (N1.getOpcode() == ISD::AND) {
3005     if (!N1.getNode()->hasOneUse())
3006       return SDValue();
3007     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3008     if (!N11C || N11C->getZExtValue() != 0xFF)
3009       return SDValue();
3010     N1 = N1.getOperand(0);
3011     LookPassAnd1 = true;
3012   }
3013
3014   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3015     std::swap(N0, N1);
3016   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3017     return SDValue();
3018   if (!N0.getNode()->hasOneUse() ||
3019       !N1.getNode()->hasOneUse())
3020     return SDValue();
3021
3022   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3023   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3024   if (!N01C || !N11C)
3025     return SDValue();
3026   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3027     return SDValue();
3028
3029   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3030   SDValue N00 = N0->getOperand(0);
3031   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3032     if (!N00.getNode()->hasOneUse())
3033       return SDValue();
3034     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3035     if (!N001C || N001C->getZExtValue() != 0xFF)
3036       return SDValue();
3037     N00 = N00.getOperand(0);
3038     LookPassAnd0 = true;
3039   }
3040
3041   SDValue N10 = N1->getOperand(0);
3042   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3043     if (!N10.getNode()->hasOneUse())
3044       return SDValue();
3045     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3046     if (!N101C || N101C->getZExtValue() != 0xFF00)
3047       return SDValue();
3048     N10 = N10.getOperand(0);
3049     LookPassAnd1 = true;
3050   }
3051
3052   if (N00 != N10)
3053     return SDValue();
3054
3055   // Make sure everything beyond the low halfword gets set to zero since the SRL
3056   // 16 will clear the top bits.
3057   unsigned OpSizeInBits = VT.getSizeInBits();
3058   if (DemandHighBits && OpSizeInBits > 16) {
3059     // If the left-shift isn't masked out then the only way this is a bswap is
3060     // if all bits beyond the low 8 are 0. In that case the entire pattern
3061     // reduces to a left shift anyway: leave it for other parts of the combiner.
3062     if (!LookPassAnd0)
3063       return SDValue();
3064
3065     // However, if the right shift isn't masked out then it might be because
3066     // it's not needed. See if we can spot that too.
3067     if (!LookPassAnd1 &&
3068         !DAG.MaskedValueIsZero(
3069             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3070       return SDValue();
3071   }
3072
3073   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3074   if (OpSizeInBits > 16)
3075     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3076                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3077   return Res;
3078 }
3079
3080 /// isBSwapHWordElement - Return true if the specified node is an element
3081 /// that makes up a 32-bit packed halfword byteswap. i.e.
3082 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3083 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3084   if (!N.getNode()->hasOneUse())
3085     return false;
3086
3087   unsigned Opc = N.getOpcode();
3088   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3089     return false;
3090
3091   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3092   if (!N1C)
3093     return false;
3094
3095   unsigned Num;
3096   switch (N1C->getZExtValue()) {
3097   default:
3098     return false;
3099   case 0xFF:       Num = 0; break;
3100   case 0xFF00:     Num = 1; break;
3101   case 0xFF0000:   Num = 2; break;
3102   case 0xFF000000: Num = 3; break;
3103   }
3104
3105   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3106   SDValue N0 = N.getOperand(0);
3107   if (Opc == ISD::AND) {
3108     if (Num == 0 || Num == 2) {
3109       // (x >> 8) & 0xff
3110       // (x >> 8) & 0xff0000
3111       if (N0.getOpcode() != ISD::SRL)
3112         return false;
3113       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3114       if (!C || C->getZExtValue() != 8)
3115         return false;
3116     } else {
3117       // (x << 8) & 0xff00
3118       // (x << 8) & 0xff000000
3119       if (N0.getOpcode() != ISD::SHL)
3120         return false;
3121       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3122       if (!C || C->getZExtValue() != 8)
3123         return false;
3124     }
3125   } else if (Opc == ISD::SHL) {
3126     // (x & 0xff) << 8
3127     // (x & 0xff0000) << 8
3128     if (Num != 0 && Num != 2)
3129       return false;
3130     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3131     if (!C || C->getZExtValue() != 8)
3132       return false;
3133   } else { // Opc == ISD::SRL
3134     // (x & 0xff00) >> 8
3135     // (x & 0xff000000) >> 8
3136     if (Num != 1 && Num != 3)
3137       return false;
3138     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3139     if (!C || C->getZExtValue() != 8)
3140       return false;
3141   }
3142
3143   if (Parts[Num])
3144     return false;
3145
3146   Parts[Num] = N0.getOperand(0).getNode();
3147   return true;
3148 }
3149
3150 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3151 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3152 /// => (rotl (bswap x), 16)
3153 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3154   if (!LegalOperations)
3155     return SDValue();
3156
3157   EVT VT = N->getValueType(0);
3158   if (VT != MVT::i32)
3159     return SDValue();
3160   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3161     return SDValue();
3162
3163   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3164   // Look for either
3165   // (or (or (and), (and)), (or (and), (and)))
3166   // (or (or (or (and), (and)), (and)), (and))
3167   if (N0.getOpcode() != ISD::OR)
3168     return SDValue();
3169   SDValue N00 = N0.getOperand(0);
3170   SDValue N01 = N0.getOperand(1);
3171
3172   if (N1.getOpcode() == ISD::OR &&
3173       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3174     // (or (or (and), (and)), (or (and), (and)))
3175     SDValue N000 = N00.getOperand(0);
3176     if (!isBSwapHWordElement(N000, Parts))
3177       return SDValue();
3178
3179     SDValue N001 = N00.getOperand(1);
3180     if (!isBSwapHWordElement(N001, Parts))
3181       return SDValue();
3182     SDValue N010 = N01.getOperand(0);
3183     if (!isBSwapHWordElement(N010, Parts))
3184       return SDValue();
3185     SDValue N011 = N01.getOperand(1);
3186     if (!isBSwapHWordElement(N011, Parts))
3187       return SDValue();
3188   } else {
3189     // (or (or (or (and), (and)), (and)), (and))
3190     if (!isBSwapHWordElement(N1, Parts))
3191       return SDValue();
3192     if (!isBSwapHWordElement(N01, Parts))
3193       return SDValue();
3194     if (N00.getOpcode() != ISD::OR)
3195       return SDValue();
3196     SDValue N000 = N00.getOperand(0);
3197     if (!isBSwapHWordElement(N000, Parts))
3198       return SDValue();
3199     SDValue N001 = N00.getOperand(1);
3200     if (!isBSwapHWordElement(N001, Parts))
3201       return SDValue();
3202   }
3203
3204   // Make sure the parts are all coming from the same node.
3205   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3206     return SDValue();
3207
3208   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3209                               SDValue(Parts[0],0));
3210
3211   // Result of the bswap should be rotated by 16. If it's not legal, then
3212   // do  (x << 16) | (x >> 16).
3213   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3214   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3215     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3216   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3217     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3218   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3219                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3220                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3221 }
3222
3223 SDValue DAGCombiner::visitOR(SDNode *N) {
3224   SDValue N0 = N->getOperand(0);
3225   SDValue N1 = N->getOperand(1);
3226   SDValue LL, LR, RL, RR, CC0, CC1;
3227   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3228   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3229   EVT VT = N1.getValueType();
3230
3231   // fold vector ops
3232   if (VT.isVector()) {
3233     SDValue FoldedVOp = SimplifyVBinOp(N);
3234     if (FoldedVOp.getNode()) return FoldedVOp;
3235
3236     // fold (or x, 0) -> x, vector edition
3237     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3238       return N1;
3239     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3240       return N0;
3241
3242     // fold (or x, -1) -> -1, vector edition
3243     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3244       return N0;
3245     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3246       return N1;
3247
3248     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3249     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3250     // Do this only if the resulting shuffle is legal.
3251     if (isa<ShuffleVectorSDNode>(N0) &&
3252         isa<ShuffleVectorSDNode>(N1) &&
3253         // Avoid folding a node with illegal type.
3254         TLI.isTypeLegal(VT) &&
3255         N0->getOperand(1) == N1->getOperand(1) &&
3256         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3257       bool CanFold = true;
3258       unsigned NumElts = VT.getVectorNumElements();
3259       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3260       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3261       // We construct two shuffle masks:
3262       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3263       // and N1 as the second operand.
3264       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3265       // and N0 as the second operand.
3266       // We do this because OR is commutable and therefore there might be
3267       // two ways to fold this node into a shuffle.
3268       SmallVector<int,4> Mask1;
3269       SmallVector<int,4> Mask2;
3270
3271       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3272         int M0 = SV0->getMaskElt(i);
3273         int M1 = SV1->getMaskElt(i);
3274
3275         // Both shuffle indexes are undef. Propagate Undef.
3276         if (M0 < 0 && M1 < 0) {
3277           Mask1.push_back(M0);
3278           Mask2.push_back(M0);
3279           continue;
3280         }
3281
3282         if (M0 < 0 || M1 < 0 ||
3283             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3284             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3285           CanFold = false;
3286           break;
3287         }
3288
3289         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3290         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3291       }
3292
3293       if (CanFold) {
3294         // Fold this sequence only if the resulting shuffle is 'legal'.
3295         if (TLI.isShuffleMaskLegal(Mask1, VT))
3296           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3297                                       N1->getOperand(0), &Mask1[0]);
3298         if (TLI.isShuffleMaskLegal(Mask2, VT))
3299           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3300                                       N0->getOperand(0), &Mask2[0]);
3301       }
3302     }
3303   }
3304
3305   // fold (or x, undef) -> -1
3306   if (!LegalOperations &&
3307       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3308     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3309     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3310   }
3311   // fold (or c1, c2) -> c1|c2
3312   if (N0C && N1C)
3313     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3314   // canonicalize constant to RHS
3315   if (N0C && !N1C)
3316     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3317   // fold (or x, 0) -> x
3318   if (N1C && N1C->isNullValue())
3319     return N0;
3320   // fold (or x, -1) -> -1
3321   if (N1C && N1C->isAllOnesValue())
3322     return N1;
3323   // fold (or x, c) -> c iff (x & ~c) == 0
3324   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3325     return N1;
3326
3327   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3328   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3329   if (BSwap.getNode())
3330     return BSwap;
3331   BSwap = MatchBSwapHWordLow(N, N0, N1);
3332   if (BSwap.getNode())
3333     return BSwap;
3334
3335   // reassociate or
3336   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3337   if (ROR.getNode())
3338     return ROR;
3339   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3340   // iff (c1 & c2) == 0.
3341   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3342              isa<ConstantSDNode>(N0.getOperand(1))) {
3343     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3344     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3345       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3346       if (!COR.getNode())
3347         return SDValue();
3348       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3349                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3350                                      N0.getOperand(0), N1), COR);
3351     }
3352   }
3353   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3354   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3355     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3356     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3357
3358     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3359         LL.getValueType().isInteger()) {
3360       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3361       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3362       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3363           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3364         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3365                                      LR.getValueType(), LL, RL);
3366         AddToWorkList(ORNode.getNode());
3367         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3368       }
3369       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3370       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3371       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3372           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3373         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3374                                       LR.getValueType(), LL, RL);
3375         AddToWorkList(ANDNode.getNode());
3376         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3377       }
3378     }
3379     // canonicalize equivalent to ll == rl
3380     if (LL == RR && LR == RL) {
3381       Op1 = ISD::getSetCCSwappedOperands(Op1);
3382       std::swap(RL, RR);
3383     }
3384     if (LL == RL && LR == RR) {
3385       bool isInteger = LL.getValueType().isInteger();
3386       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3387       if (Result != ISD::SETCC_INVALID &&
3388           (!LegalOperations ||
3389            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3390             TLI.isOperationLegal(ISD::SETCC,
3391               getSetCCResultType(N0.getValueType())))))
3392         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3393                             LL, LR, Result);
3394     }
3395   }
3396
3397   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3398   if (N0.getOpcode() == N1.getOpcode()) {
3399     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3400     if (Tmp.getNode()) return Tmp;
3401   }
3402
3403   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3404   if (N0.getOpcode() == ISD::AND &&
3405       N1.getOpcode() == ISD::AND &&
3406       N0.getOperand(1).getOpcode() == ISD::Constant &&
3407       N1.getOperand(1).getOpcode() == ISD::Constant &&
3408       // Don't increase # computations.
3409       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3410     // We can only do this xform if we know that bits from X that are set in C2
3411     // but not in C1 are already zero.  Likewise for Y.
3412     const APInt &LHSMask =
3413       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3414     const APInt &RHSMask =
3415       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3416
3417     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3418         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3419       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3420                               N0.getOperand(0), N1.getOperand(0));
3421       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3422                          DAG.getConstant(LHSMask | RHSMask, VT));
3423     }
3424   }
3425
3426   // See if this is some rotate idiom.
3427   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3428     return SDValue(Rot, 0);
3429
3430   // Simplify the operands using demanded-bits information.
3431   if (!VT.isVector() &&
3432       SimplifyDemandedBits(SDValue(N, 0)))
3433     return SDValue(N, 0);
3434
3435   return SDValue();
3436 }
3437
3438 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3439 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3440   if (Op.getOpcode() == ISD::AND) {
3441     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3442       Mask = Op.getOperand(1);
3443       Op = Op.getOperand(0);
3444     } else {
3445       return false;
3446     }
3447   }
3448
3449   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3450     Shift = Op;
3451     return true;
3452   }
3453
3454   return false;
3455 }
3456
3457 // Return true if we can prove that, whenever Neg and Pos are both in the
3458 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3459 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3460 //
3461 //     (or (shift1 X, Neg), (shift2 X, Pos))
3462 //
3463 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3464 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3465 // to consider shift amounts with defined behavior.
3466 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3467   // If OpSize is a power of 2 then:
3468   //
3469   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3470   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3471   //
3472   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3473   // for the stronger condition:
3474   //
3475   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3476   //
3477   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3478   // we can just replace Neg with Neg' for the rest of the function.
3479   //
3480   // In other cases we check for the even stronger condition:
3481   //
3482   //     Neg == OpSize - Pos                                    [B]
3483   //
3484   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3485   // behavior if Pos == 0 (and consequently Neg == OpSize).
3486   //
3487   // We could actually use [A] whenever OpSize is a power of 2, but the
3488   // only extra cases that it would match are those uninteresting ones
3489   // where Neg and Pos are never in range at the same time.  E.g. for
3490   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3491   // as well as (sub 32, Pos), but:
3492   //
3493   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3494   //
3495   // always invokes undefined behavior for 32-bit X.
3496   //
3497   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3498   unsigned MaskLoBits = 0;
3499   if (Neg.getOpcode() == ISD::AND &&
3500       isPowerOf2_64(OpSize) &&
3501       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3502       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3503     Neg = Neg.getOperand(0);
3504     MaskLoBits = Log2_64(OpSize);
3505   }
3506
3507   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3508   if (Neg.getOpcode() != ISD::SUB)
3509     return 0;
3510   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3511   if (!NegC)
3512     return 0;
3513   SDValue NegOp1 = Neg.getOperand(1);
3514
3515   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3516   // Pos'.  The truncation is redundant for the purpose of the equality.
3517   if (MaskLoBits &&
3518       Pos.getOpcode() == ISD::AND &&
3519       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3520       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3521     Pos = Pos.getOperand(0);
3522
3523   // The condition we need is now:
3524   //
3525   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3526   //
3527   // If NegOp1 == Pos then we need:
3528   //
3529   //              OpSize & Mask == NegC & Mask
3530   //
3531   // (because "x & Mask" is a truncation and distributes through subtraction).
3532   APInt Width;
3533   if (Pos == NegOp1)
3534     Width = NegC->getAPIntValue();
3535   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3536   // Then the condition we want to prove becomes:
3537   //
3538   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3539   //
3540   // which, again because "x & Mask" is a truncation, becomes:
3541   //
3542   //                NegC & Mask == (OpSize - PosC) & Mask
3543   //              OpSize & Mask == (NegC + PosC) & Mask
3544   else if (Pos.getOpcode() == ISD::ADD &&
3545            Pos.getOperand(0) == NegOp1 &&
3546            Pos.getOperand(1).getOpcode() == ISD::Constant)
3547     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3548              NegC->getAPIntValue());
3549   else
3550     return false;
3551
3552   // Now we just need to check that OpSize & Mask == Width & Mask.
3553   if (MaskLoBits)
3554     // Opsize & Mask is 0 since Mask is Opsize - 1.
3555     return Width.getLoBits(MaskLoBits) == 0;
3556   return Width == OpSize;
3557 }
3558
3559 // A subroutine of MatchRotate used once we have found an OR of two opposite
3560 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3561 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3562 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3563 // Neg with outer conversions stripped away.
3564 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3565                                        SDValue Neg, SDValue InnerPos,
3566                                        SDValue InnerNeg, unsigned PosOpcode,
3567                                        unsigned NegOpcode, SDLoc DL) {
3568   // fold (or (shl x, (*ext y)),
3569   //          (srl x, (*ext (sub 32, y)))) ->
3570   //   (rotl x, y) or (rotr x, (sub 32, y))
3571   //
3572   // fold (or (shl x, (*ext (sub 32, y))),
3573   //          (srl x, (*ext y))) ->
3574   //   (rotr x, y) or (rotl x, (sub 32, y))
3575   EVT VT = Shifted.getValueType();
3576   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3577     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3578     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3579                        HasPos ? Pos : Neg).getNode();
3580   }
3581
3582   return nullptr;
3583 }
3584
3585 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3586 // idioms for rotate, and if the target supports rotation instructions, generate
3587 // a rot[lr].
3588 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3589   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3590   EVT VT = LHS.getValueType();
3591   if (!TLI.isTypeLegal(VT)) return nullptr;
3592
3593   // The target must have at least one rotate flavor.
3594   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3595   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3596   if (!HasROTL && !HasROTR) return nullptr;
3597
3598   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3599   SDValue LHSShift;   // The shift.
3600   SDValue LHSMask;    // AND value if any.
3601   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3602     return nullptr; // Not part of a rotate.
3603
3604   SDValue RHSShift;   // The shift.
3605   SDValue RHSMask;    // AND value if any.
3606   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3607     return nullptr; // Not part of a rotate.
3608
3609   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3610     return nullptr;   // Not shifting the same value.
3611
3612   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3613     return nullptr;   // Shifts must disagree.
3614
3615   // Canonicalize shl to left side in a shl/srl pair.
3616   if (RHSShift.getOpcode() == ISD::SHL) {
3617     std::swap(LHS, RHS);
3618     std::swap(LHSShift, RHSShift);
3619     std::swap(LHSMask , RHSMask );
3620   }
3621
3622   unsigned OpSizeInBits = VT.getSizeInBits();
3623   SDValue LHSShiftArg = LHSShift.getOperand(0);
3624   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3625   SDValue RHSShiftArg = RHSShift.getOperand(0);
3626   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3627
3628   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3629   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3630   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3631       RHSShiftAmt.getOpcode() == ISD::Constant) {
3632     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3633     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3634     if ((LShVal + RShVal) != OpSizeInBits)
3635       return nullptr;
3636
3637     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3638                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3639
3640     // If there is an AND of either shifted operand, apply it to the result.
3641     if (LHSMask.getNode() || RHSMask.getNode()) {
3642       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3643
3644       if (LHSMask.getNode()) {
3645         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3646         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3647       }
3648       if (RHSMask.getNode()) {
3649         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3650         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3651       }
3652
3653       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3654     }
3655
3656     return Rot.getNode();
3657   }
3658
3659   // If there is a mask here, and we have a variable shift, we can't be sure
3660   // that we're masking out the right stuff.
3661   if (LHSMask.getNode() || RHSMask.getNode())
3662     return nullptr;
3663
3664   // If the shift amount is sign/zext/any-extended just peel it off.
3665   SDValue LExtOp0 = LHSShiftAmt;
3666   SDValue RExtOp0 = RHSShiftAmt;
3667   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3668        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3669        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3670        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3671       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3672        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3673        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3674        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3675     LExtOp0 = LHSShiftAmt.getOperand(0);
3676     RExtOp0 = RHSShiftAmt.getOperand(0);
3677   }
3678
3679   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3680                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3681   if (TryL)
3682     return TryL;
3683
3684   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3685                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3686   if (TryR)
3687     return TryR;
3688
3689   return nullptr;
3690 }
3691
3692 SDValue DAGCombiner::visitXOR(SDNode *N) {
3693   SDValue N0 = N->getOperand(0);
3694   SDValue N1 = N->getOperand(1);
3695   SDValue LHS, RHS, CC;
3696   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3697   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3698   EVT VT = N0.getValueType();
3699
3700   // fold vector ops
3701   if (VT.isVector()) {
3702     SDValue FoldedVOp = SimplifyVBinOp(N);
3703     if (FoldedVOp.getNode()) return FoldedVOp;
3704
3705     // fold (xor x, 0) -> x, vector edition
3706     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3707       return N1;
3708     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3709       return N0;
3710   }
3711
3712   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3713   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3714     return DAG.getConstant(0, VT);
3715   // fold (xor x, undef) -> undef
3716   if (N0.getOpcode() == ISD::UNDEF)
3717     return N0;
3718   if (N1.getOpcode() == ISD::UNDEF)
3719     return N1;
3720   // fold (xor c1, c2) -> c1^c2
3721   if (N0C && N1C)
3722     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3723   // canonicalize constant to RHS
3724   if (N0C && !N1C)
3725     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3726   // fold (xor x, 0) -> x
3727   if (N1C && N1C->isNullValue())
3728     return N0;
3729   // reassociate xor
3730   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3731   if (RXOR.getNode())
3732     return RXOR;
3733
3734   // fold !(x cc y) -> (x !cc y)
3735   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3736     bool isInt = LHS.getValueType().isInteger();
3737     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3738                                                isInt);
3739
3740     if (!LegalOperations ||
3741         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3742       switch (N0.getOpcode()) {
3743       default:
3744         llvm_unreachable("Unhandled SetCC Equivalent!");
3745       case ISD::SETCC:
3746         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3747       case ISD::SELECT_CC:
3748         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3749                                N0.getOperand(3), NotCC);
3750       }
3751     }
3752   }
3753
3754   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3755   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3756       N0.getNode()->hasOneUse() &&
3757       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3758     SDValue V = N0.getOperand(0);
3759     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3760                     DAG.getConstant(1, V.getValueType()));
3761     AddToWorkList(V.getNode());
3762     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3763   }
3764
3765   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3766   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3767       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3768     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3769     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3770       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3771       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3772       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3773       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3774       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3775     }
3776   }
3777   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3778   if (N1C && N1C->isAllOnesValue() &&
3779       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3780     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3781     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3782       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3783       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3784       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3785       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3786       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3787     }
3788   }
3789   // fold (xor (and x, y), y) -> (and (not x), y)
3790   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3791       N0->getOperand(1) == N1) {
3792     SDValue X = N0->getOperand(0);
3793     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3794     AddToWorkList(NotX.getNode());
3795     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3796   }
3797   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3798   if (N1C && N0.getOpcode() == ISD::XOR) {
3799     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3800     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3801     if (N00C)
3802       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3803                          DAG.getConstant(N1C->getAPIntValue() ^
3804                                          N00C->getAPIntValue(), VT));
3805     if (N01C)
3806       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3807                          DAG.getConstant(N1C->getAPIntValue() ^
3808                                          N01C->getAPIntValue(), VT));
3809   }
3810   // fold (xor x, x) -> 0
3811   if (N0 == N1)
3812     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3813
3814   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3815   if (N0.getOpcode() == N1.getOpcode()) {
3816     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3817     if (Tmp.getNode()) return Tmp;
3818   }
3819
3820   // Simplify the expression using non-local knowledge.
3821   if (!VT.isVector() &&
3822       SimplifyDemandedBits(SDValue(N, 0)))
3823     return SDValue(N, 0);
3824
3825   return SDValue();
3826 }
3827
3828 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3829 /// the shift amount is a constant.
3830 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3831   // We can't and shouldn't fold opaque constants.
3832   if (Amt->isOpaque())
3833     return SDValue();
3834
3835   SDNode *LHS = N->getOperand(0).getNode();
3836   if (!LHS->hasOneUse()) return SDValue();
3837
3838   // We want to pull some binops through shifts, so that we have (and (shift))
3839   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3840   // thing happens with address calculations, so it's important to canonicalize
3841   // it.
3842   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3843
3844   switch (LHS->getOpcode()) {
3845   default: return SDValue();
3846   case ISD::OR:
3847   case ISD::XOR:
3848     HighBitSet = false; // We can only transform sra if the high bit is clear.
3849     break;
3850   case ISD::AND:
3851     HighBitSet = true;  // We can only transform sra if the high bit is set.
3852     break;
3853   case ISD::ADD:
3854     if (N->getOpcode() != ISD::SHL)
3855       return SDValue(); // only shl(add) not sr[al](add).
3856     HighBitSet = false; // We can only transform sra if the high bit is clear.
3857     break;
3858   }
3859
3860   // We require the RHS of the binop to be a constant and not opaque as well.
3861   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3862   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3863
3864   // FIXME: disable this unless the input to the binop is a shift by a constant.
3865   // If it is not a shift, it pessimizes some common cases like:
3866   //
3867   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3868   //    int bar(int *X, int i) { return X[i & 255]; }
3869   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3870   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3871        BinOpLHSVal->getOpcode() != ISD::SRA &&
3872        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3873       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3874     return SDValue();
3875
3876   EVT VT = N->getValueType(0);
3877
3878   // If this is a signed shift right, and the high bit is modified by the
3879   // logical operation, do not perform the transformation. The highBitSet
3880   // boolean indicates the value of the high bit of the constant which would
3881   // cause it to be modified for this operation.
3882   if (N->getOpcode() == ISD::SRA) {
3883     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3884     if (BinOpRHSSignSet != HighBitSet)
3885       return SDValue();
3886   }
3887
3888   if (!TLI.isDesirableToCommuteWithShift(LHS))
3889     return SDValue();
3890
3891   // Fold the constants, shifting the binop RHS by the shift amount.
3892   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3893                                N->getValueType(0),
3894                                LHS->getOperand(1), N->getOperand(1));
3895   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3896
3897   // Create the new shift.
3898   SDValue NewShift = DAG.getNode(N->getOpcode(),
3899                                  SDLoc(LHS->getOperand(0)),
3900                                  VT, LHS->getOperand(0), N->getOperand(1));
3901
3902   // Create the new binop.
3903   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3904 }
3905
3906 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3907   assert(N->getOpcode() == ISD::TRUNCATE);
3908   assert(N->getOperand(0).getOpcode() == ISD::AND);
3909
3910   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3911   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3912     SDValue N01 = N->getOperand(0).getOperand(1);
3913
3914     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3915       EVT TruncVT = N->getValueType(0);
3916       SDValue N00 = N->getOperand(0).getOperand(0);
3917       APInt TruncC = N01C->getAPIntValue();
3918       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3919
3920       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3921                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3922                          DAG.getConstant(TruncC, TruncVT));
3923     }
3924   }
3925
3926   return SDValue();
3927 }
3928
3929 SDValue DAGCombiner::visitRotate(SDNode *N) {
3930   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3931   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3932       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3933     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3934     if (NewOp1.getNode())
3935       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3936                          N->getOperand(0), NewOp1);
3937   }
3938   return SDValue();
3939 }
3940
3941 SDValue DAGCombiner::visitSHL(SDNode *N) {
3942   SDValue N0 = N->getOperand(0);
3943   SDValue N1 = N->getOperand(1);
3944   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3945   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3946   EVT VT = N0.getValueType();
3947   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3948
3949   // fold vector ops
3950   if (VT.isVector()) {
3951     SDValue FoldedVOp = SimplifyVBinOp(N);
3952     if (FoldedVOp.getNode()) return FoldedVOp;
3953
3954     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3955     // If setcc produces all-one true value then:
3956     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3957     if (N1CV && N1CV->isConstant()) {
3958       if (N0.getOpcode() == ISD::AND) {
3959         SDValue N00 = N0->getOperand(0);
3960         SDValue N01 = N0->getOperand(1);
3961         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3962
3963         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
3964             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
3965                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
3966           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3967           if (C.getNode())
3968             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3969         }
3970       } else {
3971         N1C = isConstOrConstSplat(N1);
3972       }
3973     }
3974   }
3975
3976   // fold (shl c1, c2) -> c1<<c2
3977   if (N0C && N1C)
3978     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3979   // fold (shl 0, x) -> 0
3980   if (N0C && N0C->isNullValue())
3981     return N0;
3982   // fold (shl x, c >= size(x)) -> undef
3983   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3984     return DAG.getUNDEF(VT);
3985   // fold (shl x, 0) -> x
3986   if (N1C && N1C->isNullValue())
3987     return N0;
3988   // fold (shl undef, x) -> 0
3989   if (N0.getOpcode() == ISD::UNDEF)
3990     return DAG.getConstant(0, VT);
3991   // if (shl x, c) is known to be zero, return 0
3992   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3993                             APInt::getAllOnesValue(OpSizeInBits)))
3994     return DAG.getConstant(0, VT);
3995   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3996   if (N1.getOpcode() == ISD::TRUNCATE &&
3997       N1.getOperand(0).getOpcode() == ISD::AND) {
3998     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3999     if (NewOp1.getNode())
4000       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4001   }
4002
4003   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4004     return SDValue(N, 0);
4005
4006   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4007   if (N1C && N0.getOpcode() == ISD::SHL) {
4008     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4009       uint64_t c1 = N0C1->getZExtValue();
4010       uint64_t c2 = N1C->getZExtValue();
4011       if (c1 + c2 >= OpSizeInBits)
4012         return DAG.getConstant(0, VT);
4013       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4014                          DAG.getConstant(c1 + c2, N1.getValueType()));
4015     }
4016   }
4017
4018   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4019   // For this to be valid, the second form must not preserve any of the bits
4020   // that are shifted out by the inner shift in the first form.  This means
4021   // the outer shift size must be >= the number of bits added by the ext.
4022   // As a corollary, we don't care what kind of ext it is.
4023   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4024               N0.getOpcode() == ISD::ANY_EXTEND ||
4025               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4026       N0.getOperand(0).getOpcode() == ISD::SHL) {
4027     SDValue N0Op0 = N0.getOperand(0);
4028     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4029       uint64_t c1 = N0Op0C1->getZExtValue();
4030       uint64_t c2 = N1C->getZExtValue();
4031       EVT InnerShiftVT = N0Op0.getValueType();
4032       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4033       if (c2 >= OpSizeInBits - InnerShiftSize) {
4034         if (c1 + c2 >= OpSizeInBits)
4035           return DAG.getConstant(0, VT);
4036         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4037                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4038                                        N0Op0->getOperand(0)),
4039                            DAG.getConstant(c1 + c2, N1.getValueType()));
4040       }
4041     }
4042   }
4043
4044   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4045   // Only fold this if the inner zext has no other uses to avoid increasing
4046   // the total number of instructions.
4047   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4048       N0.getOperand(0).getOpcode() == ISD::SRL) {
4049     SDValue N0Op0 = N0.getOperand(0);
4050     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4051       uint64_t c1 = N0Op0C1->getZExtValue();
4052       if (c1 < VT.getScalarSizeInBits()) {
4053         uint64_t c2 = N1C->getZExtValue();
4054         if (c1 == c2) {
4055           SDValue NewOp0 = N0.getOperand(0);
4056           EVT CountVT = NewOp0.getOperand(1).getValueType();
4057           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4058                                        NewOp0, DAG.getConstant(c2, CountVT));
4059           AddToWorkList(NewSHL.getNode());
4060           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4061         }
4062       }
4063     }
4064   }
4065
4066   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4067   //                               (and (srl x, (sub c1, c2), MASK)
4068   // Only fold this if the inner shift has no other uses -- if it does, folding
4069   // this will increase the total number of instructions.
4070   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4071     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4072       uint64_t c1 = N0C1->getZExtValue();
4073       if (c1 < OpSizeInBits) {
4074         uint64_t c2 = N1C->getZExtValue();
4075         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4076         SDValue Shift;
4077         if (c2 > c1) {
4078           Mask = Mask.shl(c2 - c1);
4079           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4080                               DAG.getConstant(c2 - c1, N1.getValueType()));
4081         } else {
4082           Mask = Mask.lshr(c1 - c2);
4083           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4084                               DAG.getConstant(c1 - c2, N1.getValueType()));
4085         }
4086         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4087                            DAG.getConstant(Mask, VT));
4088       }
4089     }
4090   }
4091   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4092   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4093     unsigned BitSize = VT.getScalarSizeInBits();
4094     SDValue HiBitsMask =
4095       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4096                                             BitSize - N1C->getZExtValue()), VT);
4097     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4098                        HiBitsMask);
4099   }
4100
4101   if (N1C) {
4102     SDValue NewSHL = visitShiftByConstant(N, N1C);
4103     if (NewSHL.getNode())
4104       return NewSHL;
4105   }
4106
4107   return SDValue();
4108 }
4109
4110 SDValue DAGCombiner::visitSRA(SDNode *N) {
4111   SDValue N0 = N->getOperand(0);
4112   SDValue N1 = N->getOperand(1);
4113   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4114   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4115   EVT VT = N0.getValueType();
4116   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4117
4118   // fold vector ops
4119   if (VT.isVector()) {
4120     SDValue FoldedVOp = SimplifyVBinOp(N);
4121     if (FoldedVOp.getNode()) return FoldedVOp;
4122
4123     N1C = isConstOrConstSplat(N1);
4124   }
4125
4126   // fold (sra c1, c2) -> (sra c1, c2)
4127   if (N0C && N1C)
4128     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4129   // fold (sra 0, x) -> 0
4130   if (N0C && N0C->isNullValue())
4131     return N0;
4132   // fold (sra -1, x) -> -1
4133   if (N0C && N0C->isAllOnesValue())
4134     return N0;
4135   // fold (sra x, (setge c, size(x))) -> undef
4136   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4137     return DAG.getUNDEF(VT);
4138   // fold (sra x, 0) -> x
4139   if (N1C && N1C->isNullValue())
4140     return N0;
4141   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4142   // sext_inreg.
4143   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4144     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4145     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4146     if (VT.isVector())
4147       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4148                                ExtVT, VT.getVectorNumElements());
4149     if ((!LegalOperations ||
4150          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4151       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4152                          N0.getOperand(0), DAG.getValueType(ExtVT));
4153   }
4154
4155   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4156   if (N1C && N0.getOpcode() == ISD::SRA) {
4157     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4158       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4159       if (Sum >= OpSizeInBits)
4160         Sum = OpSizeInBits - 1;
4161       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4162                          DAG.getConstant(Sum, N1.getValueType()));
4163     }
4164   }
4165
4166   // fold (sra (shl X, m), (sub result_size, n))
4167   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4168   // result_size - n != m.
4169   // If truncate is free for the target sext(shl) is likely to result in better
4170   // code.
4171   if (N0.getOpcode() == ISD::SHL && N1C) {
4172     // Get the two constanst of the shifts, CN0 = m, CN = n.
4173     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4174     if (N01C) {
4175       LLVMContext &Ctx = *DAG.getContext();
4176       // Determine what the truncate's result bitsize and type would be.
4177       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4178
4179       if (VT.isVector())
4180         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4181
4182       // Determine the residual right-shift amount.
4183       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4184
4185       // If the shift is not a no-op (in which case this should be just a sign
4186       // extend already), the truncated to type is legal, sign_extend is legal
4187       // on that type, and the truncate to that type is both legal and free,
4188       // perform the transform.
4189       if ((ShiftAmt > 0) &&
4190           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4191           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4192           TLI.isTruncateFree(VT, TruncVT)) {
4193
4194           SDValue Amt = DAG.getConstant(ShiftAmt,
4195               getShiftAmountTy(N0.getOperand(0).getValueType()));
4196           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4197                                       N0.getOperand(0), Amt);
4198           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4199                                       Shift);
4200           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4201                              N->getValueType(0), Trunc);
4202       }
4203     }
4204   }
4205
4206   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4207   if (N1.getOpcode() == ISD::TRUNCATE &&
4208       N1.getOperand(0).getOpcode() == ISD::AND) {
4209     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4210     if (NewOp1.getNode())
4211       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4212   }
4213
4214   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4215   //      if c1 is equal to the number of bits the trunc removes
4216   if (N0.getOpcode() == ISD::TRUNCATE &&
4217       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4218        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4219       N0.getOperand(0).hasOneUse() &&
4220       N0.getOperand(0).getOperand(1).hasOneUse() &&
4221       N1C) {
4222     SDValue N0Op0 = N0.getOperand(0);
4223     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4224       unsigned LargeShiftVal = LargeShift->getZExtValue();
4225       EVT LargeVT = N0Op0.getValueType();
4226
4227       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4228         SDValue Amt =
4229           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4230                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4231         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4232                                   N0Op0.getOperand(0), Amt);
4233         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4234       }
4235     }
4236   }
4237
4238   // Simplify, based on bits shifted out of the LHS.
4239   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4240     return SDValue(N, 0);
4241
4242
4243   // If the sign bit is known to be zero, switch this to a SRL.
4244   if (DAG.SignBitIsZero(N0))
4245     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4246
4247   if (N1C) {
4248     SDValue NewSRA = visitShiftByConstant(N, N1C);
4249     if (NewSRA.getNode())
4250       return NewSRA;
4251   }
4252
4253   return SDValue();
4254 }
4255
4256 SDValue DAGCombiner::visitSRL(SDNode *N) {
4257   SDValue N0 = N->getOperand(0);
4258   SDValue N1 = N->getOperand(1);
4259   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4260   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4261   EVT VT = N0.getValueType();
4262   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4263
4264   // fold vector ops
4265   if (VT.isVector()) {
4266     SDValue FoldedVOp = SimplifyVBinOp(N);
4267     if (FoldedVOp.getNode()) return FoldedVOp;
4268
4269     N1C = isConstOrConstSplat(N1);
4270   }
4271
4272   // fold (srl c1, c2) -> c1 >>u c2
4273   if (N0C && N1C)
4274     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4275   // fold (srl 0, x) -> 0
4276   if (N0C && N0C->isNullValue())
4277     return N0;
4278   // fold (srl x, c >= size(x)) -> undef
4279   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4280     return DAG.getUNDEF(VT);
4281   // fold (srl x, 0) -> x
4282   if (N1C && N1C->isNullValue())
4283     return N0;
4284   // if (srl x, c) is known to be zero, return 0
4285   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4286                                    APInt::getAllOnesValue(OpSizeInBits)))
4287     return DAG.getConstant(0, VT);
4288
4289   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4290   if (N1C && N0.getOpcode() == ISD::SRL) {
4291     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4292       uint64_t c1 = N01C->getZExtValue();
4293       uint64_t c2 = N1C->getZExtValue();
4294       if (c1 + c2 >= OpSizeInBits)
4295         return DAG.getConstant(0, VT);
4296       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4297                          DAG.getConstant(c1 + c2, N1.getValueType()));
4298     }
4299   }
4300
4301   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4302   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4303       N0.getOperand(0).getOpcode() == ISD::SRL &&
4304       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4305     uint64_t c1 =
4306       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4307     uint64_t c2 = N1C->getZExtValue();
4308     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4309     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4310     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4311     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4312     if (c1 + OpSizeInBits == InnerShiftSize) {
4313       if (c1 + c2 >= InnerShiftSize)
4314         return DAG.getConstant(0, VT);
4315       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4316                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4317                                      N0.getOperand(0)->getOperand(0),
4318                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4319     }
4320   }
4321
4322   // fold (srl (shl x, c), c) -> (and x, cst2)
4323   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4324     unsigned BitSize = N0.getScalarValueSizeInBits();
4325     if (BitSize <= 64) {
4326       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4327       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4328                          DAG.getConstant(~0ULL >> ShAmt, VT));
4329     }
4330   }
4331
4332   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4333   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4334     // Shifting in all undef bits?
4335     EVT SmallVT = N0.getOperand(0).getValueType();
4336     unsigned BitSize = SmallVT.getScalarSizeInBits();
4337     if (N1C->getZExtValue() >= BitSize)
4338       return DAG.getUNDEF(VT);
4339
4340     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4341       uint64_t ShiftAmt = N1C->getZExtValue();
4342       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4343                                        N0.getOperand(0),
4344                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4345       AddToWorkList(SmallShift.getNode());
4346       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4347       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4348                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4349                          DAG.getConstant(Mask, VT));
4350     }
4351   }
4352
4353   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4354   // bit, which is unmodified by sra.
4355   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4356     if (N0.getOpcode() == ISD::SRA)
4357       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4358   }
4359
4360   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4361   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4362       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4363     APInt KnownZero, KnownOne;
4364     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4365
4366     // If any of the input bits are KnownOne, then the input couldn't be all
4367     // zeros, thus the result of the srl will always be zero.
4368     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4369
4370     // If all of the bits input the to ctlz node are known to be zero, then
4371     // the result of the ctlz is "32" and the result of the shift is one.
4372     APInt UnknownBits = ~KnownZero;
4373     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4374
4375     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4376     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4377       // Okay, we know that only that the single bit specified by UnknownBits
4378       // could be set on input to the CTLZ node. If this bit is set, the SRL
4379       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4380       // to an SRL/XOR pair, which is likely to simplify more.
4381       unsigned ShAmt = UnknownBits.countTrailingZeros();
4382       SDValue Op = N0.getOperand(0);
4383
4384       if (ShAmt) {
4385         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4386                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4387         AddToWorkList(Op.getNode());
4388       }
4389
4390       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4391                          Op, DAG.getConstant(1, VT));
4392     }
4393   }
4394
4395   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4396   if (N1.getOpcode() == ISD::TRUNCATE &&
4397       N1.getOperand(0).getOpcode() == ISD::AND) {
4398     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4399     if (NewOp1.getNode())
4400       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4401   }
4402
4403   // fold operands of srl based on knowledge that the low bits are not
4404   // demanded.
4405   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4406     return SDValue(N, 0);
4407
4408   if (N1C) {
4409     SDValue NewSRL = visitShiftByConstant(N, N1C);
4410     if (NewSRL.getNode())
4411       return NewSRL;
4412   }
4413
4414   // Attempt to convert a srl of a load into a narrower zero-extending load.
4415   SDValue NarrowLoad = ReduceLoadWidth(N);
4416   if (NarrowLoad.getNode())
4417     return NarrowLoad;
4418
4419   // Here is a common situation. We want to optimize:
4420   //
4421   //   %a = ...
4422   //   %b = and i32 %a, 2
4423   //   %c = srl i32 %b, 1
4424   //   brcond i32 %c ...
4425   //
4426   // into
4427   //
4428   //   %a = ...
4429   //   %b = and %a, 2
4430   //   %c = setcc eq %b, 0
4431   //   brcond %c ...
4432   //
4433   // However when after the source operand of SRL is optimized into AND, the SRL
4434   // itself may not be optimized further. Look for it and add the BRCOND into
4435   // the worklist.
4436   if (N->hasOneUse()) {
4437     SDNode *Use = *N->use_begin();
4438     if (Use->getOpcode() == ISD::BRCOND)
4439       AddToWorkList(Use);
4440     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4441       // Also look pass the truncate.
4442       Use = *Use->use_begin();
4443       if (Use->getOpcode() == ISD::BRCOND)
4444         AddToWorkList(Use);
4445     }
4446   }
4447
4448   return SDValue();
4449 }
4450
4451 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4452   SDValue N0 = N->getOperand(0);
4453   EVT VT = N->getValueType(0);
4454
4455   // fold (ctlz c1) -> c2
4456   if (isa<ConstantSDNode>(N0))
4457     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4458   return SDValue();
4459 }
4460
4461 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4462   SDValue N0 = N->getOperand(0);
4463   EVT VT = N->getValueType(0);
4464
4465   // fold (ctlz_zero_undef c1) -> c2
4466   if (isa<ConstantSDNode>(N0))
4467     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4468   return SDValue();
4469 }
4470
4471 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4472   SDValue N0 = N->getOperand(0);
4473   EVT VT = N->getValueType(0);
4474
4475   // fold (cttz c1) -> c2
4476   if (isa<ConstantSDNode>(N0))
4477     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4478   return SDValue();
4479 }
4480
4481 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4482   SDValue N0 = N->getOperand(0);
4483   EVT VT = N->getValueType(0);
4484
4485   // fold (cttz_zero_undef c1) -> c2
4486   if (isa<ConstantSDNode>(N0))
4487     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4488   return SDValue();
4489 }
4490
4491 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4492   SDValue N0 = N->getOperand(0);
4493   EVT VT = N->getValueType(0);
4494
4495   // fold (ctpop c1) -> c2
4496   if (isa<ConstantSDNode>(N0))
4497     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4498   return SDValue();
4499 }
4500
4501 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4502   SDValue N0 = N->getOperand(0);
4503   SDValue N1 = N->getOperand(1);
4504   SDValue N2 = N->getOperand(2);
4505   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4506   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4507   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4508   EVT VT = N->getValueType(0);
4509   EVT VT0 = N0.getValueType();
4510
4511   // fold (select C, X, X) -> X
4512   if (N1 == N2)
4513     return N1;
4514   // fold (select true, X, Y) -> X
4515   if (N0C && !N0C->isNullValue())
4516     return N1;
4517   // fold (select false, X, Y) -> Y
4518   if (N0C && N0C->isNullValue())
4519     return N2;
4520   // fold (select C, 1, X) -> (or C, X)
4521   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4522     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4523   // fold (select C, 0, 1) -> (xor C, 1)
4524   // We can't do this reliably if integer based booleans have different contents
4525   // to floating point based booleans. This is because we can't tell whether we
4526   // have an integer-based boolean or a floating-point-based boolean unless we
4527   // can find the SETCC that produced it and inspect its operands. This is
4528   // fairly easy if C is the SETCC node, but it can potentially be
4529   // undiscoverable (or not reasonably discoverable). For example, it could be
4530   // in another basic block or it could require searching a complicated
4531   // expression.
4532   if (VT.isInteger() &&
4533       (VT0 == MVT::i1 || (VT0.isInteger() &&
4534                           TLI.getBooleanContents(false, false) ==
4535                               TLI.getBooleanContents(false, true) &&
4536                           TLI.getBooleanContents(false, false) ==
4537                               TargetLowering::ZeroOrOneBooleanContent)) &&
4538       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4539     SDValue XORNode;
4540     if (VT == VT0)
4541       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4542                          N0, DAG.getConstant(1, VT0));
4543     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4544                           N0, DAG.getConstant(1, VT0));
4545     AddToWorkList(XORNode.getNode());
4546     if (VT.bitsGT(VT0))
4547       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4548     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4549   }
4550   // fold (select C, 0, X) -> (and (not C), X)
4551   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4552     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4553     AddToWorkList(NOTNode.getNode());
4554     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4555   }
4556   // fold (select C, X, 1) -> (or (not C), X)
4557   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4558     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4559     AddToWorkList(NOTNode.getNode());
4560     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4561   }
4562   // fold (select C, X, 0) -> (and C, X)
4563   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4564     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4565   // fold (select X, X, Y) -> (or X, Y)
4566   // fold (select X, 1, Y) -> (or X, Y)
4567   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4568     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4569   // fold (select X, Y, X) -> (and X, Y)
4570   // fold (select X, Y, 0) -> (and X, Y)
4571   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4572     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4573
4574   // If we can fold this based on the true/false value, do so.
4575   if (SimplifySelectOps(N, N1, N2))
4576     return SDValue(N, 0);  // Don't revisit N.
4577
4578   // fold selects based on a setcc into other things, such as min/max/abs
4579   if (N0.getOpcode() == ISD::SETCC) {
4580     if ((!LegalOperations &&
4581          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4582         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4583       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4584                          N0.getOperand(0), N0.getOperand(1),
4585                          N1, N2, N0.getOperand(2));
4586     return SimplifySelect(SDLoc(N), N0, N1, N2);
4587   }
4588
4589   return SDValue();
4590 }
4591
4592 static
4593 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4594   SDLoc DL(N);
4595   EVT LoVT, HiVT;
4596   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4597
4598   // Split the inputs.
4599   SDValue Lo, Hi, LL, LH, RL, RH;
4600   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4601   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4602
4603   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4604   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4605
4606   return std::make_pair(Lo, Hi);
4607 }
4608
4609 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4610 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4611 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4612   SDLoc dl(N);
4613   SDValue Cond = N->getOperand(0);
4614   SDValue LHS = N->getOperand(1);
4615   SDValue RHS = N->getOperand(2);
4616   MVT VT = N->getSimpleValueType(0);
4617   int NumElems = VT.getVectorNumElements();
4618   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4619          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4620          Cond.getOpcode() == ISD::BUILD_VECTOR);
4621
4622   // We're sure we have an even number of elements due to the
4623   // concat_vectors we have as arguments to vselect.
4624   // Skip BV elements until we find one that's not an UNDEF
4625   // After we find an UNDEF element, keep looping until we get to half the
4626   // length of the BV and see if all the non-undef nodes are the same.
4627   ConstantSDNode *BottomHalf = nullptr;
4628   for (int i = 0; i < NumElems / 2; ++i) {
4629     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4630       continue;
4631
4632     if (BottomHalf == nullptr)
4633       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4634     else if (Cond->getOperand(i).getNode() != BottomHalf)
4635       return SDValue();
4636   }
4637
4638   // Do the same for the second half of the BuildVector
4639   ConstantSDNode *TopHalf = nullptr;
4640   for (int i = NumElems / 2; i < NumElems; ++i) {
4641     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4642       continue;
4643
4644     if (TopHalf == nullptr)
4645       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4646     else if (Cond->getOperand(i).getNode() != TopHalf)
4647       return SDValue();
4648   }
4649
4650   assert(TopHalf && BottomHalf &&
4651          "One half of the selector was all UNDEFs and the other was all the "
4652          "same value. This should have been addressed before this function.");
4653   return DAG.getNode(
4654       ISD::CONCAT_VECTORS, dl, VT,
4655       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4656       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4657 }
4658
4659 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4660   SDValue N0 = N->getOperand(0);
4661   SDValue N1 = N->getOperand(1);
4662   SDValue N2 = N->getOperand(2);
4663   SDLoc DL(N);
4664
4665   // Canonicalize integer abs.
4666   // vselect (setg[te] X,  0),  X, -X ->
4667   // vselect (setgt    X, -1),  X, -X ->
4668   // vselect (setl[te] X,  0), -X,  X ->
4669   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4670   if (N0.getOpcode() == ISD::SETCC) {
4671     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4672     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4673     bool isAbs = false;
4674     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4675
4676     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4677          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4678         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4679       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4680     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4681              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4682       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4683
4684     if (isAbs) {
4685       EVT VT = LHS.getValueType();
4686       SDValue Shift = DAG.getNode(
4687           ISD::SRA, DL, VT, LHS,
4688           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4689       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4690       AddToWorkList(Shift.getNode());
4691       AddToWorkList(Add.getNode());
4692       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4693     }
4694   }
4695
4696   // If the VSELECT result requires splitting and the mask is provided by a
4697   // SETCC, then split both nodes and its operands before legalization. This
4698   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4699   // and enables future optimizations (e.g. min/max pattern matching on X86).
4700   if (N0.getOpcode() == ISD::SETCC) {
4701     EVT VT = N->getValueType(0);
4702
4703     // Check if any splitting is required.
4704     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4705         TargetLowering::TypeSplitVector)
4706       return SDValue();
4707
4708     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4709     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4710     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4711     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4712
4713     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4714     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4715
4716     // Add the new VSELECT nodes to the work list in case they need to be split
4717     // again.
4718     AddToWorkList(Lo.getNode());
4719     AddToWorkList(Hi.getNode());
4720
4721     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4722   }
4723
4724   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4725   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4726     return N1;
4727   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4728   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4729     return N2;
4730
4731   // The ConvertSelectToConcatVector function is assuming both the above
4732   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4733   // and addressed.
4734   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4735       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4736       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4737     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4738     if (CV.getNode())
4739       return CV;
4740   }
4741
4742   return SDValue();
4743 }
4744
4745 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4746   SDValue N0 = N->getOperand(0);
4747   SDValue N1 = N->getOperand(1);
4748   SDValue N2 = N->getOperand(2);
4749   SDValue N3 = N->getOperand(3);
4750   SDValue N4 = N->getOperand(4);
4751   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4752
4753   // fold select_cc lhs, rhs, x, x, cc -> x
4754   if (N2 == N3)
4755     return N2;
4756
4757   // Determine if the condition we're dealing with is constant
4758   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4759                               N0, N1, CC, SDLoc(N), false);
4760   if (SCC.getNode()) {
4761     AddToWorkList(SCC.getNode());
4762
4763     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4764       if (!SCCC->isNullValue())
4765         return N2;    // cond always true -> true val
4766       else
4767         return N3;    // cond always false -> false val
4768     }
4769
4770     // Fold to a simpler select_cc
4771     if (SCC.getOpcode() == ISD::SETCC)
4772       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4773                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4774                          SCC.getOperand(2));
4775   }
4776
4777   // If we can fold this based on the true/false value, do so.
4778   if (SimplifySelectOps(N, N2, N3))
4779     return SDValue(N, 0);  // Don't revisit N.
4780
4781   // fold select_cc into other things, such as min/max/abs
4782   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4783 }
4784
4785 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4786   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4787                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4788                        SDLoc(N));
4789 }
4790
4791 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4792 // dag node into a ConstantSDNode or a build_vector of constants.
4793 // This function is called by the DAGCombiner when visiting sext/zext/aext
4794 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4795 // Vector extends are not folded if operations are legal; this is to
4796 // avoid introducing illegal build_vector dag nodes.
4797 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4798                                          SelectionDAG &DAG, bool LegalTypes,
4799                                          bool LegalOperations) {
4800   unsigned Opcode = N->getOpcode();
4801   SDValue N0 = N->getOperand(0);
4802   EVT VT = N->getValueType(0);
4803
4804   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4805          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4806
4807   // fold (sext c1) -> c1
4808   // fold (zext c1) -> c1
4809   // fold (aext c1) -> c1
4810   if (isa<ConstantSDNode>(N0))
4811     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4812
4813   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4814   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4815   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4816   EVT SVT = VT.getScalarType();
4817   if (!(VT.isVector() &&
4818       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4819       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4820     return nullptr;
4821
4822   // We can fold this node into a build_vector.
4823   unsigned VTBits = SVT.getSizeInBits();
4824   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4825   unsigned ShAmt = VTBits - EVTBits;
4826   SmallVector<SDValue, 8> Elts;
4827   unsigned NumElts = N0->getNumOperands();
4828   SDLoc DL(N);
4829
4830   for (unsigned i=0; i != NumElts; ++i) {
4831     SDValue Op = N0->getOperand(i);
4832     if (Op->getOpcode() == ISD::UNDEF) {
4833       Elts.push_back(DAG.getUNDEF(SVT));
4834       continue;
4835     }
4836
4837     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4838     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4839     if (Opcode == ISD::SIGN_EXTEND)
4840       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4841                                      SVT));
4842     else
4843       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4844                                      SVT));
4845   }
4846
4847   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4848 }
4849
4850 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4851 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4852 // transformation. Returns true if extension are possible and the above
4853 // mentioned transformation is profitable.
4854 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4855                                     unsigned ExtOpc,
4856                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4857                                     const TargetLowering &TLI) {
4858   bool HasCopyToRegUses = false;
4859   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4860   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4861                             UE = N0.getNode()->use_end();
4862        UI != UE; ++UI) {
4863     SDNode *User = *UI;
4864     if (User == N)
4865       continue;
4866     if (UI.getUse().getResNo() != N0.getResNo())
4867       continue;
4868     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4869     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4870       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4871       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4872         // Sign bits will be lost after a zext.
4873         return false;
4874       bool Add = false;
4875       for (unsigned i = 0; i != 2; ++i) {
4876         SDValue UseOp = User->getOperand(i);
4877         if (UseOp == N0)
4878           continue;
4879         if (!isa<ConstantSDNode>(UseOp))
4880           return false;
4881         Add = true;
4882       }
4883       if (Add)
4884         ExtendNodes.push_back(User);
4885       continue;
4886     }
4887     // If truncates aren't free and there are users we can't
4888     // extend, it isn't worthwhile.
4889     if (!isTruncFree)
4890       return false;
4891     // Remember if this value is live-out.
4892     if (User->getOpcode() == ISD::CopyToReg)
4893       HasCopyToRegUses = true;
4894   }
4895
4896   if (HasCopyToRegUses) {
4897     bool BothLiveOut = false;
4898     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4899          UI != UE; ++UI) {
4900       SDUse &Use = UI.getUse();
4901       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4902         BothLiveOut = true;
4903         break;
4904       }
4905     }
4906     if (BothLiveOut)
4907       // Both unextended and extended values are live out. There had better be
4908       // a good reason for the transformation.
4909       return ExtendNodes.size();
4910   }
4911   return true;
4912 }
4913
4914 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4915                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4916                                   ISD::NodeType ExtType) {
4917   // Extend SetCC uses if necessary.
4918   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4919     SDNode *SetCC = SetCCs[i];
4920     SmallVector<SDValue, 4> Ops;
4921
4922     for (unsigned j = 0; j != 2; ++j) {
4923       SDValue SOp = SetCC->getOperand(j);
4924       if (SOp == Trunc)
4925         Ops.push_back(ExtLoad);
4926       else
4927         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4928     }
4929
4930     Ops.push_back(SetCC->getOperand(2));
4931     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4932   }
4933 }
4934
4935 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4936   SDValue N0 = N->getOperand(0);
4937   EVT VT = N->getValueType(0);
4938
4939   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4940                                               LegalOperations))
4941     return SDValue(Res, 0);
4942
4943   // fold (sext (sext x)) -> (sext x)
4944   // fold (sext (aext x)) -> (sext x)
4945   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4946     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4947                        N0.getOperand(0));
4948
4949   if (N0.getOpcode() == ISD::TRUNCATE) {
4950     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4951     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4952     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4953     if (NarrowLoad.getNode()) {
4954       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4955       if (NarrowLoad.getNode() != N0.getNode()) {
4956         CombineTo(N0.getNode(), NarrowLoad);
4957         // CombineTo deleted the truncate, if needed, but not what's under it.
4958         AddToWorkList(oye);
4959       }
4960       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4961     }
4962
4963     // See if the value being truncated is already sign extended.  If so, just
4964     // eliminate the trunc/sext pair.
4965     SDValue Op = N0.getOperand(0);
4966     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4967     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4968     unsigned DestBits = VT.getScalarType().getSizeInBits();
4969     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4970
4971     if (OpBits == DestBits) {
4972       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4973       // bits, it is already ready.
4974       if (NumSignBits > DestBits-MidBits)
4975         return Op;
4976     } else if (OpBits < DestBits) {
4977       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4978       // bits, just sext from i32.
4979       if (NumSignBits > OpBits-MidBits)
4980         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4981     } else {
4982       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4983       // bits, just truncate to i32.
4984       if (NumSignBits > OpBits-MidBits)
4985         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4986     }
4987
4988     // fold (sext (truncate x)) -> (sextinreg x).
4989     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4990                                                  N0.getValueType())) {
4991       if (OpBits < DestBits)
4992         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4993       else if (OpBits > DestBits)
4994         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4995       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4996                          DAG.getValueType(N0.getValueType()));
4997     }
4998   }
4999
5000   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5001   // None of the supported targets knows how to perform load and sign extend
5002   // on vectors in one instruction.  We only perform this transformation on
5003   // scalars.
5004   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5005       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5006       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5007        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5008     bool DoXform = true;
5009     SmallVector<SDNode*, 4> SetCCs;
5010     if (!N0.hasOneUse())
5011       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5012     if (DoXform) {
5013       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5014       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5015                                        LN0->getChain(),
5016                                        LN0->getBasePtr(), N0.getValueType(),
5017                                        LN0->getMemOperand());
5018       CombineTo(N, ExtLoad);
5019       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5020                                   N0.getValueType(), ExtLoad);
5021       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5022       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5023                       ISD::SIGN_EXTEND);
5024       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5025     }
5026   }
5027
5028   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5029   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5030   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5031       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5032     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5033     EVT MemVT = LN0->getMemoryVT();
5034     if ((!LegalOperations && !LN0->isVolatile()) ||
5035         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5036       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5037                                        LN0->getChain(),
5038                                        LN0->getBasePtr(), MemVT,
5039                                        LN0->getMemOperand());
5040       CombineTo(N, ExtLoad);
5041       CombineTo(N0.getNode(),
5042                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5043                             N0.getValueType(), ExtLoad),
5044                 ExtLoad.getValue(1));
5045       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5046     }
5047   }
5048
5049   // fold (sext (and/or/xor (load x), cst)) ->
5050   //      (and/or/xor (sextload x), (sext cst))
5051   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5052        N0.getOpcode() == ISD::XOR) &&
5053       isa<LoadSDNode>(N0.getOperand(0)) &&
5054       N0.getOperand(1).getOpcode() == ISD::Constant &&
5055       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5056       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5057     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5058     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5059       bool DoXform = true;
5060       SmallVector<SDNode*, 4> SetCCs;
5061       if (!N0.hasOneUse())
5062         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5063                                           SetCCs, TLI);
5064       if (DoXform) {
5065         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5066                                          LN0->getChain(), LN0->getBasePtr(),
5067                                          LN0->getMemoryVT(),
5068                                          LN0->getMemOperand());
5069         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5070         Mask = Mask.sext(VT.getSizeInBits());
5071         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5072                                   ExtLoad, DAG.getConstant(Mask, VT));
5073         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5074                                     SDLoc(N0.getOperand(0)),
5075                                     N0.getOperand(0).getValueType(), ExtLoad);
5076         CombineTo(N, And);
5077         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5078         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5079                         ISD::SIGN_EXTEND);
5080         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5081       }
5082     }
5083   }
5084
5085   if (N0.getOpcode() == ISD::SETCC) {
5086     EVT N0VT = N0.getOperand(0).getValueType();
5087     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5088     // Only do this before legalize for now.
5089     if (VT.isVector() && !LegalOperations &&
5090         TLI.getBooleanContents(N0VT) ==
5091             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5092       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5093       // of the same size as the compared operands. Only optimize sext(setcc())
5094       // if this is the case.
5095       EVT SVT = getSetCCResultType(N0VT);
5096
5097       // We know that the # elements of the results is the same as the
5098       // # elements of the compare (and the # elements of the compare result
5099       // for that matter).  Check to see that they are the same size.  If so,
5100       // we know that the element size of the sext'd result matches the
5101       // element size of the compare operands.
5102       if (VT.getSizeInBits() == SVT.getSizeInBits())
5103         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5104                              N0.getOperand(1),
5105                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5106
5107       // If the desired elements are smaller or larger than the source
5108       // elements we can use a matching integer vector type and then
5109       // truncate/sign extend
5110       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5111       if (SVT == MatchingVectorType) {
5112         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5113                                N0.getOperand(0), N0.getOperand(1),
5114                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5115         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5116       }
5117     }
5118
5119     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5120     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5121     SDValue NegOne =
5122       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5123     SDValue SCC =
5124       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5125                        NegOne, DAG.getConstant(0, VT),
5126                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5127     if (SCC.getNode()) return SCC;
5128
5129     if (!VT.isVector()) {
5130       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5131       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5132         SDLoc DL(N);
5133         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5134         SDValue SetCC = DAG.getSetCC(DL,
5135                                      SetCCVT,
5136                                      N0.getOperand(0), N0.getOperand(1), CC);
5137         EVT SelectVT = getSetCCResultType(VT);
5138         return DAG.getSelect(DL, VT,
5139                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5140                              NegOne, DAG.getConstant(0, VT));
5141
5142       }
5143     }
5144   }
5145
5146   // fold (sext x) -> (zext x) if the sign bit is known zero.
5147   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5148       DAG.SignBitIsZero(N0))
5149     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5150
5151   return SDValue();
5152 }
5153
5154 // isTruncateOf - If N is a truncate of some other value, return true, record
5155 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5156 // This function computes KnownZero to avoid a duplicated call to
5157 // computeKnownBits in the caller.
5158 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5159                          APInt &KnownZero) {
5160   APInt KnownOne;
5161   if (N->getOpcode() == ISD::TRUNCATE) {
5162     Op = N->getOperand(0);
5163     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5164     return true;
5165   }
5166
5167   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5168       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5169     return false;
5170
5171   SDValue Op0 = N->getOperand(0);
5172   SDValue Op1 = N->getOperand(1);
5173   assert(Op0.getValueType() == Op1.getValueType());
5174
5175   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5176   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5177   if (COp0 && COp0->isNullValue())
5178     Op = Op1;
5179   else if (COp1 && COp1->isNullValue())
5180     Op = Op0;
5181   else
5182     return false;
5183
5184   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5185
5186   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5187     return false;
5188
5189   return true;
5190 }
5191
5192 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5193   SDValue N0 = N->getOperand(0);
5194   EVT VT = N->getValueType(0);
5195
5196   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5197                                               LegalOperations))
5198     return SDValue(Res, 0);
5199
5200   // fold (zext (zext x)) -> (zext x)
5201   // fold (zext (aext x)) -> (zext x)
5202   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5203     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5204                        N0.getOperand(0));
5205
5206   // fold (zext (truncate x)) -> (zext x) or
5207   //      (zext (truncate x)) -> (truncate x)
5208   // This is valid when the truncated bits of x are already zero.
5209   // FIXME: We should extend this to work for vectors too.
5210   SDValue Op;
5211   APInt KnownZero;
5212   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5213     APInt TruncatedBits =
5214       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5215       APInt(Op.getValueSizeInBits(), 0) :
5216       APInt::getBitsSet(Op.getValueSizeInBits(),
5217                         N0.getValueSizeInBits(),
5218                         std::min(Op.getValueSizeInBits(),
5219                                  VT.getSizeInBits()));
5220     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5221       if (VT.bitsGT(Op.getValueType()))
5222         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5223       if (VT.bitsLT(Op.getValueType()))
5224         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5225
5226       return Op;
5227     }
5228   }
5229
5230   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5231   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5232   if (N0.getOpcode() == ISD::TRUNCATE) {
5233     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5234     if (NarrowLoad.getNode()) {
5235       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5236       if (NarrowLoad.getNode() != N0.getNode()) {
5237         CombineTo(N0.getNode(), NarrowLoad);
5238         // CombineTo deleted the truncate, if needed, but not what's under it.
5239         AddToWorkList(oye);
5240       }
5241       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5242     }
5243   }
5244
5245   // fold (zext (truncate x)) -> (and x, mask)
5246   if (N0.getOpcode() == ISD::TRUNCATE &&
5247       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5248
5249     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5250     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5251     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5252     if (NarrowLoad.getNode()) {
5253       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5254       if (NarrowLoad.getNode() != N0.getNode()) {
5255         CombineTo(N0.getNode(), NarrowLoad);
5256         // CombineTo deleted the truncate, if needed, but not what's under it.
5257         AddToWorkList(oye);
5258       }
5259       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5260     }
5261
5262     SDValue Op = N0.getOperand(0);
5263     if (Op.getValueType().bitsLT(VT)) {
5264       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5265       AddToWorkList(Op.getNode());
5266     } else if (Op.getValueType().bitsGT(VT)) {
5267       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5268       AddToWorkList(Op.getNode());
5269     }
5270     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5271                                   N0.getValueType().getScalarType());
5272   }
5273
5274   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5275   // if either of the casts is not free.
5276   if (N0.getOpcode() == ISD::AND &&
5277       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5278       N0.getOperand(1).getOpcode() == ISD::Constant &&
5279       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5280                            N0.getValueType()) ||
5281        !TLI.isZExtFree(N0.getValueType(), VT))) {
5282     SDValue X = N0.getOperand(0).getOperand(0);
5283     if (X.getValueType().bitsLT(VT)) {
5284       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5285     } else if (X.getValueType().bitsGT(VT)) {
5286       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5287     }
5288     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5289     Mask = Mask.zext(VT.getSizeInBits());
5290     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5291                        X, DAG.getConstant(Mask, VT));
5292   }
5293
5294   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5295   // None of the supported targets knows how to perform load and vector_zext
5296   // on vectors in one instruction.  We only perform this transformation on
5297   // scalars.
5298   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5299       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5300       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5301        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5302     bool DoXform = true;
5303     SmallVector<SDNode*, 4> SetCCs;
5304     if (!N0.hasOneUse())
5305       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5306     if (DoXform) {
5307       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5308       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5309                                        LN0->getChain(),
5310                                        LN0->getBasePtr(), N0.getValueType(),
5311                                        LN0->getMemOperand());
5312       CombineTo(N, ExtLoad);
5313       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5314                                   N0.getValueType(), ExtLoad);
5315       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5316
5317       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5318                       ISD::ZERO_EXTEND);
5319       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5320     }
5321   }
5322
5323   // fold (zext (and/or/xor (load x), cst)) ->
5324   //      (and/or/xor (zextload x), (zext cst))
5325   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5326        N0.getOpcode() == ISD::XOR) &&
5327       isa<LoadSDNode>(N0.getOperand(0)) &&
5328       N0.getOperand(1).getOpcode() == ISD::Constant &&
5329       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5330       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5331     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5332     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5333       bool DoXform = true;
5334       SmallVector<SDNode*, 4> SetCCs;
5335       if (!N0.hasOneUse())
5336         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5337                                           SetCCs, TLI);
5338       if (DoXform) {
5339         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5340                                          LN0->getChain(), LN0->getBasePtr(),
5341                                          LN0->getMemoryVT(),
5342                                          LN0->getMemOperand());
5343         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5344         Mask = Mask.zext(VT.getSizeInBits());
5345         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5346                                   ExtLoad, DAG.getConstant(Mask, VT));
5347         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5348                                     SDLoc(N0.getOperand(0)),
5349                                     N0.getOperand(0).getValueType(), ExtLoad);
5350         CombineTo(N, And);
5351         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5352         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5353                         ISD::ZERO_EXTEND);
5354         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5355       }
5356     }
5357   }
5358
5359   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5360   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5361   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5362       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5363     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5364     EVT MemVT = LN0->getMemoryVT();
5365     if ((!LegalOperations && !LN0->isVolatile()) ||
5366         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5367       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5368                                        LN0->getChain(),
5369                                        LN0->getBasePtr(), MemVT,
5370                                        LN0->getMemOperand());
5371       CombineTo(N, ExtLoad);
5372       CombineTo(N0.getNode(),
5373                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5374                             ExtLoad),
5375                 ExtLoad.getValue(1));
5376       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5377     }
5378   }
5379
5380   if (N0.getOpcode() == ISD::SETCC) {
5381     if (!LegalOperations && VT.isVector() &&
5382         N0.getValueType().getVectorElementType() == MVT::i1) {
5383       EVT N0VT = N0.getOperand(0).getValueType();
5384       if (getSetCCResultType(N0VT) == N0.getValueType())
5385         return SDValue();
5386
5387       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5388       // Only do this before legalize for now.
5389       EVT EltVT = VT.getVectorElementType();
5390       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5391                                     DAG.getConstant(1, EltVT));
5392       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5393         // We know that the # elements of the results is the same as the
5394         // # elements of the compare (and the # elements of the compare result
5395         // for that matter).  Check to see that they are the same size.  If so,
5396         // we know that the element size of the sext'd result matches the
5397         // element size of the compare operands.
5398         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5399                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5400                                          N0.getOperand(1),
5401                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5402                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5403                                        OneOps));
5404
5405       // If the desired elements are smaller or larger than the source
5406       // elements we can use a matching integer vector type and then
5407       // truncate/sign extend
5408       EVT MatchingElementType =
5409         EVT::getIntegerVT(*DAG.getContext(),
5410                           N0VT.getScalarType().getSizeInBits());
5411       EVT MatchingVectorType =
5412         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5413                          N0VT.getVectorNumElements());
5414       SDValue VsetCC =
5415         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5416                       N0.getOperand(1),
5417                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5418       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5419                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5420                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5421     }
5422
5423     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5424     SDValue SCC =
5425       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5426                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5427                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5428     if (SCC.getNode()) return SCC;
5429   }
5430
5431   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5432   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5433       isa<ConstantSDNode>(N0.getOperand(1)) &&
5434       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5435       N0.hasOneUse()) {
5436     SDValue ShAmt = N0.getOperand(1);
5437     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5438     if (N0.getOpcode() == ISD::SHL) {
5439       SDValue InnerZExt = N0.getOperand(0);
5440       // If the original shl may be shifting out bits, do not perform this
5441       // transformation.
5442       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5443         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5444       if (ShAmtVal > KnownZeroBits)
5445         return SDValue();
5446     }
5447
5448     SDLoc DL(N);
5449
5450     // Ensure that the shift amount is wide enough for the shifted value.
5451     if (VT.getSizeInBits() >= 256)
5452       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5453
5454     return DAG.getNode(N0.getOpcode(), DL, VT,
5455                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5456                        ShAmt);
5457   }
5458
5459   return SDValue();
5460 }
5461
5462 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5463   SDValue N0 = N->getOperand(0);
5464   EVT VT = N->getValueType(0);
5465
5466   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5467                                               LegalOperations))
5468     return SDValue(Res, 0);
5469
5470   // fold (aext (aext x)) -> (aext x)
5471   // fold (aext (zext x)) -> (zext x)
5472   // fold (aext (sext x)) -> (sext x)
5473   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5474       N0.getOpcode() == ISD::ZERO_EXTEND ||
5475       N0.getOpcode() == ISD::SIGN_EXTEND)
5476     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5477
5478   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5479   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5480   if (N0.getOpcode() == ISD::TRUNCATE) {
5481     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5482     if (NarrowLoad.getNode()) {
5483       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5484       if (NarrowLoad.getNode() != N0.getNode()) {
5485         CombineTo(N0.getNode(), NarrowLoad);
5486         // CombineTo deleted the truncate, if needed, but not what's under it.
5487         AddToWorkList(oye);
5488       }
5489       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5490     }
5491   }
5492
5493   // fold (aext (truncate x))
5494   if (N0.getOpcode() == ISD::TRUNCATE) {
5495     SDValue TruncOp = N0.getOperand(0);
5496     if (TruncOp.getValueType() == VT)
5497       return TruncOp; // x iff x size == zext size.
5498     if (TruncOp.getValueType().bitsGT(VT))
5499       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5500     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5501   }
5502
5503   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5504   // if the trunc is not free.
5505   if (N0.getOpcode() == ISD::AND &&
5506       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5507       N0.getOperand(1).getOpcode() == ISD::Constant &&
5508       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5509                           N0.getValueType())) {
5510     SDValue X = N0.getOperand(0).getOperand(0);
5511     if (X.getValueType().bitsLT(VT)) {
5512       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5513     } else if (X.getValueType().bitsGT(VT)) {
5514       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5515     }
5516     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5517     Mask = Mask.zext(VT.getSizeInBits());
5518     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5519                        X, DAG.getConstant(Mask, VT));
5520   }
5521
5522   // fold (aext (load x)) -> (aext (truncate (extload x)))
5523   // None of the supported targets knows how to perform load and any_ext
5524   // on vectors in one instruction.  We only perform this transformation on
5525   // scalars.
5526   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5527       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5528       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5529     bool DoXform = true;
5530     SmallVector<SDNode*, 4> SetCCs;
5531     if (!N0.hasOneUse())
5532       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5533     if (DoXform) {
5534       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5535       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5536                                        LN0->getChain(),
5537                                        LN0->getBasePtr(), N0.getValueType(),
5538                                        LN0->getMemOperand());
5539       CombineTo(N, ExtLoad);
5540       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5541                                   N0.getValueType(), ExtLoad);
5542       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5543       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5544                       ISD::ANY_EXTEND);
5545       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5546     }
5547   }
5548
5549   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5550   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5551   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5552   if (N0.getOpcode() == ISD::LOAD &&
5553       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5554       N0.hasOneUse()) {
5555     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5556     ISD::LoadExtType ExtType = LN0->getExtensionType();
5557     EVT MemVT = LN0->getMemoryVT();
5558     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5559       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5560                                        VT, LN0->getChain(), LN0->getBasePtr(),
5561                                        MemVT, LN0->getMemOperand());
5562       CombineTo(N, ExtLoad);
5563       CombineTo(N0.getNode(),
5564                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5565                             N0.getValueType(), ExtLoad),
5566                 ExtLoad.getValue(1));
5567       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5568     }
5569   }
5570
5571   if (N0.getOpcode() == ISD::SETCC) {
5572     // For vectors:
5573     // aext(setcc) -> vsetcc
5574     // aext(setcc) -> truncate(vsetcc)
5575     // aext(setcc) -> aext(vsetcc)
5576     // Only do this before legalize for now.
5577     if (VT.isVector() && !LegalOperations) {
5578       EVT N0VT = N0.getOperand(0).getValueType();
5579         // We know that the # elements of the results is the same as the
5580         // # elements of the compare (and the # elements of the compare result
5581         // for that matter).  Check to see that they are the same size.  If so,
5582         // we know that the element size of the sext'd result matches the
5583         // element size of the compare operands.
5584       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5585         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5586                              N0.getOperand(1),
5587                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5588       // If the desired elements are smaller or larger than the source
5589       // elements we can use a matching integer vector type and then
5590       // truncate/any extend
5591       else {
5592         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5593         SDValue VsetCC =
5594           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5595                         N0.getOperand(1),
5596                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5597         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5598       }
5599     }
5600
5601     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5602     SDValue SCC =
5603       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5604                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5605                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5606     if (SCC.getNode())
5607       return SCC;
5608   }
5609
5610   return SDValue();
5611 }
5612
5613 /// GetDemandedBits - See if the specified operand can be simplified with the
5614 /// knowledge that only the bits specified by Mask are used.  If so, return the
5615 /// simpler operand, otherwise return a null SDValue.
5616 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5617   switch (V.getOpcode()) {
5618   default: break;
5619   case ISD::Constant: {
5620     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5621     assert(CV && "Const value should be ConstSDNode.");
5622     const APInt &CVal = CV->getAPIntValue();
5623     APInt NewVal = CVal & Mask;
5624     if (NewVal != CVal)
5625       return DAG.getConstant(NewVal, V.getValueType());
5626     break;
5627   }
5628   case ISD::OR:
5629   case ISD::XOR:
5630     // If the LHS or RHS don't contribute bits to the or, drop them.
5631     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5632       return V.getOperand(1);
5633     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5634       return V.getOperand(0);
5635     break;
5636   case ISD::SRL:
5637     // Only look at single-use SRLs.
5638     if (!V.getNode()->hasOneUse())
5639       break;
5640     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5641       // See if we can recursively simplify the LHS.
5642       unsigned Amt = RHSC->getZExtValue();
5643
5644       // Watch out for shift count overflow though.
5645       if (Amt >= Mask.getBitWidth()) break;
5646       APInt NewMask = Mask << Amt;
5647       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5648       if (SimplifyLHS.getNode())
5649         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5650                            SimplifyLHS, V.getOperand(1));
5651     }
5652   }
5653   return SDValue();
5654 }
5655
5656 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5657 /// bits and then truncated to a narrower type and where N is a multiple
5658 /// of number of bits of the narrower type, transform it to a narrower load
5659 /// from address + N / num of bits of new type. If the result is to be
5660 /// extended, also fold the extension to form a extending load.
5661 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5662   unsigned Opc = N->getOpcode();
5663
5664   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5665   SDValue N0 = N->getOperand(0);
5666   EVT VT = N->getValueType(0);
5667   EVT ExtVT = VT;
5668
5669   // This transformation isn't valid for vector loads.
5670   if (VT.isVector())
5671     return SDValue();
5672
5673   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5674   // extended to VT.
5675   if (Opc == ISD::SIGN_EXTEND_INREG) {
5676     ExtType = ISD::SEXTLOAD;
5677     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5678   } else if (Opc == ISD::SRL) {
5679     // Another special-case: SRL is basically zero-extending a narrower value.
5680     ExtType = ISD::ZEXTLOAD;
5681     N0 = SDValue(N, 0);
5682     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5683     if (!N01) return SDValue();
5684     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5685                               VT.getSizeInBits() - N01->getZExtValue());
5686   }
5687   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5688     return SDValue();
5689
5690   unsigned EVTBits = ExtVT.getSizeInBits();
5691
5692   // Do not generate loads of non-round integer types since these can
5693   // be expensive (and would be wrong if the type is not byte sized).
5694   if (!ExtVT.isRound())
5695     return SDValue();
5696
5697   unsigned ShAmt = 0;
5698   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5699     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5700       ShAmt = N01->getZExtValue();
5701       // Is the shift amount a multiple of size of VT?
5702       if ((ShAmt & (EVTBits-1)) == 0) {
5703         N0 = N0.getOperand(0);
5704         // Is the load width a multiple of size of VT?
5705         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5706           return SDValue();
5707       }
5708
5709       // At this point, we must have a load or else we can't do the transform.
5710       if (!isa<LoadSDNode>(N0)) return SDValue();
5711
5712       // Because a SRL must be assumed to *need* to zero-extend the high bits
5713       // (as opposed to anyext the high bits), we can't combine the zextload
5714       // lowering of SRL and an sextload.
5715       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5716         return SDValue();
5717
5718       // If the shift amount is larger than the input type then we're not
5719       // accessing any of the loaded bytes.  If the load was a zextload/extload
5720       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5721       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5722         return SDValue();
5723     }
5724   }
5725
5726   // If the load is shifted left (and the result isn't shifted back right),
5727   // we can fold the truncate through the shift.
5728   unsigned ShLeftAmt = 0;
5729   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5730       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5731     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5732       ShLeftAmt = N01->getZExtValue();
5733       N0 = N0.getOperand(0);
5734     }
5735   }
5736
5737   // If we haven't found a load, we can't narrow it.  Don't transform one with
5738   // multiple uses, this would require adding a new load.
5739   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5740     return SDValue();
5741
5742   // Don't change the width of a volatile load.
5743   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5744   if (LN0->isVolatile())
5745     return SDValue();
5746
5747   // Verify that we are actually reducing a load width here.
5748   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5749     return SDValue();
5750
5751   // For the transform to be legal, the load must produce only two values
5752   // (the value loaded and the chain).  Don't transform a pre-increment
5753   // load, for example, which produces an extra value.  Otherwise the
5754   // transformation is not equivalent, and the downstream logic to replace
5755   // uses gets things wrong.
5756   if (LN0->getNumValues() > 2)
5757     return SDValue();
5758
5759   // If the load that we're shrinking is an extload and we're not just
5760   // discarding the extension we can't simply shrink the load. Bail.
5761   // TODO: It would be possible to merge the extensions in some cases.
5762   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5763       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5764     return SDValue();
5765
5766   EVT PtrType = N0.getOperand(1).getValueType();
5767
5768   if (PtrType == MVT::Untyped || PtrType.isExtended())
5769     // It's not possible to generate a constant of extended or untyped type.
5770     return SDValue();
5771
5772   // For big endian targets, we need to adjust the offset to the pointer to
5773   // load the correct bytes.
5774   if (TLI.isBigEndian()) {
5775     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5776     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5777     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5778   }
5779
5780   uint64_t PtrOff = ShAmt / 8;
5781   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5782   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5783                                PtrType, LN0->getBasePtr(),
5784                                DAG.getConstant(PtrOff, PtrType));
5785   AddToWorkList(NewPtr.getNode());
5786
5787   SDValue Load;
5788   if (ExtType == ISD::NON_EXTLOAD)
5789     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5790                         LN0->getPointerInfo().getWithOffset(PtrOff),
5791                         LN0->isVolatile(), LN0->isNonTemporal(),
5792                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5793   else
5794     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5795                           LN0->getPointerInfo().getWithOffset(PtrOff),
5796                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5797                           NewAlign, LN0->getTBAAInfo());
5798
5799   // Replace the old load's chain with the new load's chain.
5800   WorkListRemover DeadNodes(*this);
5801   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5802
5803   // Shift the result left, if we've swallowed a left shift.
5804   SDValue Result = Load;
5805   if (ShLeftAmt != 0) {
5806     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5807     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5808       ShImmTy = VT;
5809     // If the shift amount is as large as the result size (but, presumably,
5810     // no larger than the source) then the useful bits of the result are
5811     // zero; we can't simply return the shortened shift, because the result
5812     // of that operation is undefined.
5813     if (ShLeftAmt >= VT.getSizeInBits())
5814       Result = DAG.getConstant(0, VT);
5815     else
5816       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5817                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5818   }
5819
5820   // Return the new loaded value.
5821   return Result;
5822 }
5823
5824 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5825   SDValue N0 = N->getOperand(0);
5826   SDValue N1 = N->getOperand(1);
5827   EVT VT = N->getValueType(0);
5828   EVT EVT = cast<VTSDNode>(N1)->getVT();
5829   unsigned VTBits = VT.getScalarType().getSizeInBits();
5830   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5831
5832   // fold (sext_in_reg c1) -> c1
5833   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5834     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5835
5836   // If the input is already sign extended, just drop the extension.
5837   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5838     return N0;
5839
5840   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5841   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5842       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5843     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5844                        N0.getOperand(0), N1);
5845
5846   // fold (sext_in_reg (sext x)) -> (sext x)
5847   // fold (sext_in_reg (aext x)) -> (sext x)
5848   // if x is small enough.
5849   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5850     SDValue N00 = N0.getOperand(0);
5851     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5852         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5853       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5854   }
5855
5856   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5857   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5858     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5859
5860   // fold operands of sext_in_reg based on knowledge that the top bits are not
5861   // demanded.
5862   if (SimplifyDemandedBits(SDValue(N, 0)))
5863     return SDValue(N, 0);
5864
5865   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5866   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5867   SDValue NarrowLoad = ReduceLoadWidth(N);
5868   if (NarrowLoad.getNode())
5869     return NarrowLoad;
5870
5871   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5872   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5873   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5874   if (N0.getOpcode() == ISD::SRL) {
5875     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5876       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5877         // We can turn this into an SRA iff the input to the SRL is already sign
5878         // extended enough.
5879         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5880         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5881           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5882                              N0.getOperand(0), N0.getOperand(1));
5883       }
5884   }
5885
5886   // fold (sext_inreg (extload x)) -> (sextload x)
5887   if (ISD::isEXTLoad(N0.getNode()) &&
5888       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5890       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5891        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5892     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5893     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5894                                      LN0->getChain(),
5895                                      LN0->getBasePtr(), EVT,
5896                                      LN0->getMemOperand());
5897     CombineTo(N, ExtLoad);
5898     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5899     AddToWorkList(ExtLoad.getNode());
5900     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5901   }
5902   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5903   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5904       N0.hasOneUse() &&
5905       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5906       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5907        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5908     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5909     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5910                                      LN0->getChain(),
5911                                      LN0->getBasePtr(), EVT,
5912                                      LN0->getMemOperand());
5913     CombineTo(N, ExtLoad);
5914     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5915     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5916   }
5917
5918   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5919   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5920     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5921                                        N0.getOperand(1), false);
5922     if (BSwap.getNode())
5923       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5924                          BSwap, N1);
5925   }
5926
5927   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5928   // into a build_vector.
5929   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5930     SmallVector<SDValue, 8> Elts;
5931     unsigned NumElts = N0->getNumOperands();
5932     unsigned ShAmt = VTBits - EVTBits;
5933
5934     for (unsigned i = 0; i != NumElts; ++i) {
5935       SDValue Op = N0->getOperand(i);
5936       if (Op->getOpcode() == ISD::UNDEF) {
5937         Elts.push_back(Op);
5938         continue;
5939       }
5940
5941       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5942       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5943       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5944                                      Op.getValueType()));
5945     }
5946
5947     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5948   }
5949
5950   return SDValue();
5951 }
5952
5953 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5954   SDValue N0 = N->getOperand(0);
5955   EVT VT = N->getValueType(0);
5956   bool isLE = TLI.isLittleEndian();
5957
5958   // noop truncate
5959   if (N0.getValueType() == N->getValueType(0))
5960     return N0;
5961   // fold (truncate c1) -> c1
5962   if (isa<ConstantSDNode>(N0))
5963     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5964   // fold (truncate (truncate x)) -> (truncate x)
5965   if (N0.getOpcode() == ISD::TRUNCATE)
5966     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5967   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5968   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5969       N0.getOpcode() == ISD::SIGN_EXTEND ||
5970       N0.getOpcode() == ISD::ANY_EXTEND) {
5971     if (N0.getOperand(0).getValueType().bitsLT(VT))
5972       // if the source is smaller than the dest, we still need an extend
5973       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5974                          N0.getOperand(0));
5975     if (N0.getOperand(0).getValueType().bitsGT(VT))
5976       // if the source is larger than the dest, than we just need the truncate
5977       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5978     // if the source and dest are the same type, we can drop both the extend
5979     // and the truncate.
5980     return N0.getOperand(0);
5981   }
5982
5983   // Fold extract-and-trunc into a narrow extract. For example:
5984   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5985   //   i32 y = TRUNCATE(i64 x)
5986   //        -- becomes --
5987   //   v16i8 b = BITCAST (v2i64 val)
5988   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5989   //
5990   // Note: We only run this optimization after type legalization (which often
5991   // creates this pattern) and before operation legalization after which
5992   // we need to be more careful about the vector instructions that we generate.
5993   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5994       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5995
5996     EVT VecTy = N0.getOperand(0).getValueType();
5997     EVT ExTy = N0.getValueType();
5998     EVT TrTy = N->getValueType(0);
5999
6000     unsigned NumElem = VecTy.getVectorNumElements();
6001     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6002
6003     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6004     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6005
6006     SDValue EltNo = N0->getOperand(1);
6007     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6008       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6009       EVT IndexTy = TLI.getVectorIdxTy();
6010       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6011
6012       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6013                               NVT, N0.getOperand(0));
6014
6015       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6016                          SDLoc(N), TrTy, V,
6017                          DAG.getConstant(Index, IndexTy));
6018     }
6019   }
6020
6021   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6022   if (N0.getOpcode() == ISD::SELECT) {
6023     EVT SrcVT = N0.getValueType();
6024     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6025         TLI.isTruncateFree(SrcVT, VT)) {
6026       SDLoc SL(N0);
6027       SDValue Cond = N0.getOperand(0);
6028       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6029       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6030       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6031     }
6032   }
6033
6034   // Fold a series of buildvector, bitcast, and truncate if possible.
6035   // For example fold
6036   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6037   //   (2xi32 (buildvector x, y)).
6038   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6039       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6040       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6041       N0.getOperand(0).hasOneUse()) {
6042
6043     SDValue BuildVect = N0.getOperand(0);
6044     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6045     EVT TruncVecEltTy = VT.getVectorElementType();
6046
6047     // Check that the element types match.
6048     if (BuildVectEltTy == TruncVecEltTy) {
6049       // Now we only need to compute the offset of the truncated elements.
6050       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6051       unsigned TruncVecNumElts = VT.getVectorNumElements();
6052       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6053
6054       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6055              "Invalid number of elements");
6056
6057       SmallVector<SDValue, 8> Opnds;
6058       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6059         Opnds.push_back(BuildVect.getOperand(i));
6060
6061       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6062     }
6063   }
6064
6065   // See if we can simplify the input to this truncate through knowledge that
6066   // only the low bits are being used.
6067   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6068   // Currently we only perform this optimization on scalars because vectors
6069   // may have different active low bits.
6070   if (!VT.isVector()) {
6071     SDValue Shorter =
6072       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6073                                                VT.getSizeInBits()));
6074     if (Shorter.getNode())
6075       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6076   }
6077   // fold (truncate (load x)) -> (smaller load x)
6078   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6079   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6080     SDValue Reduced = ReduceLoadWidth(N);
6081     if (Reduced.getNode())
6082       return Reduced;
6083     // Handle the case where the load remains an extending load even
6084     // after truncation.
6085     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6086       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6087       if (!LN0->isVolatile() &&
6088           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6089         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6090                                          VT, LN0->getChain(), LN0->getBasePtr(),
6091                                          LN0->getMemoryVT(),
6092                                          LN0->getMemOperand());
6093         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6094         return NewLoad;
6095       }
6096     }
6097   }
6098   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6099   // where ... are all 'undef'.
6100   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6101     SmallVector<EVT, 8> VTs;
6102     SDValue V;
6103     unsigned Idx = 0;
6104     unsigned NumDefs = 0;
6105
6106     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6107       SDValue X = N0.getOperand(i);
6108       if (X.getOpcode() != ISD::UNDEF) {
6109         V = X;
6110         Idx = i;
6111         NumDefs++;
6112       }
6113       // Stop if more than one members are non-undef.
6114       if (NumDefs > 1)
6115         break;
6116       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6117                                      VT.getVectorElementType(),
6118                                      X.getValueType().getVectorNumElements()));
6119     }
6120
6121     if (NumDefs == 0)
6122       return DAG.getUNDEF(VT);
6123
6124     if (NumDefs == 1) {
6125       assert(V.getNode() && "The single defined operand is empty!");
6126       SmallVector<SDValue, 8> Opnds;
6127       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6128         if (i != Idx) {
6129           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6130           continue;
6131         }
6132         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6133         AddToWorkList(NV.getNode());
6134         Opnds.push_back(NV);
6135       }
6136       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6137     }
6138   }
6139
6140   // Simplify the operands using demanded-bits information.
6141   if (!VT.isVector() &&
6142       SimplifyDemandedBits(SDValue(N, 0)))
6143     return SDValue(N, 0);
6144
6145   return SDValue();
6146 }
6147
6148 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6149   SDValue Elt = N->getOperand(i);
6150   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6151     return Elt.getNode();
6152   return Elt.getOperand(Elt.getResNo()).getNode();
6153 }
6154
6155 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6156 /// if load locations are consecutive.
6157 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6158   assert(N->getOpcode() == ISD::BUILD_PAIR);
6159
6160   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6161   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6162   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6163       LD1->getAddressSpace() != LD2->getAddressSpace())
6164     return SDValue();
6165   EVT LD1VT = LD1->getValueType(0);
6166
6167   if (ISD::isNON_EXTLoad(LD2) &&
6168       LD2->hasOneUse() &&
6169       // If both are volatile this would reduce the number of volatile loads.
6170       // If one is volatile it might be ok, but play conservative and bail out.
6171       !LD1->isVolatile() &&
6172       !LD2->isVolatile() &&
6173       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6174     unsigned Align = LD1->getAlignment();
6175     unsigned NewAlign = TLI.getDataLayout()->
6176       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6177
6178     if (NewAlign <= Align &&
6179         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6180       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6181                          LD1->getBasePtr(), LD1->getPointerInfo(),
6182                          false, false, false, Align);
6183   }
6184
6185   return SDValue();
6186 }
6187
6188 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6189   SDValue N0 = N->getOperand(0);
6190   EVT VT = N->getValueType(0);
6191
6192   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6193   // Only do this before legalize, since afterward the target may be depending
6194   // on the bitconvert.
6195   // First check to see if this is all constant.
6196   if (!LegalTypes &&
6197       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6198       VT.isVector()) {
6199     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6200
6201     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6202     assert(!DestEltVT.isVector() &&
6203            "Element type of vector ValueType must not be vector!");
6204     if (isSimple)
6205       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6206   }
6207
6208   // If the input is a constant, let getNode fold it.
6209   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6210     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6211     if (Res.getNode() != N) {
6212       if (!LegalOperations ||
6213           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6214         return Res;
6215
6216       // Folding it resulted in an illegal node, and it's too late to
6217       // do that. Clean up the old node and forego the transformation.
6218       // Ideally this won't happen very often, because instcombine
6219       // and the earlier dagcombine runs (where illegal nodes are
6220       // permitted) should have folded most of them already.
6221       DAG.DeleteNode(Res.getNode());
6222     }
6223   }
6224
6225   // (conv (conv x, t1), t2) -> (conv x, t2)
6226   if (N0.getOpcode() == ISD::BITCAST)
6227     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6228                        N0.getOperand(0));
6229
6230   // fold (conv (load x)) -> (load (conv*)x)
6231   // If the resultant load doesn't need a higher alignment than the original!
6232   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6233       // Do not change the width of a volatile load.
6234       !cast<LoadSDNode>(N0)->isVolatile() &&
6235       // Do not remove the cast if the types differ in endian layout.
6236       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6237       TLI.hasBigEndianPartOrdering(VT) &&
6238       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6239       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6240     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6241     unsigned Align = TLI.getDataLayout()->
6242       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6243     unsigned OrigAlign = LN0->getAlignment();
6244
6245     if (Align <= OrigAlign) {
6246       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6247                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6248                                  LN0->isVolatile(), LN0->isNonTemporal(),
6249                                  LN0->isInvariant(), OrigAlign,
6250                                  LN0->getTBAAInfo());
6251       AddToWorkList(N);
6252       CombineTo(N0.getNode(),
6253                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6254                             N0.getValueType(), Load),
6255                 Load.getValue(1));
6256       return Load;
6257     }
6258   }
6259
6260   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6261   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6262   // This often reduces constant pool loads.
6263   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6264        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6265       N0.getNode()->hasOneUse() && VT.isInteger() &&
6266       !VT.isVector() && !N0.getValueType().isVector()) {
6267     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6268                                   N0.getOperand(0));
6269     AddToWorkList(NewConv.getNode());
6270
6271     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6272     if (N0.getOpcode() == ISD::FNEG)
6273       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6274                          NewConv, DAG.getConstant(SignBit, VT));
6275     assert(N0.getOpcode() == ISD::FABS);
6276     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6277                        NewConv, DAG.getConstant(~SignBit, VT));
6278   }
6279
6280   // fold (bitconvert (fcopysign cst, x)) ->
6281   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6282   // Note that we don't handle (copysign x, cst) because this can always be
6283   // folded to an fneg or fabs.
6284   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6285       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6286       VT.isInteger() && !VT.isVector()) {
6287     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6288     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6289     if (isTypeLegal(IntXVT)) {
6290       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6291                               IntXVT, N0.getOperand(1));
6292       AddToWorkList(X.getNode());
6293
6294       // If X has a different width than the result/lhs, sext it or truncate it.
6295       unsigned VTWidth = VT.getSizeInBits();
6296       if (OrigXWidth < VTWidth) {
6297         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6298         AddToWorkList(X.getNode());
6299       } else if (OrigXWidth > VTWidth) {
6300         // To get the sign bit in the right place, we have to shift it right
6301         // before truncating.
6302         X = DAG.getNode(ISD::SRL, SDLoc(X),
6303                         X.getValueType(), X,
6304                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6305         AddToWorkList(X.getNode());
6306         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6307         AddToWorkList(X.getNode());
6308       }
6309
6310       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6311       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6312                       X, DAG.getConstant(SignBit, VT));
6313       AddToWorkList(X.getNode());
6314
6315       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6316                                 VT, N0.getOperand(0));
6317       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6318                         Cst, DAG.getConstant(~SignBit, VT));
6319       AddToWorkList(Cst.getNode());
6320
6321       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6322     }
6323   }
6324
6325   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6326   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6327     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6328     if (CombineLD.getNode())
6329       return CombineLD;
6330   }
6331
6332   return SDValue();
6333 }
6334
6335 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6336   EVT VT = N->getValueType(0);
6337   return CombineConsecutiveLoads(N, VT);
6338 }
6339
6340 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6341 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6342 /// destination element value type.
6343 SDValue DAGCombiner::
6344 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6345   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6346
6347   // If this is already the right type, we're done.
6348   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6349
6350   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6351   unsigned DstBitSize = DstEltVT.getSizeInBits();
6352
6353   // If this is a conversion of N elements of one type to N elements of another
6354   // type, convert each element.  This handles FP<->INT cases.
6355   if (SrcBitSize == DstBitSize) {
6356     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6357                               BV->getValueType(0).getVectorNumElements());
6358
6359     // Due to the FP element handling below calling this routine recursively,
6360     // we can end up with a scalar-to-vector node here.
6361     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6362       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6363                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6364                                      DstEltVT, BV->getOperand(0)));
6365
6366     SmallVector<SDValue, 8> Ops;
6367     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6368       SDValue Op = BV->getOperand(i);
6369       // If the vector element type is not legal, the BUILD_VECTOR operands
6370       // are promoted and implicitly truncated.  Make that explicit here.
6371       if (Op.getValueType() != SrcEltVT)
6372         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6373       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6374                                 DstEltVT, Op));
6375       AddToWorkList(Ops.back().getNode());
6376     }
6377     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6378   }
6379
6380   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6381   // handle annoying details of growing/shrinking FP values, we convert them to
6382   // int first.
6383   if (SrcEltVT.isFloatingPoint()) {
6384     // Convert the input float vector to a int vector where the elements are the
6385     // same sizes.
6386     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6387     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6388     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6389     SrcEltVT = IntVT;
6390   }
6391
6392   // Now we know the input is an integer vector.  If the output is a FP type,
6393   // convert to integer first, then to FP of the right size.
6394   if (DstEltVT.isFloatingPoint()) {
6395     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6396     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6397     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6398
6399     // Next, convert to FP elements of the same size.
6400     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6401   }
6402
6403   // Okay, we know the src/dst types are both integers of differing types.
6404   // Handling growing first.
6405   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6406   if (SrcBitSize < DstBitSize) {
6407     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6408
6409     SmallVector<SDValue, 8> Ops;
6410     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6411          i += NumInputsPerOutput) {
6412       bool isLE = TLI.isLittleEndian();
6413       APInt NewBits = APInt(DstBitSize, 0);
6414       bool EltIsUndef = true;
6415       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6416         // Shift the previously computed bits over.
6417         NewBits <<= SrcBitSize;
6418         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6419         if (Op.getOpcode() == ISD::UNDEF) continue;
6420         EltIsUndef = false;
6421
6422         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6423                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6424       }
6425
6426       if (EltIsUndef)
6427         Ops.push_back(DAG.getUNDEF(DstEltVT));
6428       else
6429         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6430     }
6431
6432     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6433     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6434   }
6435
6436   // Finally, this must be the case where we are shrinking elements: each input
6437   // turns into multiple outputs.
6438   bool isS2V = ISD::isScalarToVector(BV);
6439   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6440   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6441                             NumOutputsPerInput*BV->getNumOperands());
6442   SmallVector<SDValue, 8> Ops;
6443
6444   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6445     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6446       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6447         Ops.push_back(DAG.getUNDEF(DstEltVT));
6448       continue;
6449     }
6450
6451     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6452                   getAPIntValue().zextOrTrunc(SrcBitSize);
6453
6454     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6455       APInt ThisVal = OpVal.trunc(DstBitSize);
6456       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6457       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6458         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6459         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6460                            Ops[0]);
6461       OpVal = OpVal.lshr(DstBitSize);
6462     }
6463
6464     // For big endian targets, swap the order of the pieces of each element.
6465     if (TLI.isBigEndian())
6466       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6467   }
6468
6469   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6470 }
6471
6472 SDValue DAGCombiner::visitFADD(SDNode *N) {
6473   SDValue N0 = N->getOperand(0);
6474   SDValue N1 = N->getOperand(1);
6475   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6476   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6477   EVT VT = N->getValueType(0);
6478
6479   // fold vector ops
6480   if (VT.isVector()) {
6481     SDValue FoldedVOp = SimplifyVBinOp(N);
6482     if (FoldedVOp.getNode()) return FoldedVOp;
6483   }
6484
6485   // fold (fadd c1, c2) -> c1 + c2
6486   if (N0CFP && N1CFP)
6487     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6488   // canonicalize constant to RHS
6489   if (N0CFP && !N1CFP)
6490     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6491   // fold (fadd A, 0) -> A
6492   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6493       N1CFP->getValueAPF().isZero())
6494     return N0;
6495   // fold (fadd A, (fneg B)) -> (fsub A, B)
6496   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6497     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6498     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6499                        GetNegatedExpression(N1, DAG, LegalOperations));
6500   // fold (fadd (fneg A), B) -> (fsub B, A)
6501   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6502     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6503     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6504                        GetNegatedExpression(N0, DAG, LegalOperations));
6505
6506   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6507   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6508       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6509       isa<ConstantFPSDNode>(N0.getOperand(1)))
6510     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6511                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6512                                    N0.getOperand(1), N1));
6513
6514   // No FP constant should be created after legalization as Instruction
6515   // Selection pass has hard time in dealing with FP constant.
6516   //
6517   // We don't need test this condition for transformation like following, as
6518   // the DAG being transformed implies it is legal to take FP constant as
6519   // operand.
6520   //
6521   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6522   //
6523   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6524
6525   // If allow, fold (fadd (fneg x), x) -> 0.0
6526   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6527       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6528     return DAG.getConstantFP(0.0, VT);
6529
6530     // If allow, fold (fadd x, (fneg x)) -> 0.0
6531   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6532       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6533     return DAG.getConstantFP(0.0, VT);
6534
6535   // In unsafe math mode, we can fold chains of FADD's of the same value
6536   // into multiplications.  This transform is not safe in general because
6537   // we are reducing the number of rounding steps.
6538   if (DAG.getTarget().Options.UnsafeFPMath &&
6539       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6540       !N0CFP && !N1CFP) {
6541     if (N0.getOpcode() == ISD::FMUL) {
6542       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6543       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6544
6545       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6546       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6547         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6548                                      SDValue(CFP00, 0),
6549                                      DAG.getConstantFP(1.0, VT));
6550         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6551                            N1, NewCFP);
6552       }
6553
6554       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6555       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6556         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6557                                      SDValue(CFP01, 0),
6558                                      DAG.getConstantFP(1.0, VT));
6559         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6560                            N1, NewCFP);
6561       }
6562
6563       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6564       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6565           N1.getOperand(0) == N1.getOperand(1) &&
6566           N0.getOperand(1) == N1.getOperand(0)) {
6567         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6568                                      SDValue(CFP00, 0),
6569                                      DAG.getConstantFP(2.0, VT));
6570         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6571                            N0.getOperand(1), NewCFP);
6572       }
6573
6574       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6575       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6576           N1.getOperand(0) == N1.getOperand(1) &&
6577           N0.getOperand(0) == N1.getOperand(0)) {
6578         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6579                                      SDValue(CFP01, 0),
6580                                      DAG.getConstantFP(2.0, VT));
6581         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6582                            N0.getOperand(0), NewCFP);
6583       }
6584     }
6585
6586     if (N1.getOpcode() == ISD::FMUL) {
6587       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6588       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6589
6590       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6591       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6592         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6593                                      SDValue(CFP10, 0),
6594                                      DAG.getConstantFP(1.0, VT));
6595         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6596                            N0, NewCFP);
6597       }
6598
6599       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6600       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6601         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6602                                      SDValue(CFP11, 0),
6603                                      DAG.getConstantFP(1.0, VT));
6604         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6605                            N0, NewCFP);
6606       }
6607
6608
6609       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6610       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6611           N0.getOperand(0) == N0.getOperand(1) &&
6612           N1.getOperand(1) == N0.getOperand(0)) {
6613         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6614                                      SDValue(CFP10, 0),
6615                                      DAG.getConstantFP(2.0, VT));
6616         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6617                            N1.getOperand(1), NewCFP);
6618       }
6619
6620       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6621       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6622           N0.getOperand(0) == N0.getOperand(1) &&
6623           N1.getOperand(0) == N0.getOperand(0)) {
6624         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6625                                      SDValue(CFP11, 0),
6626                                      DAG.getConstantFP(2.0, VT));
6627         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628                            N1.getOperand(0), NewCFP);
6629       }
6630     }
6631
6632     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6633       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6634       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6635       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6636           (N0.getOperand(0) == N1))
6637         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6638                            N1, DAG.getConstantFP(3.0, VT));
6639     }
6640
6641     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6642       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6643       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6644       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6645           N1.getOperand(0) == N0)
6646         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6647                            N0, DAG.getConstantFP(3.0, VT));
6648     }
6649
6650     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6651     if (AllowNewFpConst &&
6652         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6653         N0.getOperand(0) == N0.getOperand(1) &&
6654         N1.getOperand(0) == N1.getOperand(1) &&
6655         N0.getOperand(0) == N1.getOperand(0))
6656       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6657                          N0.getOperand(0),
6658                          DAG.getConstantFP(4.0, VT));
6659   }
6660
6661   // FADD -> FMA combines:
6662   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6663        DAG.getTarget().Options.UnsafeFPMath) &&
6664       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6665       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6666
6667     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6668     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6669       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6670                          N0.getOperand(0), N0.getOperand(1), N1);
6671
6672     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6673     // Note: Commutes FADD operands.
6674     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6675       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6676                          N1.getOperand(0), N1.getOperand(1), N0);
6677   }
6678
6679   return SDValue();
6680 }
6681
6682 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6683   SDValue N0 = N->getOperand(0);
6684   SDValue N1 = N->getOperand(1);
6685   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6686   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6687   EVT VT = N->getValueType(0);
6688   SDLoc dl(N);
6689
6690   // fold vector ops
6691   if (VT.isVector()) {
6692     SDValue FoldedVOp = SimplifyVBinOp(N);
6693     if (FoldedVOp.getNode()) return FoldedVOp;
6694   }
6695
6696   // fold (fsub c1, c2) -> c1-c2
6697   if (N0CFP && N1CFP)
6698     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6699   // fold (fsub A, 0) -> A
6700   if (DAG.getTarget().Options.UnsafeFPMath &&
6701       N1CFP && N1CFP->getValueAPF().isZero())
6702     return N0;
6703   // fold (fsub 0, B) -> -B
6704   if (DAG.getTarget().Options.UnsafeFPMath &&
6705       N0CFP && N0CFP->getValueAPF().isZero()) {
6706     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6707       return GetNegatedExpression(N1, DAG, LegalOperations);
6708     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6709       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6710   }
6711   // fold (fsub A, (fneg B)) -> (fadd A, B)
6712   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6713     return DAG.getNode(ISD::FADD, dl, VT, N0,
6714                        GetNegatedExpression(N1, DAG, LegalOperations));
6715
6716   // If 'unsafe math' is enabled, fold
6717   //    (fsub x, x) -> 0.0 &
6718   //    (fsub x, (fadd x, y)) -> (fneg y) &
6719   //    (fsub x, (fadd y, x)) -> (fneg y)
6720   if (DAG.getTarget().Options.UnsafeFPMath) {
6721     if (N0 == N1)
6722       return DAG.getConstantFP(0.0f, VT);
6723
6724     if (N1.getOpcode() == ISD::FADD) {
6725       SDValue N10 = N1->getOperand(0);
6726       SDValue N11 = N1->getOperand(1);
6727
6728       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6729                                           &DAG.getTarget().Options))
6730         return GetNegatedExpression(N11, DAG, LegalOperations);
6731
6732       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6733                                           &DAG.getTarget().Options))
6734         return GetNegatedExpression(N10, DAG, LegalOperations);
6735     }
6736   }
6737
6738   // FSUB -> FMA combines:
6739   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6740        DAG.getTarget().Options.UnsafeFPMath) &&
6741       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6742       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6743
6744     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6745     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6746       return DAG.getNode(ISD::FMA, dl, VT,
6747                          N0.getOperand(0), N0.getOperand(1),
6748                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6749
6750     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6751     // Note: Commutes FSUB operands.
6752     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6753       return DAG.getNode(ISD::FMA, dl, VT,
6754                          DAG.getNode(ISD::FNEG, dl, VT,
6755                          N1.getOperand(0)),
6756                          N1.getOperand(1), N0);
6757
6758     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6759     if (N0.getOpcode() == ISD::FNEG &&
6760         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6761         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6762       SDValue N00 = N0.getOperand(0).getOperand(0);
6763       SDValue N01 = N0.getOperand(0).getOperand(1);
6764       return DAG.getNode(ISD::FMA, dl, VT,
6765                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6766                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6767     }
6768   }
6769
6770   return SDValue();
6771 }
6772
6773 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6774   SDValue N0 = N->getOperand(0);
6775   SDValue N1 = N->getOperand(1);
6776   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6777   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6778   EVT VT = N->getValueType(0);
6779   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6780
6781   // fold vector ops
6782   if (VT.isVector()) {
6783     SDValue FoldedVOp = SimplifyVBinOp(N);
6784     if (FoldedVOp.getNode()) return FoldedVOp;
6785   }
6786
6787   // fold (fmul c1, c2) -> c1*c2
6788   if (N0CFP && N1CFP)
6789     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6790   // canonicalize constant to RHS
6791   if (N0CFP && !N1CFP)
6792     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6793   // fold (fmul A, 0) -> 0
6794   if (DAG.getTarget().Options.UnsafeFPMath &&
6795       N1CFP && N1CFP->getValueAPF().isZero())
6796     return N1;
6797   // fold (fmul A, 0) -> 0, vector edition.
6798   if (DAG.getTarget().Options.UnsafeFPMath &&
6799       ISD::isBuildVectorAllZeros(N1.getNode()))
6800     return N1;
6801   // fold (fmul A, 1.0) -> A
6802   if (N1CFP && N1CFP->isExactlyValue(1.0))
6803     return N0;
6804   // fold (fmul X, 2.0) -> (fadd X, X)
6805   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6806     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6807   // fold (fmul X, -1.0) -> (fneg X)
6808   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6809     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6810       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6811
6812   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6813   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6814                                        &DAG.getTarget().Options)) {
6815     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6816                                          &DAG.getTarget().Options)) {
6817       // Both can be negated for free, check to see if at least one is cheaper
6818       // negated.
6819       if (LHSNeg == 2 || RHSNeg == 2)
6820         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6821                            GetNegatedExpression(N0, DAG, LegalOperations),
6822                            GetNegatedExpression(N1, DAG, LegalOperations));
6823     }
6824   }
6825
6826   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6827   if (DAG.getTarget().Options.UnsafeFPMath &&
6828       N1CFP && N0.getOpcode() == ISD::FMUL &&
6829       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6830     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6831                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6832                                    N0.getOperand(1), N1));
6833
6834   return SDValue();
6835 }
6836
6837 SDValue DAGCombiner::visitFMA(SDNode *N) {
6838   SDValue N0 = N->getOperand(0);
6839   SDValue N1 = N->getOperand(1);
6840   SDValue N2 = N->getOperand(2);
6841   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6842   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6843   EVT VT = N->getValueType(0);
6844   SDLoc dl(N);
6845
6846   if (DAG.getTarget().Options.UnsafeFPMath) {
6847     if (N0CFP && N0CFP->isZero())
6848       return N2;
6849     if (N1CFP && N1CFP->isZero())
6850       return N2;
6851   }
6852   if (N0CFP && N0CFP->isExactlyValue(1.0))
6853     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6854   if (N1CFP && N1CFP->isExactlyValue(1.0))
6855     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6856
6857   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6858   if (N0CFP && !N1CFP)
6859     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6860
6861   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6862   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6863       N2.getOpcode() == ISD::FMUL &&
6864       N0 == N2.getOperand(0) &&
6865       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6866     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6867                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6868   }
6869
6870
6871   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6872   if (DAG.getTarget().Options.UnsafeFPMath &&
6873       N0.getOpcode() == ISD::FMUL && N1CFP &&
6874       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6875     return DAG.getNode(ISD::FMA, dl, VT,
6876                        N0.getOperand(0),
6877                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6878                        N2);
6879   }
6880
6881   // (fma x, 1, y) -> (fadd x, y)
6882   // (fma x, -1, y) -> (fadd (fneg x), y)
6883   if (N1CFP) {
6884     if (N1CFP->isExactlyValue(1.0))
6885       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6886
6887     if (N1CFP->isExactlyValue(-1.0) &&
6888         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6889       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6890       AddToWorkList(RHSNeg.getNode());
6891       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6892     }
6893   }
6894
6895   // (fma x, c, x) -> (fmul x, (c+1))
6896   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6897     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6898                        DAG.getNode(ISD::FADD, dl, VT,
6899                                    N1, DAG.getConstantFP(1.0, VT)));
6900
6901   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6902   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6903       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6904     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6905                        DAG.getNode(ISD::FADD, dl, VT,
6906                                    N1, DAG.getConstantFP(-1.0, VT)));
6907
6908
6909   return SDValue();
6910 }
6911
6912 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6913   SDValue N0 = N->getOperand(0);
6914   SDValue N1 = N->getOperand(1);
6915   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6916   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6917   EVT VT = N->getValueType(0);
6918   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6919
6920   // fold vector ops
6921   if (VT.isVector()) {
6922     SDValue FoldedVOp = SimplifyVBinOp(N);
6923     if (FoldedVOp.getNode()) return FoldedVOp;
6924   }
6925
6926   // fold (fdiv c1, c2) -> c1/c2
6927   if (N0CFP && N1CFP)
6928     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6929
6930   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6931   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6932     // Compute the reciprocal 1.0 / c2.
6933     APFloat N1APF = N1CFP->getValueAPF();
6934     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6935     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6936     // Only do the transform if the reciprocal is a legal fp immediate that
6937     // isn't too nasty (eg NaN, denormal, ...).
6938     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6939         (!LegalOperations ||
6940          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6941          // backend)... we should handle this gracefully after Legalize.
6942          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6943          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6944          TLI.isFPImmLegal(Recip, VT)))
6945       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6946                          DAG.getConstantFP(Recip, VT));
6947   }
6948
6949   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6950   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6951                                        &DAG.getTarget().Options)) {
6952     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6953                                          &DAG.getTarget().Options)) {
6954       // Both can be negated for free, check to see if at least one is cheaper
6955       // negated.
6956       if (LHSNeg == 2 || RHSNeg == 2)
6957         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6958                            GetNegatedExpression(N0, DAG, LegalOperations),
6959                            GetNegatedExpression(N1, DAG, LegalOperations));
6960     }
6961   }
6962
6963   return SDValue();
6964 }
6965
6966 SDValue DAGCombiner::visitFREM(SDNode *N) {
6967   SDValue N0 = N->getOperand(0);
6968   SDValue N1 = N->getOperand(1);
6969   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6970   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6971   EVT VT = N->getValueType(0);
6972
6973   // fold (frem c1, c2) -> fmod(c1,c2)
6974   if (N0CFP && N1CFP)
6975     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6976
6977   return SDValue();
6978 }
6979
6980 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6981   SDValue N0 = N->getOperand(0);
6982   SDValue N1 = N->getOperand(1);
6983   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6984   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6985   EVT VT = N->getValueType(0);
6986
6987   if (N0CFP && N1CFP)  // Constant fold
6988     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6989
6990   if (N1CFP) {
6991     const APFloat& V = N1CFP->getValueAPF();
6992     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6993     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6994     if (!V.isNegative()) {
6995       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6996         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6997     } else {
6998       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6999         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7000                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7001     }
7002   }
7003
7004   // copysign(fabs(x), y) -> copysign(x, y)
7005   // copysign(fneg(x), y) -> copysign(x, y)
7006   // copysign(copysign(x,z), y) -> copysign(x, y)
7007   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7008       N0.getOpcode() == ISD::FCOPYSIGN)
7009     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7010                        N0.getOperand(0), N1);
7011
7012   // copysign(x, abs(y)) -> abs(x)
7013   if (N1.getOpcode() == ISD::FABS)
7014     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7015
7016   // copysign(x, copysign(y,z)) -> copysign(x, z)
7017   if (N1.getOpcode() == ISD::FCOPYSIGN)
7018     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7019                        N0, N1.getOperand(1));
7020
7021   // copysign(x, fp_extend(y)) -> copysign(x, y)
7022   // copysign(x, fp_round(y)) -> copysign(x, y)
7023   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7024     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7025                        N0, N1.getOperand(0));
7026
7027   return SDValue();
7028 }
7029
7030 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7031   SDValue N0 = N->getOperand(0);
7032   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7033   EVT VT = N->getValueType(0);
7034   EVT OpVT = N0.getValueType();
7035
7036   // fold (sint_to_fp c1) -> c1fp
7037   if (N0C &&
7038       // ...but only if the target supports immediate floating-point values
7039       (!LegalOperations ||
7040        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7041     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7042
7043   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7044   // but UINT_TO_FP is legal on this target, try to convert.
7045   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7046       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7047     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7048     if (DAG.SignBitIsZero(N0))
7049       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7050   }
7051
7052   // The next optimizations are desirable only if SELECT_CC can be lowered.
7053   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7054     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7055     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7056         !VT.isVector() &&
7057         (!LegalOperations ||
7058          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7059       SDValue Ops[] =
7060         { N0.getOperand(0), N0.getOperand(1),
7061           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7062           N0.getOperand(2) };
7063       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7064     }
7065
7066     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7067     //      (select_cc x, y, 1.0, 0.0,, cc)
7068     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7069         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7070         (!LegalOperations ||
7071          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7072       SDValue Ops[] =
7073         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7074           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7075           N0.getOperand(0).getOperand(2) };
7076       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7077     }
7078   }
7079
7080   return SDValue();
7081 }
7082
7083 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7084   SDValue N0 = N->getOperand(0);
7085   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7086   EVT VT = N->getValueType(0);
7087   EVT OpVT = N0.getValueType();
7088
7089   // fold (uint_to_fp c1) -> c1fp
7090   if (N0C &&
7091       // ...but only if the target supports immediate floating-point values
7092       (!LegalOperations ||
7093        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7094     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7095
7096   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7097   // but SINT_TO_FP is legal on this target, try to convert.
7098   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7099       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7100     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7101     if (DAG.SignBitIsZero(N0))
7102       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7103   }
7104
7105   // The next optimizations are desirable only if SELECT_CC can be lowered.
7106   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7107     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7108
7109     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7110         (!LegalOperations ||
7111          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7112       SDValue Ops[] =
7113         { N0.getOperand(0), N0.getOperand(1),
7114           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7115           N0.getOperand(2) };
7116       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7117     }
7118   }
7119
7120   return SDValue();
7121 }
7122
7123 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7124   SDValue N0 = N->getOperand(0);
7125   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7126   EVT VT = N->getValueType(0);
7127
7128   // fold (fp_to_sint c1fp) -> c1
7129   if (N0CFP)
7130     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7131
7132   return SDValue();
7133 }
7134
7135 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7136   SDValue N0 = N->getOperand(0);
7137   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7138   EVT VT = N->getValueType(0);
7139
7140   // fold (fp_to_uint c1fp) -> c1
7141   if (N0CFP)
7142     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7143
7144   return SDValue();
7145 }
7146
7147 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7148   SDValue N0 = N->getOperand(0);
7149   SDValue N1 = N->getOperand(1);
7150   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7151   EVT VT = N->getValueType(0);
7152
7153   // fold (fp_round c1fp) -> c1fp
7154   if (N0CFP)
7155     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7156
7157   // fold (fp_round (fp_extend x)) -> x
7158   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7159     return N0.getOperand(0);
7160
7161   // fold (fp_round (fp_round x)) -> (fp_round x)
7162   if (N0.getOpcode() == ISD::FP_ROUND) {
7163     // This is a value preserving truncation if both round's are.
7164     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7165                    N0.getNode()->getConstantOperandVal(1) == 1;
7166     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7167                        DAG.getIntPtrConstant(IsTrunc));
7168   }
7169
7170   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7171   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7172     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7173                               N0.getOperand(0), N1);
7174     AddToWorkList(Tmp.getNode());
7175     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7176                        Tmp, N0.getOperand(1));
7177   }
7178
7179   return SDValue();
7180 }
7181
7182 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7183   SDValue N0 = N->getOperand(0);
7184   EVT VT = N->getValueType(0);
7185   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7186   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7187
7188   // fold (fp_round_inreg c1fp) -> c1fp
7189   if (N0CFP && isTypeLegal(EVT)) {
7190     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7191     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7192   }
7193
7194   return SDValue();
7195 }
7196
7197 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7198   SDValue N0 = N->getOperand(0);
7199   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7200   EVT VT = N->getValueType(0);
7201
7202   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7203   if (N->hasOneUse() &&
7204       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7205     return SDValue();
7206
7207   // fold (fp_extend c1fp) -> c1fp
7208   if (N0CFP)
7209     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7210
7211   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7212   // value of X.
7213   if (N0.getOpcode() == ISD::FP_ROUND
7214       && N0.getNode()->getConstantOperandVal(1) == 1) {
7215     SDValue In = N0.getOperand(0);
7216     if (In.getValueType() == VT) return In;
7217     if (VT.bitsLT(In.getValueType()))
7218       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7219                          In, N0.getOperand(1));
7220     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7221   }
7222
7223   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7224   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7225        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7226     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7227     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7228                                      LN0->getChain(),
7229                                      LN0->getBasePtr(), N0.getValueType(),
7230                                      LN0->getMemOperand());
7231     CombineTo(N, ExtLoad);
7232     CombineTo(N0.getNode(),
7233               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7234                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7235               ExtLoad.getValue(1));
7236     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7237   }
7238
7239   return SDValue();
7240 }
7241
7242 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7243   SDValue N0 = N->getOperand(0);
7244   EVT VT = N->getValueType(0);
7245
7246   if (VT.isVector()) {
7247     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7248     if (FoldedVOp.getNode()) return FoldedVOp;
7249   }
7250
7251   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7252                          &DAG.getTarget().Options))
7253     return GetNegatedExpression(N0, DAG, LegalOperations);
7254
7255   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7256   // constant pool values.
7257   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7258       !VT.isVector() &&
7259       N0.getNode()->hasOneUse() &&
7260       N0.getOperand(0).getValueType().isInteger()) {
7261     SDValue Int = N0.getOperand(0);
7262     EVT IntVT = Int.getValueType();
7263     if (IntVT.isInteger() && !IntVT.isVector()) {
7264       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7265               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7266       AddToWorkList(Int.getNode());
7267       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7268                          VT, Int);
7269     }
7270   }
7271
7272   // (fneg (fmul c, x)) -> (fmul -c, x)
7273   if (N0.getOpcode() == ISD::FMUL) {
7274     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7275     if (CFP1) {
7276       APFloat CVal = CFP1->getValueAPF();
7277       CVal.changeSign();
7278       if (Level >= AfterLegalizeDAG &&
7279           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7280            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7281         return DAG.getNode(
7282             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7283             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7284     }
7285   }
7286
7287   return SDValue();
7288 }
7289
7290 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7291   SDValue N0 = N->getOperand(0);
7292   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7293   EVT VT = N->getValueType(0);
7294
7295   // fold (fceil c1) -> fceil(c1)
7296   if (N0CFP)
7297     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7298
7299   return SDValue();
7300 }
7301
7302 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7303   SDValue N0 = N->getOperand(0);
7304   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7305   EVT VT = N->getValueType(0);
7306
7307   // fold (ftrunc c1) -> ftrunc(c1)
7308   if (N0CFP)
7309     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7310
7311   return SDValue();
7312 }
7313
7314 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7315   SDValue N0 = N->getOperand(0);
7316   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7317   EVT VT = N->getValueType(0);
7318
7319   // fold (ffloor c1) -> ffloor(c1)
7320   if (N0CFP)
7321     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7322
7323   return SDValue();
7324 }
7325
7326 SDValue DAGCombiner::visitFABS(SDNode *N) {
7327   SDValue N0 = N->getOperand(0);
7328   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7329   EVT VT = N->getValueType(0);
7330
7331   if (VT.isVector()) {
7332     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7333     if (FoldedVOp.getNode()) return FoldedVOp;
7334   }
7335
7336   // fold (fabs c1) -> fabs(c1)
7337   if (N0CFP)
7338     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7339   // fold (fabs (fabs x)) -> (fabs x)
7340   if (N0.getOpcode() == ISD::FABS)
7341     return N->getOperand(0);
7342   // fold (fabs (fneg x)) -> (fabs x)
7343   // fold (fabs (fcopysign x, y)) -> (fabs x)
7344   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7345     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7346
7347   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7348   // constant pool values.
7349   if (!TLI.isFAbsFree(VT) &&
7350       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7351       N0.getOperand(0).getValueType().isInteger() &&
7352       !N0.getOperand(0).getValueType().isVector()) {
7353     SDValue Int = N0.getOperand(0);
7354     EVT IntVT = Int.getValueType();
7355     if (IntVT.isInteger() && !IntVT.isVector()) {
7356       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7357              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7358       AddToWorkList(Int.getNode());
7359       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7360                          N->getValueType(0), Int);
7361     }
7362   }
7363
7364   return SDValue();
7365 }
7366
7367 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7368   SDValue Chain = N->getOperand(0);
7369   SDValue N1 = N->getOperand(1);
7370   SDValue N2 = N->getOperand(2);
7371
7372   // If N is a constant we could fold this into a fallthrough or unconditional
7373   // branch. However that doesn't happen very often in normal code, because
7374   // Instcombine/SimplifyCFG should have handled the available opportunities.
7375   // If we did this folding here, it would be necessary to update the
7376   // MachineBasicBlock CFG, which is awkward.
7377
7378   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7379   // on the target.
7380   if (N1.getOpcode() == ISD::SETCC &&
7381       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7382                                    N1.getOperand(0).getValueType())) {
7383     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7384                        Chain, N1.getOperand(2),
7385                        N1.getOperand(0), N1.getOperand(1), N2);
7386   }
7387
7388   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7389       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7390        (N1.getOperand(0).hasOneUse() &&
7391         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7392     SDNode *Trunc = nullptr;
7393     if (N1.getOpcode() == ISD::TRUNCATE) {
7394       // Look pass the truncate.
7395       Trunc = N1.getNode();
7396       N1 = N1.getOperand(0);
7397     }
7398
7399     // Match this pattern so that we can generate simpler code:
7400     //
7401     //   %a = ...
7402     //   %b = and i32 %a, 2
7403     //   %c = srl i32 %b, 1
7404     //   brcond i32 %c ...
7405     //
7406     // into
7407     //
7408     //   %a = ...
7409     //   %b = and i32 %a, 2
7410     //   %c = setcc eq %b, 0
7411     //   brcond %c ...
7412     //
7413     // This applies only when the AND constant value has one bit set and the
7414     // SRL constant is equal to the log2 of the AND constant. The back-end is
7415     // smart enough to convert the result into a TEST/JMP sequence.
7416     SDValue Op0 = N1.getOperand(0);
7417     SDValue Op1 = N1.getOperand(1);
7418
7419     if (Op0.getOpcode() == ISD::AND &&
7420         Op1.getOpcode() == ISD::Constant) {
7421       SDValue AndOp1 = Op0.getOperand(1);
7422
7423       if (AndOp1.getOpcode() == ISD::Constant) {
7424         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7425
7426         if (AndConst.isPowerOf2() &&
7427             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7428           SDValue SetCC =
7429             DAG.getSetCC(SDLoc(N),
7430                          getSetCCResultType(Op0.getValueType()),
7431                          Op0, DAG.getConstant(0, Op0.getValueType()),
7432                          ISD::SETNE);
7433
7434           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7435                                           MVT::Other, Chain, SetCC, N2);
7436           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7437           // will convert it back to (X & C1) >> C2.
7438           CombineTo(N, NewBRCond, false);
7439           // Truncate is dead.
7440           if (Trunc) {
7441             removeFromWorkList(Trunc);
7442             DAG.DeleteNode(Trunc);
7443           }
7444           // Replace the uses of SRL with SETCC
7445           WorkListRemover DeadNodes(*this);
7446           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7447           removeFromWorkList(N1.getNode());
7448           DAG.DeleteNode(N1.getNode());
7449           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7450         }
7451       }
7452     }
7453
7454     if (Trunc)
7455       // Restore N1 if the above transformation doesn't match.
7456       N1 = N->getOperand(1);
7457   }
7458
7459   // Transform br(xor(x, y)) -> br(x != y)
7460   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7461   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7462     SDNode *TheXor = N1.getNode();
7463     SDValue Op0 = TheXor->getOperand(0);
7464     SDValue Op1 = TheXor->getOperand(1);
7465     if (Op0.getOpcode() == Op1.getOpcode()) {
7466       // Avoid missing important xor optimizations.
7467       SDValue Tmp = visitXOR(TheXor);
7468       if (Tmp.getNode()) {
7469         if (Tmp.getNode() != TheXor) {
7470           DEBUG(dbgs() << "\nReplacing.8 ";
7471                 TheXor->dump(&DAG);
7472                 dbgs() << "\nWith: ";
7473                 Tmp.getNode()->dump(&DAG);
7474                 dbgs() << '\n');
7475           WorkListRemover DeadNodes(*this);
7476           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7477           removeFromWorkList(TheXor);
7478           DAG.DeleteNode(TheXor);
7479           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7480                              MVT::Other, Chain, Tmp, N2);
7481         }
7482
7483         // visitXOR has changed XOR's operands or replaced the XOR completely,
7484         // bail out.
7485         return SDValue(N, 0);
7486       }
7487     }
7488
7489     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7490       bool Equal = false;
7491       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7492         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7493             Op0.getOpcode() == ISD::XOR) {
7494           TheXor = Op0.getNode();
7495           Equal = true;
7496         }
7497
7498       EVT SetCCVT = N1.getValueType();
7499       if (LegalTypes)
7500         SetCCVT = getSetCCResultType(SetCCVT);
7501       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7502                                    SetCCVT,
7503                                    Op0, Op1,
7504                                    Equal ? ISD::SETEQ : ISD::SETNE);
7505       // Replace the uses of XOR with SETCC
7506       WorkListRemover DeadNodes(*this);
7507       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7508       removeFromWorkList(N1.getNode());
7509       DAG.DeleteNode(N1.getNode());
7510       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7511                          MVT::Other, Chain, SetCC, N2);
7512     }
7513   }
7514
7515   return SDValue();
7516 }
7517
7518 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7519 //
7520 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7521   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7522   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7523
7524   // If N is a constant we could fold this into a fallthrough or unconditional
7525   // branch. However that doesn't happen very often in normal code, because
7526   // Instcombine/SimplifyCFG should have handled the available opportunities.
7527   // If we did this folding here, it would be necessary to update the
7528   // MachineBasicBlock CFG, which is awkward.
7529
7530   // Use SimplifySetCC to simplify SETCC's.
7531   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7532                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7533                                false);
7534   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7535
7536   // fold to a simpler setcc
7537   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7538     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7539                        N->getOperand(0), Simp.getOperand(2),
7540                        Simp.getOperand(0), Simp.getOperand(1),
7541                        N->getOperand(4));
7542
7543   return SDValue();
7544 }
7545
7546 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7547 /// uses N as its base pointer and that N may be folded in the load / store
7548 /// addressing mode.
7549 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7550                                     SelectionDAG &DAG,
7551                                     const TargetLowering &TLI) {
7552   EVT VT;
7553   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7554     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7555       return false;
7556     VT = Use->getValueType(0);
7557   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7558     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7559       return false;
7560     VT = ST->getValue().getValueType();
7561   } else
7562     return false;
7563
7564   TargetLowering::AddrMode AM;
7565   if (N->getOpcode() == ISD::ADD) {
7566     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7567     if (Offset)
7568       // [reg +/- imm]
7569       AM.BaseOffs = Offset->getSExtValue();
7570     else
7571       // [reg +/- reg]
7572       AM.Scale = 1;
7573   } else if (N->getOpcode() == ISD::SUB) {
7574     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7575     if (Offset)
7576       // [reg +/- imm]
7577       AM.BaseOffs = -Offset->getSExtValue();
7578     else
7579       // [reg +/- reg]
7580       AM.Scale = 1;
7581   } else
7582     return false;
7583
7584   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7585 }
7586
7587 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7588 /// pre-indexed load / store when the base pointer is an add or subtract
7589 /// and it has other uses besides the load / store. After the
7590 /// transformation, the new indexed load / store has effectively folded
7591 /// the add / subtract in and all of its other uses are redirected to the
7592 /// new load / store.
7593 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7594   if (Level < AfterLegalizeDAG)
7595     return false;
7596
7597   bool isLoad = true;
7598   SDValue Ptr;
7599   EVT VT;
7600   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7601     if (LD->isIndexed())
7602       return false;
7603     VT = LD->getMemoryVT();
7604     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7605         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7606       return false;
7607     Ptr = LD->getBasePtr();
7608   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7609     if (ST->isIndexed())
7610       return false;
7611     VT = ST->getMemoryVT();
7612     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7613         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7614       return false;
7615     Ptr = ST->getBasePtr();
7616     isLoad = false;
7617   } else {
7618     return false;
7619   }
7620
7621   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7622   // out.  There is no reason to make this a preinc/predec.
7623   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7624       Ptr.getNode()->hasOneUse())
7625     return false;
7626
7627   // Ask the target to do addressing mode selection.
7628   SDValue BasePtr;
7629   SDValue Offset;
7630   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7631   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7632     return false;
7633
7634   // Backends without true r+i pre-indexed forms may need to pass a
7635   // constant base with a variable offset so that constant coercion
7636   // will work with the patterns in canonical form.
7637   bool Swapped = false;
7638   if (isa<ConstantSDNode>(BasePtr)) {
7639     std::swap(BasePtr, Offset);
7640     Swapped = true;
7641   }
7642
7643   // Don't create a indexed load / store with zero offset.
7644   if (isa<ConstantSDNode>(Offset) &&
7645       cast<ConstantSDNode>(Offset)->isNullValue())
7646     return false;
7647
7648   // Try turning it into a pre-indexed load / store except when:
7649   // 1) The new base ptr is a frame index.
7650   // 2) If N is a store and the new base ptr is either the same as or is a
7651   //    predecessor of the value being stored.
7652   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7653   //    that would create a cycle.
7654   // 4) All uses are load / store ops that use it as old base ptr.
7655
7656   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7657   // (plus the implicit offset) to a register to preinc anyway.
7658   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7659     return false;
7660
7661   // Check #2.
7662   if (!isLoad) {
7663     SDValue Val = cast<StoreSDNode>(N)->getValue();
7664     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7665       return false;
7666   }
7667
7668   // If the offset is a constant, there may be other adds of constants that
7669   // can be folded with this one. We should do this to avoid having to keep
7670   // a copy of the original base pointer.
7671   SmallVector<SDNode *, 16> OtherUses;
7672   if (isa<ConstantSDNode>(Offset))
7673     for (SDNode *Use : BasePtr.getNode()->uses()) {
7674       if (Use == Ptr.getNode())
7675         continue;
7676
7677       if (Use->isPredecessorOf(N))
7678         continue;
7679
7680       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7681         OtherUses.clear();
7682         break;
7683       }
7684
7685       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7686       if (Op1.getNode() == BasePtr.getNode())
7687         std::swap(Op0, Op1);
7688       assert(Op0.getNode() == BasePtr.getNode() &&
7689              "Use of ADD/SUB but not an operand");
7690
7691       if (!isa<ConstantSDNode>(Op1)) {
7692         OtherUses.clear();
7693         break;
7694       }
7695
7696       // FIXME: In some cases, we can be smarter about this.
7697       if (Op1.getValueType() != Offset.getValueType()) {
7698         OtherUses.clear();
7699         break;
7700       }
7701
7702       OtherUses.push_back(Use);
7703     }
7704
7705   if (Swapped)
7706     std::swap(BasePtr, Offset);
7707
7708   // Now check for #3 and #4.
7709   bool RealUse = false;
7710
7711   // Caches for hasPredecessorHelper
7712   SmallPtrSet<const SDNode *, 32> Visited;
7713   SmallVector<const SDNode *, 16> Worklist;
7714
7715   for (SDNode *Use : Ptr.getNode()->uses()) {
7716     if (Use == N)
7717       continue;
7718     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7719       return false;
7720
7721     // If Ptr may be folded in addressing mode of other use, then it's
7722     // not profitable to do this transformation.
7723     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7724       RealUse = true;
7725   }
7726
7727   if (!RealUse)
7728     return false;
7729
7730   SDValue Result;
7731   if (isLoad)
7732     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7733                                 BasePtr, Offset, AM);
7734   else
7735     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7736                                  BasePtr, Offset, AM);
7737   ++PreIndexedNodes;
7738   ++NodesCombined;
7739   DEBUG(dbgs() << "\nReplacing.4 ";
7740         N->dump(&DAG);
7741         dbgs() << "\nWith: ";
7742         Result.getNode()->dump(&DAG);
7743         dbgs() << '\n');
7744   WorkListRemover DeadNodes(*this);
7745   if (isLoad) {
7746     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7747     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7748   } else {
7749     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7750   }
7751
7752   // Finally, since the node is now dead, remove it from the graph.
7753   DAG.DeleteNode(N);
7754
7755   if (Swapped)
7756     std::swap(BasePtr, Offset);
7757
7758   // Replace other uses of BasePtr that can be updated to use Ptr
7759   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7760     unsigned OffsetIdx = 1;
7761     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7762       OffsetIdx = 0;
7763     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7764            BasePtr.getNode() && "Expected BasePtr operand");
7765
7766     // We need to replace ptr0 in the following expression:
7767     //   x0 * offset0 + y0 * ptr0 = t0
7768     // knowing that
7769     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7770     //
7771     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7772     // indexed load/store and the expresion that needs to be re-written.
7773     //
7774     // Therefore, we have:
7775     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7776
7777     ConstantSDNode *CN =
7778       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7779     int X0, X1, Y0, Y1;
7780     APInt Offset0 = CN->getAPIntValue();
7781     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7782
7783     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7784     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7785     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7786     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7787
7788     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7789
7790     APInt CNV = Offset0;
7791     if (X0 < 0) CNV = -CNV;
7792     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7793     else CNV = CNV - Offset1;
7794
7795     // We can now generate the new expression.
7796     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7797     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7798
7799     SDValue NewUse = DAG.getNode(Opcode,
7800                                  SDLoc(OtherUses[i]),
7801                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7802     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7803     removeFromWorkList(OtherUses[i]);
7804     DAG.DeleteNode(OtherUses[i]);
7805   }
7806
7807   // Replace the uses of Ptr with uses of the updated base value.
7808   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7809   removeFromWorkList(Ptr.getNode());
7810   DAG.DeleteNode(Ptr.getNode());
7811
7812   return true;
7813 }
7814
7815 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7816 /// add / sub of the base pointer node into a post-indexed load / store.
7817 /// The transformation folded the add / subtract into the new indexed
7818 /// load / store effectively and all of its uses are redirected to the
7819 /// new load / store.
7820 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7821   if (Level < AfterLegalizeDAG)
7822     return false;
7823
7824   bool isLoad = true;
7825   SDValue Ptr;
7826   EVT VT;
7827   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7828     if (LD->isIndexed())
7829       return false;
7830     VT = LD->getMemoryVT();
7831     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7832         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7833       return false;
7834     Ptr = LD->getBasePtr();
7835   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7836     if (ST->isIndexed())
7837       return false;
7838     VT = ST->getMemoryVT();
7839     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7840         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7841       return false;
7842     Ptr = ST->getBasePtr();
7843     isLoad = false;
7844   } else {
7845     return false;
7846   }
7847
7848   if (Ptr.getNode()->hasOneUse())
7849     return false;
7850
7851   for (SDNode *Op : Ptr.getNode()->uses()) {
7852     if (Op == N ||
7853         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7854       continue;
7855
7856     SDValue BasePtr;
7857     SDValue Offset;
7858     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7859     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7860       // Don't create a indexed load / store with zero offset.
7861       if (isa<ConstantSDNode>(Offset) &&
7862           cast<ConstantSDNode>(Offset)->isNullValue())
7863         continue;
7864
7865       // Try turning it into a post-indexed load / store except when
7866       // 1) All uses are load / store ops that use it as base ptr (and
7867       //    it may be folded as addressing mmode).
7868       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7869       //    nor a successor of N. Otherwise, if Op is folded that would
7870       //    create a cycle.
7871
7872       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7873         continue;
7874
7875       // Check for #1.
7876       bool TryNext = false;
7877       for (SDNode *Use : BasePtr.getNode()->uses()) {
7878         if (Use == Ptr.getNode())
7879           continue;
7880
7881         // If all the uses are load / store addresses, then don't do the
7882         // transformation.
7883         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7884           bool RealUse = false;
7885           for (SDNode *UseUse : Use->uses()) {
7886             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7887               RealUse = true;
7888           }
7889
7890           if (!RealUse) {
7891             TryNext = true;
7892             break;
7893           }
7894         }
7895       }
7896
7897       if (TryNext)
7898         continue;
7899
7900       // Check for #2
7901       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7902         SDValue Result = isLoad
7903           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7904                                BasePtr, Offset, AM)
7905           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7906                                 BasePtr, Offset, AM);
7907         ++PostIndexedNodes;
7908         ++NodesCombined;
7909         DEBUG(dbgs() << "\nReplacing.5 ";
7910               N->dump(&DAG);
7911               dbgs() << "\nWith: ";
7912               Result.getNode()->dump(&DAG);
7913               dbgs() << '\n');
7914         WorkListRemover DeadNodes(*this);
7915         if (isLoad) {
7916           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7917           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7918         } else {
7919           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7920         }
7921
7922         // Finally, since the node is now dead, remove it from the graph.
7923         DAG.DeleteNode(N);
7924
7925         // Replace the uses of Use with uses of the updated base value.
7926         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7927                                       Result.getValue(isLoad ? 1 : 0));
7928         removeFromWorkList(Op);
7929         DAG.DeleteNode(Op);
7930         return true;
7931       }
7932     }
7933   }
7934
7935   return false;
7936 }
7937
7938 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7939   LoadSDNode *LD  = cast<LoadSDNode>(N);
7940   SDValue Chain = LD->getChain();
7941   SDValue Ptr   = LD->getBasePtr();
7942
7943   // If load is not volatile and there are no uses of the loaded value (and
7944   // the updated indexed value in case of indexed loads), change uses of the
7945   // chain value into uses of the chain input (i.e. delete the dead load).
7946   if (!LD->isVolatile()) {
7947     if (N->getValueType(1) == MVT::Other) {
7948       // Unindexed loads.
7949       if (!N->hasAnyUseOfValue(0)) {
7950         // It's not safe to use the two value CombineTo variant here. e.g.
7951         // v1, chain2 = load chain1, loc
7952         // v2, chain3 = load chain2, loc
7953         // v3         = add v2, c
7954         // Now we replace use of chain2 with chain1.  This makes the second load
7955         // isomorphic to the one we are deleting, and thus makes this load live.
7956         DEBUG(dbgs() << "\nReplacing.6 ";
7957               N->dump(&DAG);
7958               dbgs() << "\nWith chain: ";
7959               Chain.getNode()->dump(&DAG);
7960               dbgs() << "\n");
7961         WorkListRemover DeadNodes(*this);
7962         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7963
7964         if (N->use_empty()) {
7965           removeFromWorkList(N);
7966           DAG.DeleteNode(N);
7967         }
7968
7969         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7970       }
7971     } else {
7972       // Indexed loads.
7973       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7974       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7975         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7976         DEBUG(dbgs() << "\nReplacing.7 ";
7977               N->dump(&DAG);
7978               dbgs() << "\nWith: ";
7979               Undef.getNode()->dump(&DAG);
7980               dbgs() << " and 2 other values\n");
7981         WorkListRemover DeadNodes(*this);
7982         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7983         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7984                                       DAG.getUNDEF(N->getValueType(1)));
7985         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7986         removeFromWorkList(N);
7987         DAG.DeleteNode(N);
7988         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7989       }
7990     }
7991   }
7992
7993   // If this load is directly stored, replace the load value with the stored
7994   // value.
7995   // TODO: Handle store large -> read small portion.
7996   // TODO: Handle TRUNCSTORE/LOADEXT
7997   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7998     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7999       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8000       if (PrevST->getBasePtr() == Ptr &&
8001           PrevST->getValue().getValueType() == N->getValueType(0))
8002       return CombineTo(N, Chain.getOperand(1), Chain);
8003     }
8004   }
8005
8006   // Try to infer better alignment information than the load already has.
8007   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8008     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8009       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8010         SDValue NewLoad =
8011                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8012                               LD->getValueType(0),
8013                               Chain, Ptr, LD->getPointerInfo(),
8014                               LD->getMemoryVT(),
8015                               LD->isVolatile(), LD->isNonTemporal(), Align,
8016                               LD->getTBAAInfo());
8017         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8018       }
8019     }
8020   }
8021
8022   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8023     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8024 #ifndef NDEBUG
8025   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8026       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8027     UseAA = false;
8028 #endif
8029   if (UseAA && LD->isUnindexed()) {
8030     // Walk up chain skipping non-aliasing memory nodes.
8031     SDValue BetterChain = FindBetterChain(N, Chain);
8032
8033     // If there is a better chain.
8034     if (Chain != BetterChain) {
8035       SDValue ReplLoad;
8036
8037       // Replace the chain to void dependency.
8038       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8039         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8040                                BetterChain, Ptr, LD->getMemOperand());
8041       } else {
8042         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8043                                   LD->getValueType(0),
8044                                   BetterChain, Ptr, LD->getMemoryVT(),
8045                                   LD->getMemOperand());
8046       }
8047
8048       // Create token factor to keep old chain connected.
8049       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8050                                   MVT::Other, Chain, ReplLoad.getValue(1));
8051
8052       // Make sure the new and old chains are cleaned up.
8053       AddToWorkList(Token.getNode());
8054
8055       // Replace uses with load result and token factor. Don't add users
8056       // to work list.
8057       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8058     }
8059   }
8060
8061   // Try transforming N to an indexed load.
8062   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8063     return SDValue(N, 0);
8064
8065   // Try to slice up N to more direct loads if the slices are mapped to
8066   // different register banks or pairing can take place.
8067   if (SliceUpLoad(N))
8068     return SDValue(N, 0);
8069
8070   return SDValue();
8071 }
8072
8073 namespace {
8074 /// \brief Helper structure used to slice a load in smaller loads.
8075 /// Basically a slice is obtained from the following sequence:
8076 /// Origin = load Ty1, Base
8077 /// Shift = srl Ty1 Origin, CstTy Amount
8078 /// Inst = trunc Shift to Ty2
8079 ///
8080 /// Then, it will be rewriten into:
8081 /// Slice = load SliceTy, Base + SliceOffset
8082 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8083 ///
8084 /// SliceTy is deduced from the number of bits that are actually used to
8085 /// build Inst.
8086 struct LoadedSlice {
8087   /// \brief Helper structure used to compute the cost of a slice.
8088   struct Cost {
8089     /// Are we optimizing for code size.
8090     bool ForCodeSize;
8091     /// Various cost.
8092     unsigned Loads;
8093     unsigned Truncates;
8094     unsigned CrossRegisterBanksCopies;
8095     unsigned ZExts;
8096     unsigned Shift;
8097
8098     Cost(bool ForCodeSize = false)
8099         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8100           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8101
8102     /// \brief Get the cost of one isolated slice.
8103     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8104         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8105           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8106       EVT TruncType = LS.Inst->getValueType(0);
8107       EVT LoadedType = LS.getLoadedType();
8108       if (TruncType != LoadedType &&
8109           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8110         ZExts = 1;
8111     }
8112
8113     /// \brief Account for slicing gain in the current cost.
8114     /// Slicing provide a few gains like removing a shift or a
8115     /// truncate. This method allows to grow the cost of the original
8116     /// load with the gain from this slice.
8117     void addSliceGain(const LoadedSlice &LS) {
8118       // Each slice saves a truncate.
8119       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8120       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8121                               LS.Inst->getOperand(0).getValueType()))
8122         ++Truncates;
8123       // If there is a shift amount, this slice gets rid of it.
8124       if (LS.Shift)
8125         ++Shift;
8126       // If this slice can merge a cross register bank copy, account for it.
8127       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8128         ++CrossRegisterBanksCopies;
8129     }
8130
8131     Cost &operator+=(const Cost &RHS) {
8132       Loads += RHS.Loads;
8133       Truncates += RHS.Truncates;
8134       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8135       ZExts += RHS.ZExts;
8136       Shift += RHS.Shift;
8137       return *this;
8138     }
8139
8140     bool operator==(const Cost &RHS) const {
8141       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8142              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8143              ZExts == RHS.ZExts && Shift == RHS.Shift;
8144     }
8145
8146     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8147
8148     bool operator<(const Cost &RHS) const {
8149       // Assume cross register banks copies are as expensive as loads.
8150       // FIXME: Do we want some more target hooks?
8151       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8152       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8153       // Unless we are optimizing for code size, consider the
8154       // expensive operation first.
8155       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8156         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8157       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8158              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8159     }
8160
8161     bool operator>(const Cost &RHS) const { return RHS < *this; }
8162
8163     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8164
8165     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8166   };
8167   // The last instruction that represent the slice. This should be a
8168   // truncate instruction.
8169   SDNode *Inst;
8170   // The original load instruction.
8171   LoadSDNode *Origin;
8172   // The right shift amount in bits from the original load.
8173   unsigned Shift;
8174   // The DAG from which Origin came from.
8175   // This is used to get some contextual information about legal types, etc.
8176   SelectionDAG *DAG;
8177
8178   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8179               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8180       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8181
8182   LoadedSlice(const LoadedSlice &LS)
8183       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8184
8185   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8186   /// \return Result is \p BitWidth and has used bits set to 1 and
8187   ///         not used bits set to 0.
8188   APInt getUsedBits() const {
8189     // Reproduce the trunc(lshr) sequence:
8190     // - Start from the truncated value.
8191     // - Zero extend to the desired bit width.
8192     // - Shift left.
8193     assert(Origin && "No original load to compare against.");
8194     unsigned BitWidth = Origin->getValueSizeInBits(0);
8195     assert(Inst && "This slice is not bound to an instruction");
8196     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8197            "Extracted slice is bigger than the whole type!");
8198     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8199     UsedBits.setAllBits();
8200     UsedBits = UsedBits.zext(BitWidth);
8201     UsedBits <<= Shift;
8202     return UsedBits;
8203   }
8204
8205   /// \brief Get the size of the slice to be loaded in bytes.
8206   unsigned getLoadedSize() const {
8207     unsigned SliceSize = getUsedBits().countPopulation();
8208     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8209     return SliceSize / 8;
8210   }
8211
8212   /// \brief Get the type that will be loaded for this slice.
8213   /// Note: This may not be the final type for the slice.
8214   EVT getLoadedType() const {
8215     assert(DAG && "Missing context");
8216     LLVMContext &Ctxt = *DAG->getContext();
8217     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8218   }
8219
8220   /// \brief Get the alignment of the load used for this slice.
8221   unsigned getAlignment() const {
8222     unsigned Alignment = Origin->getAlignment();
8223     unsigned Offset = getOffsetFromBase();
8224     if (Offset != 0)
8225       Alignment = MinAlign(Alignment, Alignment + Offset);
8226     return Alignment;
8227   }
8228
8229   /// \brief Check if this slice can be rewritten with legal operations.
8230   bool isLegal() const {
8231     // An invalid slice is not legal.
8232     if (!Origin || !Inst || !DAG)
8233       return false;
8234
8235     // Offsets are for indexed load only, we do not handle that.
8236     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8237       return false;
8238
8239     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8240
8241     // Check that the type is legal.
8242     EVT SliceType = getLoadedType();
8243     if (!TLI.isTypeLegal(SliceType))
8244       return false;
8245
8246     // Check that the load is legal for this type.
8247     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8248       return false;
8249
8250     // Check that the offset can be computed.
8251     // 1. Check its type.
8252     EVT PtrType = Origin->getBasePtr().getValueType();
8253     if (PtrType == MVT::Untyped || PtrType.isExtended())
8254       return false;
8255
8256     // 2. Check that it fits in the immediate.
8257     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8258       return false;
8259
8260     // 3. Check that the computation is legal.
8261     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8262       return false;
8263
8264     // Check that the zext is legal if it needs one.
8265     EVT TruncateType = Inst->getValueType(0);
8266     if (TruncateType != SliceType &&
8267         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8268       return false;
8269
8270     return true;
8271   }
8272
8273   /// \brief Get the offset in bytes of this slice in the original chunk of
8274   /// bits.
8275   /// \pre DAG != nullptr.
8276   uint64_t getOffsetFromBase() const {
8277     assert(DAG && "Missing context.");
8278     bool IsBigEndian =
8279         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8280     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8281     uint64_t Offset = Shift / 8;
8282     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8283     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8284            "The size of the original loaded type is not a multiple of a"
8285            " byte.");
8286     // If Offset is bigger than TySizeInBytes, it means we are loading all
8287     // zeros. This should have been optimized before in the process.
8288     assert(TySizeInBytes > Offset &&
8289            "Invalid shift amount for given loaded size");
8290     if (IsBigEndian)
8291       Offset = TySizeInBytes - Offset - getLoadedSize();
8292     return Offset;
8293   }
8294
8295   /// \brief Generate the sequence of instructions to load the slice
8296   /// represented by this object and redirect the uses of this slice to
8297   /// this new sequence of instructions.
8298   /// \pre this->Inst && this->Origin are valid Instructions and this
8299   /// object passed the legal check: LoadedSlice::isLegal returned true.
8300   /// \return The last instruction of the sequence used to load the slice.
8301   SDValue loadSlice() const {
8302     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8303     const SDValue &OldBaseAddr = Origin->getBasePtr();
8304     SDValue BaseAddr = OldBaseAddr;
8305     // Get the offset in that chunk of bytes w.r.t. the endianess.
8306     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8307     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8308     if (Offset) {
8309       // BaseAddr = BaseAddr + Offset.
8310       EVT ArithType = BaseAddr.getValueType();
8311       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8312                               DAG->getConstant(Offset, ArithType));
8313     }
8314
8315     // Create the type of the loaded slice according to its size.
8316     EVT SliceType = getLoadedType();
8317
8318     // Create the load for the slice.
8319     SDValue LastInst = DAG->getLoad(
8320         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8321         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8322         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8323     // If the final type is not the same as the loaded type, this means that
8324     // we have to pad with zero. Create a zero extend for that.
8325     EVT FinalType = Inst->getValueType(0);
8326     if (SliceType != FinalType)
8327       LastInst =
8328           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8329     return LastInst;
8330   }
8331
8332   /// \brief Check if this slice can be merged with an expensive cross register
8333   /// bank copy. E.g.,
8334   /// i = load i32
8335   /// f = bitcast i32 i to float
8336   bool canMergeExpensiveCrossRegisterBankCopy() const {
8337     if (!Inst || !Inst->hasOneUse())
8338       return false;
8339     SDNode *Use = *Inst->use_begin();
8340     if (Use->getOpcode() != ISD::BITCAST)
8341       return false;
8342     assert(DAG && "Missing context");
8343     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8344     EVT ResVT = Use->getValueType(0);
8345     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8346     const TargetRegisterClass *ArgRC =
8347         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8348     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8349       return false;
8350
8351     // At this point, we know that we perform a cross-register-bank copy.
8352     // Check if it is expensive.
8353     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8354     // Assume bitcasts are cheap, unless both register classes do not
8355     // explicitly share a common sub class.
8356     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8357       return false;
8358
8359     // Check if it will be merged with the load.
8360     // 1. Check the alignment constraint.
8361     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8362         ResVT.getTypeForEVT(*DAG->getContext()));
8363
8364     if (RequiredAlignment > getAlignment())
8365       return false;
8366
8367     // 2. Check that the load is a legal operation for that type.
8368     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8369       return false;
8370
8371     // 3. Check that we do not have a zext in the way.
8372     if (Inst->getValueType(0) != getLoadedType())
8373       return false;
8374
8375     return true;
8376   }
8377 };
8378 }
8379
8380 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8381 /// \p UsedBits looks like 0..0 1..1 0..0.
8382 static bool areUsedBitsDense(const APInt &UsedBits) {
8383   // If all the bits are one, this is dense!
8384   if (UsedBits.isAllOnesValue())
8385     return true;
8386
8387   // Get rid of the unused bits on the right.
8388   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8389   // Get rid of the unused bits on the left.
8390   if (NarrowedUsedBits.countLeadingZeros())
8391     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8392   // Check that the chunk of bits is completely used.
8393   return NarrowedUsedBits.isAllOnesValue();
8394 }
8395
8396 /// \brief Check whether or not \p First and \p Second are next to each other
8397 /// in memory. This means that there is no hole between the bits loaded
8398 /// by \p First and the bits loaded by \p Second.
8399 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8400                                      const LoadedSlice &Second) {
8401   assert(First.Origin == Second.Origin && First.Origin &&
8402          "Unable to match different memory origins.");
8403   APInt UsedBits = First.getUsedBits();
8404   assert((UsedBits & Second.getUsedBits()) == 0 &&
8405          "Slices are not supposed to overlap.");
8406   UsedBits |= Second.getUsedBits();
8407   return areUsedBitsDense(UsedBits);
8408 }
8409
8410 /// \brief Adjust the \p GlobalLSCost according to the target
8411 /// paring capabilities and the layout of the slices.
8412 /// \pre \p GlobalLSCost should account for at least as many loads as
8413 /// there is in the slices in \p LoadedSlices.
8414 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8415                                  LoadedSlice::Cost &GlobalLSCost) {
8416   unsigned NumberOfSlices = LoadedSlices.size();
8417   // If there is less than 2 elements, no pairing is possible.
8418   if (NumberOfSlices < 2)
8419     return;
8420
8421   // Sort the slices so that elements that are likely to be next to each
8422   // other in memory are next to each other in the list.
8423   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8424             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8425     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8426     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8427   });
8428   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8429   // First (resp. Second) is the first (resp. Second) potentially candidate
8430   // to be placed in a paired load.
8431   const LoadedSlice *First = nullptr;
8432   const LoadedSlice *Second = nullptr;
8433   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8434                 // Set the beginning of the pair.
8435                                                            First = Second) {
8436
8437     Second = &LoadedSlices[CurrSlice];
8438
8439     // If First is NULL, it means we start a new pair.
8440     // Get to the next slice.
8441     if (!First)
8442       continue;
8443
8444     EVT LoadedType = First->getLoadedType();
8445
8446     // If the types of the slices are different, we cannot pair them.
8447     if (LoadedType != Second->getLoadedType())
8448       continue;
8449
8450     // Check if the target supplies paired loads for this type.
8451     unsigned RequiredAlignment = 0;
8452     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8453       // move to the next pair, this type is hopeless.
8454       Second = nullptr;
8455       continue;
8456     }
8457     // Check if we meet the alignment requirement.
8458     if (RequiredAlignment > First->getAlignment())
8459       continue;
8460
8461     // Check that both loads are next to each other in memory.
8462     if (!areSlicesNextToEachOther(*First, *Second))
8463       continue;
8464
8465     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8466     --GlobalLSCost.Loads;
8467     // Move to the next pair.
8468     Second = nullptr;
8469   }
8470 }
8471
8472 /// \brief Check the profitability of all involved LoadedSlice.
8473 /// Currently, it is considered profitable if there is exactly two
8474 /// involved slices (1) which are (2) next to each other in memory, and
8475 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8476 ///
8477 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8478 /// the elements themselves.
8479 ///
8480 /// FIXME: When the cost model will be mature enough, we can relax
8481 /// constraints (1) and (2).
8482 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8483                                 const APInt &UsedBits, bool ForCodeSize) {
8484   unsigned NumberOfSlices = LoadedSlices.size();
8485   if (StressLoadSlicing)
8486     return NumberOfSlices > 1;
8487
8488   // Check (1).
8489   if (NumberOfSlices != 2)
8490     return false;
8491
8492   // Check (2).
8493   if (!areUsedBitsDense(UsedBits))
8494     return false;
8495
8496   // Check (3).
8497   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8498   // The original code has one big load.
8499   OrigCost.Loads = 1;
8500   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8501     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8502     // Accumulate the cost of all the slices.
8503     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8504     GlobalSlicingCost += SliceCost;
8505
8506     // Account as cost in the original configuration the gain obtained
8507     // with the current slices.
8508     OrigCost.addSliceGain(LS);
8509   }
8510
8511   // If the target supports paired load, adjust the cost accordingly.
8512   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8513   return OrigCost > GlobalSlicingCost;
8514 }
8515
8516 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8517 /// operations, split it in the various pieces being extracted.
8518 ///
8519 /// This sort of thing is introduced by SROA.
8520 /// This slicing takes care not to insert overlapping loads.
8521 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8522 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8523   if (Level < AfterLegalizeDAG)
8524     return false;
8525
8526   LoadSDNode *LD = cast<LoadSDNode>(N);
8527   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8528       !LD->getValueType(0).isInteger())
8529     return false;
8530
8531   // Keep track of already used bits to detect overlapping values.
8532   // In that case, we will just abort the transformation.
8533   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8534
8535   SmallVector<LoadedSlice, 4> LoadedSlices;
8536
8537   // Check if this load is used as several smaller chunks of bits.
8538   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8539   // of computation for each trunc.
8540   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8541        UI != UIEnd; ++UI) {
8542     // Skip the uses of the chain.
8543     if (UI.getUse().getResNo() != 0)
8544       continue;
8545
8546     SDNode *User = *UI;
8547     unsigned Shift = 0;
8548
8549     // Check if this is a trunc(lshr).
8550     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8551         isa<ConstantSDNode>(User->getOperand(1))) {
8552       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8553       User = *User->use_begin();
8554     }
8555
8556     // At this point, User is a Truncate, iff we encountered, trunc or
8557     // trunc(lshr).
8558     if (User->getOpcode() != ISD::TRUNCATE)
8559       return false;
8560
8561     // The width of the type must be a power of 2 and greater than 8-bits.
8562     // Otherwise the load cannot be represented in LLVM IR.
8563     // Moreover, if we shifted with a non-8-bits multiple, the slice
8564     // will be across several bytes. We do not support that.
8565     unsigned Width = User->getValueSizeInBits(0);
8566     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8567       return 0;
8568
8569     // Build the slice for this chain of computations.
8570     LoadedSlice LS(User, LD, Shift, &DAG);
8571     APInt CurrentUsedBits = LS.getUsedBits();
8572
8573     // Check if this slice overlaps with another.
8574     if ((CurrentUsedBits & UsedBits) != 0)
8575       return false;
8576     // Update the bits used globally.
8577     UsedBits |= CurrentUsedBits;
8578
8579     // Check if the new slice would be legal.
8580     if (!LS.isLegal())
8581       return false;
8582
8583     // Record the slice.
8584     LoadedSlices.push_back(LS);
8585   }
8586
8587   // Abort slicing if it does not seem to be profitable.
8588   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8589     return false;
8590
8591   ++SlicedLoads;
8592
8593   // Rewrite each chain to use an independent load.
8594   // By construction, each chain can be represented by a unique load.
8595
8596   // Prepare the argument for the new token factor for all the slices.
8597   SmallVector<SDValue, 8> ArgChains;
8598   for (SmallVectorImpl<LoadedSlice>::const_iterator
8599            LSIt = LoadedSlices.begin(),
8600            LSItEnd = LoadedSlices.end();
8601        LSIt != LSItEnd; ++LSIt) {
8602     SDValue SliceInst = LSIt->loadSlice();
8603     CombineTo(LSIt->Inst, SliceInst, true);
8604     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8605       SliceInst = SliceInst.getOperand(0);
8606     assert(SliceInst->getOpcode() == ISD::LOAD &&
8607            "It takes more than a zext to get to the loaded slice!!");
8608     ArgChains.push_back(SliceInst.getValue(1));
8609   }
8610
8611   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8612                               ArgChains);
8613   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8614   return true;
8615 }
8616
8617 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8618 /// load is having specific bytes cleared out.  If so, return the byte size
8619 /// being masked out and the shift amount.
8620 static std::pair<unsigned, unsigned>
8621 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8622   std::pair<unsigned, unsigned> Result(0, 0);
8623
8624   // Check for the structure we're looking for.
8625   if (V->getOpcode() != ISD::AND ||
8626       !isa<ConstantSDNode>(V->getOperand(1)) ||
8627       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8628     return Result;
8629
8630   // Check the chain and pointer.
8631   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8632   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8633
8634   // The store should be chained directly to the load or be an operand of a
8635   // tokenfactor.
8636   if (LD == Chain.getNode())
8637     ; // ok.
8638   else if (Chain->getOpcode() != ISD::TokenFactor)
8639     return Result; // Fail.
8640   else {
8641     bool isOk = false;
8642     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8643       if (Chain->getOperand(i).getNode() == LD) {
8644         isOk = true;
8645         break;
8646       }
8647     if (!isOk) return Result;
8648   }
8649
8650   // This only handles simple types.
8651   if (V.getValueType() != MVT::i16 &&
8652       V.getValueType() != MVT::i32 &&
8653       V.getValueType() != MVT::i64)
8654     return Result;
8655
8656   // Check the constant mask.  Invert it so that the bits being masked out are
8657   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8658   // follow the sign bit for uniformity.
8659   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8660   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8661   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8662   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8663   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8664   if (NotMaskLZ == 64) return Result;  // All zero mask.
8665
8666   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8667   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8668     return Result;
8669
8670   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8671   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8672     NotMaskLZ -= 64-V.getValueSizeInBits();
8673
8674   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8675   switch (MaskedBytes) {
8676   case 1:
8677   case 2:
8678   case 4: break;
8679   default: return Result; // All one mask, or 5-byte mask.
8680   }
8681
8682   // Verify that the first bit starts at a multiple of mask so that the access
8683   // is aligned the same as the access width.
8684   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8685
8686   Result.first = MaskedBytes;
8687   Result.second = NotMaskTZ/8;
8688   return Result;
8689 }
8690
8691
8692 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8693 /// provides a value as specified by MaskInfo.  If so, replace the specified
8694 /// store with a narrower store of truncated IVal.
8695 static SDNode *
8696 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8697                                 SDValue IVal, StoreSDNode *St,
8698                                 DAGCombiner *DC) {
8699   unsigned NumBytes = MaskInfo.first;
8700   unsigned ByteShift = MaskInfo.second;
8701   SelectionDAG &DAG = DC->getDAG();
8702
8703   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8704   // that uses this.  If not, this is not a replacement.
8705   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8706                                   ByteShift*8, (ByteShift+NumBytes)*8);
8707   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8708
8709   // Check that it is legal on the target to do this.  It is legal if the new
8710   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8711   // legalization.
8712   MVT VT = MVT::getIntegerVT(NumBytes*8);
8713   if (!DC->isTypeLegal(VT))
8714     return nullptr;
8715
8716   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8717   // shifted by ByteShift and truncated down to NumBytes.
8718   if (ByteShift)
8719     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8720                        DAG.getConstant(ByteShift*8,
8721                                     DC->getShiftAmountTy(IVal.getValueType())));
8722
8723   // Figure out the offset for the store and the alignment of the access.
8724   unsigned StOffset;
8725   unsigned NewAlign = St->getAlignment();
8726
8727   if (DAG.getTargetLoweringInfo().isLittleEndian())
8728     StOffset = ByteShift;
8729   else
8730     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8731
8732   SDValue Ptr = St->getBasePtr();
8733   if (StOffset) {
8734     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8735                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8736     NewAlign = MinAlign(NewAlign, StOffset);
8737   }
8738
8739   // Truncate down to the new size.
8740   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8741
8742   ++OpsNarrowed;
8743   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8744                       St->getPointerInfo().getWithOffset(StOffset),
8745                       false, false, NewAlign).getNode();
8746 }
8747
8748
8749 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8750 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8751 /// of the loaded bits, try narrowing the load and store if it would end up
8752 /// being a win for performance or code size.
8753 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8754   StoreSDNode *ST  = cast<StoreSDNode>(N);
8755   if (ST->isVolatile())
8756     return SDValue();
8757
8758   SDValue Chain = ST->getChain();
8759   SDValue Value = ST->getValue();
8760   SDValue Ptr   = ST->getBasePtr();
8761   EVT VT = Value.getValueType();
8762
8763   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8764     return SDValue();
8765
8766   unsigned Opc = Value.getOpcode();
8767
8768   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8769   // is a byte mask indicating a consecutive number of bytes, check to see if
8770   // Y is known to provide just those bytes.  If so, we try to replace the
8771   // load + replace + store sequence with a single (narrower) store, which makes
8772   // the load dead.
8773   if (Opc == ISD::OR) {
8774     std::pair<unsigned, unsigned> MaskedLoad;
8775     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8776     if (MaskedLoad.first)
8777       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8778                                                   Value.getOperand(1), ST,this))
8779         return SDValue(NewST, 0);
8780
8781     // Or is commutative, so try swapping X and Y.
8782     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8783     if (MaskedLoad.first)
8784       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8785                                                   Value.getOperand(0), ST,this))
8786         return SDValue(NewST, 0);
8787   }
8788
8789   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8790       Value.getOperand(1).getOpcode() != ISD::Constant)
8791     return SDValue();
8792
8793   SDValue N0 = Value.getOperand(0);
8794   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8795       Chain == SDValue(N0.getNode(), 1)) {
8796     LoadSDNode *LD = cast<LoadSDNode>(N0);
8797     if (LD->getBasePtr() != Ptr ||
8798         LD->getPointerInfo().getAddrSpace() !=
8799         ST->getPointerInfo().getAddrSpace())
8800       return SDValue();
8801
8802     // Find the type to narrow it the load / op / store to.
8803     SDValue N1 = Value.getOperand(1);
8804     unsigned BitWidth = N1.getValueSizeInBits();
8805     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8806     if (Opc == ISD::AND)
8807       Imm ^= APInt::getAllOnesValue(BitWidth);
8808     if (Imm == 0 || Imm.isAllOnesValue())
8809       return SDValue();
8810     unsigned ShAmt = Imm.countTrailingZeros();
8811     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8812     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8813     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8814     while (NewBW < BitWidth &&
8815            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8816              TLI.isNarrowingProfitable(VT, NewVT))) {
8817       NewBW = NextPowerOf2(NewBW);
8818       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8819     }
8820     if (NewBW >= BitWidth)
8821       return SDValue();
8822
8823     // If the lsb changed does not start at the type bitwidth boundary,
8824     // start at the previous one.
8825     if (ShAmt % NewBW)
8826       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8827     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8828                                    std::min(BitWidth, ShAmt + NewBW));
8829     if ((Imm & Mask) == Imm) {
8830       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8831       if (Opc == ISD::AND)
8832         NewImm ^= APInt::getAllOnesValue(NewBW);
8833       uint64_t PtrOff = ShAmt / 8;
8834       // For big endian targets, we need to adjust the offset to the pointer to
8835       // load the correct bytes.
8836       if (TLI.isBigEndian())
8837         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8838
8839       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8840       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8841       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8842         return SDValue();
8843
8844       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8845                                    Ptr.getValueType(), Ptr,
8846                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8847       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8848                                   LD->getChain(), NewPtr,
8849                                   LD->getPointerInfo().getWithOffset(PtrOff),
8850                                   LD->isVolatile(), LD->isNonTemporal(),
8851                                   LD->isInvariant(), NewAlign,
8852                                   LD->getTBAAInfo());
8853       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8854                                    DAG.getConstant(NewImm, NewVT));
8855       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8856                                    NewVal, NewPtr,
8857                                    ST->getPointerInfo().getWithOffset(PtrOff),
8858                                    false, false, NewAlign);
8859
8860       AddToWorkList(NewPtr.getNode());
8861       AddToWorkList(NewLD.getNode());
8862       AddToWorkList(NewVal.getNode());
8863       WorkListRemover DeadNodes(*this);
8864       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8865       ++OpsNarrowed;
8866       return NewST;
8867     }
8868   }
8869
8870   return SDValue();
8871 }
8872
8873 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8874 /// if the load value isn't used by any other operations, then consider
8875 /// transforming the pair to integer load / store operations if the target
8876 /// deems the transformation profitable.
8877 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8878   StoreSDNode *ST  = cast<StoreSDNode>(N);
8879   SDValue Chain = ST->getChain();
8880   SDValue Value = ST->getValue();
8881   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8882       Value.hasOneUse() &&
8883       Chain == SDValue(Value.getNode(), 1)) {
8884     LoadSDNode *LD = cast<LoadSDNode>(Value);
8885     EVT VT = LD->getMemoryVT();
8886     if (!VT.isFloatingPoint() ||
8887         VT != ST->getMemoryVT() ||
8888         LD->isNonTemporal() ||
8889         ST->isNonTemporal() ||
8890         LD->getPointerInfo().getAddrSpace() != 0 ||
8891         ST->getPointerInfo().getAddrSpace() != 0)
8892       return SDValue();
8893
8894     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8895     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8896         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8897         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8898         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8899       return SDValue();
8900
8901     unsigned LDAlign = LD->getAlignment();
8902     unsigned STAlign = ST->getAlignment();
8903     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8904     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8905     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8906       return SDValue();
8907
8908     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8909                                 LD->getChain(), LD->getBasePtr(),
8910                                 LD->getPointerInfo(),
8911                                 false, false, false, LDAlign);
8912
8913     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8914                                  NewLD, ST->getBasePtr(),
8915                                  ST->getPointerInfo(),
8916                                  false, false, STAlign);
8917
8918     AddToWorkList(NewLD.getNode());
8919     AddToWorkList(NewST.getNode());
8920     WorkListRemover DeadNodes(*this);
8921     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8922     ++LdStFP2Int;
8923     return NewST;
8924   }
8925
8926   return SDValue();
8927 }
8928
8929 /// Helper struct to parse and store a memory address as base + index + offset.
8930 /// We ignore sign extensions when it is safe to do so.
8931 /// The following two expressions are not equivalent. To differentiate we need
8932 /// to store whether there was a sign extension involved in the index
8933 /// computation.
8934 ///  (load (i64 add (i64 copyfromreg %c)
8935 ///                 (i64 signextend (add (i8 load %index)
8936 ///                                      (i8 1))))
8937 /// vs
8938 ///
8939 /// (load (i64 add (i64 copyfromreg %c)
8940 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8941 ///                                         (i32 1)))))
8942 struct BaseIndexOffset {
8943   SDValue Base;
8944   SDValue Index;
8945   int64_t Offset;
8946   bool IsIndexSignExt;
8947
8948   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8949
8950   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8951                   bool IsIndexSignExt) :
8952     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8953
8954   bool equalBaseIndex(const BaseIndexOffset &Other) {
8955     return Other.Base == Base && Other.Index == Index &&
8956       Other.IsIndexSignExt == IsIndexSignExt;
8957   }
8958
8959   /// Parses tree in Ptr for base, index, offset addresses.
8960   static BaseIndexOffset match(SDValue Ptr) {
8961     bool IsIndexSignExt = false;
8962
8963     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8964     // instruction, then it could be just the BASE or everything else we don't
8965     // know how to handle. Just use Ptr as BASE and give up.
8966     if (Ptr->getOpcode() != ISD::ADD)
8967       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8968
8969     // We know that we have at least an ADD instruction. Try to pattern match
8970     // the simple case of BASE + OFFSET.
8971     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8972       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8973       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8974                               IsIndexSignExt);
8975     }
8976
8977     // Inside a loop the current BASE pointer is calculated using an ADD and a
8978     // MUL instruction. In this case Ptr is the actual BASE pointer.
8979     // (i64 add (i64 %array_ptr)
8980     //          (i64 mul (i64 %induction_var)
8981     //                   (i64 %element_size)))
8982     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8983       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8984
8985     // Look at Base + Index + Offset cases.
8986     SDValue Base = Ptr->getOperand(0);
8987     SDValue IndexOffset = Ptr->getOperand(1);
8988
8989     // Skip signextends.
8990     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8991       IndexOffset = IndexOffset->getOperand(0);
8992       IsIndexSignExt = true;
8993     }
8994
8995     // Either the case of Base + Index (no offset) or something else.
8996     if (IndexOffset->getOpcode() != ISD::ADD)
8997       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8998
8999     // Now we have the case of Base + Index + offset.
9000     SDValue Index = IndexOffset->getOperand(0);
9001     SDValue Offset = IndexOffset->getOperand(1);
9002
9003     if (!isa<ConstantSDNode>(Offset))
9004       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9005
9006     // Ignore signextends.
9007     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9008       Index = Index->getOperand(0);
9009       IsIndexSignExt = true;
9010     } else IsIndexSignExt = false;
9011
9012     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9013     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9014   }
9015 };
9016
9017 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9018 /// is located in a sequence of memory operations connected by a chain.
9019 struct MemOpLink {
9020   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9021     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9022   // Ptr to the mem node.
9023   LSBaseSDNode *MemNode;
9024   // Offset from the base ptr.
9025   int64_t OffsetFromBase;
9026   // What is the sequence number of this mem node.
9027   // Lowest mem operand in the DAG starts at zero.
9028   unsigned SequenceNum;
9029 };
9030
9031 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9032   EVT MemVT = St->getMemoryVT();
9033   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9034   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9035     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9036
9037   // Don't merge vectors into wider inputs.
9038   if (MemVT.isVector() || !MemVT.isSimple())
9039     return false;
9040
9041   // Perform an early exit check. Do not bother looking at stored values that
9042   // are not constants or loads.
9043   SDValue StoredVal = St->getValue();
9044   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9045   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9046       !IsLoadSrc)
9047     return false;
9048
9049   // Only look at ends of store sequences.
9050   SDValue Chain = SDValue(St, 1);
9051   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9052     return false;
9053
9054   // This holds the base pointer, index, and the offset in bytes from the base
9055   // pointer.
9056   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9057
9058   // We must have a base and an offset.
9059   if (!BasePtr.Base.getNode())
9060     return false;
9061
9062   // Do not handle stores to undef base pointers.
9063   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9064     return false;
9065
9066   // Save the LoadSDNodes that we find in the chain.
9067   // We need to make sure that these nodes do not interfere with
9068   // any of the store nodes.
9069   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9070
9071   // Save the StoreSDNodes that we find in the chain.
9072   SmallVector<MemOpLink, 8> StoreNodes;
9073
9074   // Walk up the chain and look for nodes with offsets from the same
9075   // base pointer. Stop when reaching an instruction with a different kind
9076   // or instruction which has a different base pointer.
9077   unsigned Seq = 0;
9078   StoreSDNode *Index = St;
9079   while (Index) {
9080     // If the chain has more than one use, then we can't reorder the mem ops.
9081     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9082       break;
9083
9084     // Find the base pointer and offset for this memory node.
9085     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9086
9087     // Check that the base pointer is the same as the original one.
9088     if (!Ptr.equalBaseIndex(BasePtr))
9089       break;
9090
9091     // Check that the alignment is the same.
9092     if (Index->getAlignment() != St->getAlignment())
9093       break;
9094
9095     // The memory operands must not be volatile.
9096     if (Index->isVolatile() || Index->isIndexed())
9097       break;
9098
9099     // No truncation.
9100     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9101       if (St->isTruncatingStore())
9102         break;
9103
9104     // The stored memory type must be the same.
9105     if (Index->getMemoryVT() != MemVT)
9106       break;
9107
9108     // We do not allow unaligned stores because we want to prevent overriding
9109     // stores.
9110     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9111       break;
9112
9113     // We found a potential memory operand to merge.
9114     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9115
9116     // Find the next memory operand in the chain. If the next operand in the
9117     // chain is a store then move up and continue the scan with the next
9118     // memory operand. If the next operand is a load save it and use alias
9119     // information to check if it interferes with anything.
9120     SDNode *NextInChain = Index->getChain().getNode();
9121     while (1) {
9122       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9123         // We found a store node. Use it for the next iteration.
9124         Index = STn;
9125         break;
9126       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9127         if (Ldn->isVolatile()) {
9128           Index = nullptr;
9129           break;
9130         }
9131
9132         // Save the load node for later. Continue the scan.
9133         AliasLoadNodes.push_back(Ldn);
9134         NextInChain = Ldn->getChain().getNode();
9135         continue;
9136       } else {
9137         Index = nullptr;
9138         break;
9139       }
9140     }
9141   }
9142
9143   // Check if there is anything to merge.
9144   if (StoreNodes.size() < 2)
9145     return false;
9146
9147   // Sort the memory operands according to their distance from the base pointer.
9148   std::sort(StoreNodes.begin(), StoreNodes.end(),
9149             [](MemOpLink LHS, MemOpLink RHS) {
9150     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9151            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9152             LHS.SequenceNum > RHS.SequenceNum);
9153   });
9154
9155   // Scan the memory operations on the chain and find the first non-consecutive
9156   // store memory address.
9157   unsigned LastConsecutiveStore = 0;
9158   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9159   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9160
9161     // Check that the addresses are consecutive starting from the second
9162     // element in the list of stores.
9163     if (i > 0) {
9164       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9165       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9166         break;
9167     }
9168
9169     bool Alias = false;
9170     // Check if this store interferes with any of the loads that we found.
9171     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9172       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9173         Alias = true;
9174         break;
9175       }
9176     // We found a load that alias with this store. Stop the sequence.
9177     if (Alias)
9178       break;
9179
9180     // Mark this node as useful.
9181     LastConsecutiveStore = i;
9182   }
9183
9184   // The node with the lowest store address.
9185   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9186
9187   // Store the constants into memory as one consecutive store.
9188   if (!IsLoadSrc) {
9189     unsigned LastLegalType = 0;
9190     unsigned LastLegalVectorType = 0;
9191     bool NonZero = false;
9192     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9193       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9194       SDValue StoredVal = St->getValue();
9195
9196       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9197         NonZero |= !C->isNullValue();
9198       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9199         NonZero |= !C->getConstantFPValue()->isNullValue();
9200       } else {
9201         // Non-constant.
9202         break;
9203       }
9204
9205       // Find a legal type for the constant store.
9206       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9207       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9208       if (TLI.isTypeLegal(StoreTy))
9209         LastLegalType = i+1;
9210       // Or check whether a truncstore is legal.
9211       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9212                TargetLowering::TypePromoteInteger) {
9213         EVT LegalizedStoredValueTy =
9214           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9215         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9216           LastLegalType = i+1;
9217       }
9218
9219       // Find a legal type for the vector store.
9220       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9221       if (TLI.isTypeLegal(Ty))
9222         LastLegalVectorType = i + 1;
9223     }
9224
9225     // We only use vectors if the constant is known to be zero and the
9226     // function is not marked with the noimplicitfloat attribute.
9227     if (NonZero || NoVectors)
9228       LastLegalVectorType = 0;
9229
9230     // Check if we found a legal integer type to store.
9231     if (LastLegalType == 0 && LastLegalVectorType == 0)
9232       return false;
9233
9234     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9235     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9236
9237     // Make sure we have something to merge.
9238     if (NumElem < 2)
9239       return false;
9240
9241     unsigned EarliestNodeUsed = 0;
9242     for (unsigned i=0; i < NumElem; ++i) {
9243       // Find a chain for the new wide-store operand. Notice that some
9244       // of the store nodes that we found may not be selected for inclusion
9245       // in the wide store. The chain we use needs to be the chain of the
9246       // earliest store node which is *used* and replaced by the wide store.
9247       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9248         EarliestNodeUsed = i;
9249     }
9250
9251     // The earliest Node in the DAG.
9252     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9253     SDLoc DL(StoreNodes[0].MemNode);
9254
9255     SDValue StoredVal;
9256     if (UseVector) {
9257       // Find a legal type for the vector store.
9258       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9259       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9260       StoredVal = DAG.getConstant(0, Ty);
9261     } else {
9262       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9263       APInt StoreInt(StoreBW, 0);
9264
9265       // Construct a single integer constant which is made of the smaller
9266       // constant inputs.
9267       bool IsLE = TLI.isLittleEndian();
9268       for (unsigned i = 0; i < NumElem ; ++i) {
9269         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9270         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9271         SDValue Val = St->getValue();
9272         StoreInt<<=ElementSizeBytes*8;
9273         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9274           StoreInt|=C->getAPIntValue().zext(StoreBW);
9275         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9276           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9277         } else {
9278           assert(false && "Invalid constant element type");
9279         }
9280       }
9281
9282       // Create the new Load and Store operations.
9283       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9284       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9285     }
9286
9287     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9288                                     FirstInChain->getBasePtr(),
9289                                     FirstInChain->getPointerInfo(),
9290                                     false, false,
9291                                     FirstInChain->getAlignment());
9292
9293     // Replace the first store with the new store
9294     CombineTo(EarliestOp, NewStore);
9295     // Erase all other stores.
9296     for (unsigned i = 0; i < NumElem ; ++i) {
9297       if (StoreNodes[i].MemNode == EarliestOp)
9298         continue;
9299       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9300       // ReplaceAllUsesWith will replace all uses that existed when it was
9301       // called, but graph optimizations may cause new ones to appear. For
9302       // example, the case in pr14333 looks like
9303       //
9304       //  St's chain -> St -> another store -> X
9305       //
9306       // And the only difference from St to the other store is the chain.
9307       // When we change it's chain to be St's chain they become identical,
9308       // get CSEed and the net result is that X is now a use of St.
9309       // Since we know that St is redundant, just iterate.
9310       while (!St->use_empty())
9311         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9312       removeFromWorkList(St);
9313       DAG.DeleteNode(St);
9314     }
9315
9316     return true;
9317   }
9318
9319   // Below we handle the case of multiple consecutive stores that
9320   // come from multiple consecutive loads. We merge them into a single
9321   // wide load and a single wide store.
9322
9323   // Look for load nodes which are used by the stored values.
9324   SmallVector<MemOpLink, 8> LoadNodes;
9325
9326   // Find acceptable loads. Loads need to have the same chain (token factor),
9327   // must not be zext, volatile, indexed, and they must be consecutive.
9328   BaseIndexOffset LdBasePtr;
9329   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9330     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9331     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9332     if (!Ld) break;
9333
9334     // Loads must only have one use.
9335     if (!Ld->hasNUsesOfValue(1, 0))
9336       break;
9337
9338     // Check that the alignment is the same as the stores.
9339     if (Ld->getAlignment() != St->getAlignment())
9340       break;
9341
9342     // The memory operands must not be volatile.
9343     if (Ld->isVolatile() || Ld->isIndexed())
9344       break;
9345
9346     // We do not accept ext loads.
9347     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9348       break;
9349
9350     // The stored memory type must be the same.
9351     if (Ld->getMemoryVT() != MemVT)
9352       break;
9353
9354     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9355     // If this is not the first ptr that we check.
9356     if (LdBasePtr.Base.getNode()) {
9357       // The base ptr must be the same.
9358       if (!LdPtr.equalBaseIndex(LdBasePtr))
9359         break;
9360     } else {
9361       // Check that all other base pointers are the same as this one.
9362       LdBasePtr = LdPtr;
9363     }
9364
9365     // We found a potential memory operand to merge.
9366     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9367   }
9368
9369   if (LoadNodes.size() < 2)
9370     return false;
9371
9372   // Scan the memory operations on the chain and find the first non-consecutive
9373   // load memory address. These variables hold the index in the store node
9374   // array.
9375   unsigned LastConsecutiveLoad = 0;
9376   // This variable refers to the size and not index in the array.
9377   unsigned LastLegalVectorType = 0;
9378   unsigned LastLegalIntegerType = 0;
9379   StartAddress = LoadNodes[0].OffsetFromBase;
9380   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9381   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9382     // All loads much share the same chain.
9383     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9384       break;
9385
9386     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9387     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9388       break;
9389     LastConsecutiveLoad = i;
9390
9391     // Find a legal type for the vector store.
9392     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9393     if (TLI.isTypeLegal(StoreTy))
9394       LastLegalVectorType = i + 1;
9395
9396     // Find a legal type for the integer store.
9397     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9398     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9399     if (TLI.isTypeLegal(StoreTy))
9400       LastLegalIntegerType = i + 1;
9401     // Or check whether a truncstore and extload is legal.
9402     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9403              TargetLowering::TypePromoteInteger) {
9404       EVT LegalizedStoredValueTy =
9405         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9406       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9407           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9408           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9409           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9410         LastLegalIntegerType = i+1;
9411     }
9412   }
9413
9414   // Only use vector types if the vector type is larger than the integer type.
9415   // If they are the same, use integers.
9416   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9417   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9418
9419   // We add +1 here because the LastXXX variables refer to location while
9420   // the NumElem refers to array/index size.
9421   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9422   NumElem = std::min(LastLegalType, NumElem);
9423
9424   if (NumElem < 2)
9425     return false;
9426
9427   // The earliest Node in the DAG.
9428   unsigned EarliestNodeUsed = 0;
9429   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9430   for (unsigned i=1; i<NumElem; ++i) {
9431     // Find a chain for the new wide-store operand. Notice that some
9432     // of the store nodes that we found may not be selected for inclusion
9433     // in the wide store. The chain we use needs to be the chain of the
9434     // earliest store node which is *used* and replaced by the wide store.
9435     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9436       EarliestNodeUsed = i;
9437   }
9438
9439   // Find if it is better to use vectors or integers to load and store
9440   // to memory.
9441   EVT JointMemOpVT;
9442   if (UseVectorTy) {
9443     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9444   } else {
9445     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9446     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9447   }
9448
9449   SDLoc LoadDL(LoadNodes[0].MemNode);
9450   SDLoc StoreDL(StoreNodes[0].MemNode);
9451
9452   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9453   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9454                                 FirstLoad->getChain(),
9455                                 FirstLoad->getBasePtr(),
9456                                 FirstLoad->getPointerInfo(),
9457                                 false, false, false,
9458                                 FirstLoad->getAlignment());
9459
9460   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9461                                   FirstInChain->getBasePtr(),
9462                                   FirstInChain->getPointerInfo(), false, false,
9463                                   FirstInChain->getAlignment());
9464
9465   // Replace one of the loads with the new load.
9466   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9467   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9468                                 SDValue(NewLoad.getNode(), 1));
9469
9470   // Remove the rest of the load chains.
9471   for (unsigned i = 1; i < NumElem ; ++i) {
9472     // Replace all chain users of the old load nodes with the chain of the new
9473     // load node.
9474     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9475     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9476   }
9477
9478   // Replace the first store with the new store.
9479   CombineTo(EarliestOp, NewStore);
9480   // Erase all other stores.
9481   for (unsigned i = 0; i < NumElem ; ++i) {
9482     // Remove all Store nodes.
9483     if (StoreNodes[i].MemNode == EarliestOp)
9484       continue;
9485     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9486     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9487     removeFromWorkList(St);
9488     DAG.DeleteNode(St);
9489   }
9490
9491   return true;
9492 }
9493
9494 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9495   StoreSDNode *ST  = cast<StoreSDNode>(N);
9496   SDValue Chain = ST->getChain();
9497   SDValue Value = ST->getValue();
9498   SDValue Ptr   = ST->getBasePtr();
9499
9500   // If this is a store of a bit convert, store the input value if the
9501   // resultant store does not need a higher alignment than the original.
9502   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9503       ST->isUnindexed()) {
9504     unsigned OrigAlign = ST->getAlignment();
9505     EVT SVT = Value.getOperand(0).getValueType();
9506     unsigned Align = TLI.getDataLayout()->
9507       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9508     if (Align <= OrigAlign &&
9509         ((!LegalOperations && !ST->isVolatile()) ||
9510          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9511       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9512                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9513                           ST->isNonTemporal(), OrigAlign,
9514                           ST->getTBAAInfo());
9515   }
9516
9517   // Turn 'store undef, Ptr' -> nothing.
9518   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9519     return Chain;
9520
9521   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9522   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9523     // NOTE: If the original store is volatile, this transform must not increase
9524     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9525     // processor operation but an i64 (which is not legal) requires two.  So the
9526     // transform should not be done in this case.
9527     if (Value.getOpcode() != ISD::TargetConstantFP) {
9528       SDValue Tmp;
9529       switch (CFP->getSimpleValueType(0).SimpleTy) {
9530       default: llvm_unreachable("Unknown FP type");
9531       case MVT::f16:    // We don't do this for these yet.
9532       case MVT::f80:
9533       case MVT::f128:
9534       case MVT::ppcf128:
9535         break;
9536       case MVT::f32:
9537         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9538             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9539           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9540                               bitcastToAPInt().getZExtValue(), MVT::i32);
9541           return DAG.getStore(Chain, SDLoc(N), Tmp,
9542                               Ptr, ST->getMemOperand());
9543         }
9544         break;
9545       case MVT::f64:
9546         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9547              !ST->isVolatile()) ||
9548             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9549           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9550                                 getZExtValue(), MVT::i64);
9551           return DAG.getStore(Chain, SDLoc(N), Tmp,
9552                               Ptr, ST->getMemOperand());
9553         }
9554
9555         if (!ST->isVolatile() &&
9556             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9557           // Many FP stores are not made apparent until after legalize, e.g. for
9558           // argument passing.  Since this is so common, custom legalize the
9559           // 64-bit integer store into two 32-bit stores.
9560           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9561           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9562           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9563           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9564
9565           unsigned Alignment = ST->getAlignment();
9566           bool isVolatile = ST->isVolatile();
9567           bool isNonTemporal = ST->isNonTemporal();
9568           const MDNode *TBAAInfo = ST->getTBAAInfo();
9569
9570           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9571                                      Ptr, ST->getPointerInfo(),
9572                                      isVolatile, isNonTemporal,
9573                                      ST->getAlignment(), TBAAInfo);
9574           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9575                             DAG.getConstant(4, Ptr.getValueType()));
9576           Alignment = MinAlign(Alignment, 4U);
9577           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9578                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9579                                      isVolatile, isNonTemporal,
9580                                      Alignment, TBAAInfo);
9581           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9582                              St0, St1);
9583         }
9584
9585         break;
9586       }
9587     }
9588   }
9589
9590   // Try to infer better alignment information than the store already has.
9591   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9592     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9593       if (Align > ST->getAlignment())
9594         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9595                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9596                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9597                                  ST->getTBAAInfo());
9598     }
9599   }
9600
9601   // Try transforming a pair floating point load / store ops to integer
9602   // load / store ops.
9603   SDValue NewST = TransformFPLoadStorePair(N);
9604   if (NewST.getNode())
9605     return NewST;
9606
9607   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9608     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9609 #ifndef NDEBUG
9610   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9611       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9612     UseAA = false;
9613 #endif
9614   if (UseAA && ST->isUnindexed()) {
9615     // Walk up chain skipping non-aliasing memory nodes.
9616     SDValue BetterChain = FindBetterChain(N, Chain);
9617
9618     // If there is a better chain.
9619     if (Chain != BetterChain) {
9620       SDValue ReplStore;
9621
9622       // Replace the chain to avoid dependency.
9623       if (ST->isTruncatingStore()) {
9624         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9625                                       ST->getMemoryVT(), ST->getMemOperand());
9626       } else {
9627         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9628                                  ST->getMemOperand());
9629       }
9630
9631       // Create token to keep both nodes around.
9632       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9633                                   MVT::Other, Chain, ReplStore);
9634
9635       // Make sure the new and old chains are cleaned up.
9636       AddToWorkList(Token.getNode());
9637
9638       // Don't add users to work list.
9639       return CombineTo(N, Token, false);
9640     }
9641   }
9642
9643   // Try transforming N to an indexed store.
9644   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9645     return SDValue(N, 0);
9646
9647   // FIXME: is there such a thing as a truncating indexed store?
9648   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9649       Value.getValueType().isInteger()) {
9650     // See if we can simplify the input to this truncstore with knowledge that
9651     // only the low bits are being used.  For example:
9652     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9653     SDValue Shorter =
9654       GetDemandedBits(Value,
9655                       APInt::getLowBitsSet(
9656                         Value.getValueType().getScalarType().getSizeInBits(),
9657                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9658     AddToWorkList(Value.getNode());
9659     if (Shorter.getNode())
9660       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9661                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9662
9663     // Otherwise, see if we can simplify the operation with
9664     // SimplifyDemandedBits, which only works if the value has a single use.
9665     if (SimplifyDemandedBits(Value,
9666                         APInt::getLowBitsSet(
9667                           Value.getValueType().getScalarType().getSizeInBits(),
9668                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9669       return SDValue(N, 0);
9670   }
9671
9672   // If this is a load followed by a store to the same location, then the store
9673   // is dead/noop.
9674   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9675     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9676         ST->isUnindexed() && !ST->isVolatile() &&
9677         // There can't be any side effects between the load and store, such as
9678         // a call or store.
9679         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9680       // The store is dead, remove it.
9681       return Chain;
9682     }
9683   }
9684
9685   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9686   // truncating store.  We can do this even if this is already a truncstore.
9687   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9688       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9689       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9690                             ST->getMemoryVT())) {
9691     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9692                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9693   }
9694
9695   // Only perform this optimization before the types are legal, because we
9696   // don't want to perform this optimization on every DAGCombine invocation.
9697   if (!LegalTypes) {
9698     bool EverChanged = false;
9699
9700     do {
9701       // There can be multiple store sequences on the same chain.
9702       // Keep trying to merge store sequences until we are unable to do so
9703       // or until we merge the last store on the chain.
9704       bool Changed = MergeConsecutiveStores(ST);
9705       EverChanged |= Changed;
9706       if (!Changed) break;
9707     } while (ST->getOpcode() != ISD::DELETED_NODE);
9708
9709     if (EverChanged)
9710       return SDValue(N, 0);
9711   }
9712
9713   return ReduceLoadOpStoreWidth(N);
9714 }
9715
9716 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9717   SDValue InVec = N->getOperand(0);
9718   SDValue InVal = N->getOperand(1);
9719   SDValue EltNo = N->getOperand(2);
9720   SDLoc dl(N);
9721
9722   // If the inserted element is an UNDEF, just use the input vector.
9723   if (InVal.getOpcode() == ISD::UNDEF)
9724     return InVec;
9725
9726   EVT VT = InVec.getValueType();
9727
9728   // If we can't generate a legal BUILD_VECTOR, exit
9729   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9730     return SDValue();
9731
9732   // Check that we know which element is being inserted
9733   if (!isa<ConstantSDNode>(EltNo))
9734     return SDValue();
9735   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9736
9737   // Canonicalize insert_vector_elt dag nodes.
9738   // Example:
9739   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9740   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9741   //
9742   // Do this only if the child insert_vector node has one use; also
9743   // do this only if indices are both constants and Idx1 < Idx0.
9744   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9745       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9746     unsigned OtherElt =
9747       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9748     if (Elt < OtherElt) {
9749       // Swap nodes.
9750       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9751                                   InVec.getOperand(0), InVal, EltNo);
9752       AddToWorkList(NewOp.getNode());
9753       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9754                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9755     }
9756   }
9757
9758   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9759   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9760   // vector elements.
9761   SmallVector<SDValue, 8> Ops;
9762   // Do not combine these two vectors if the output vector will not replace
9763   // the input vector.
9764   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9765     Ops.append(InVec.getNode()->op_begin(),
9766                InVec.getNode()->op_end());
9767   } else if (InVec.getOpcode() == ISD::UNDEF) {
9768     unsigned NElts = VT.getVectorNumElements();
9769     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9770   } else {
9771     return SDValue();
9772   }
9773
9774   // Insert the element
9775   if (Elt < Ops.size()) {
9776     // All the operands of BUILD_VECTOR must have the same type;
9777     // we enforce that here.
9778     EVT OpVT = Ops[0].getValueType();
9779     if (InVal.getValueType() != OpVT)
9780       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9781                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9782                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9783     Ops[Elt] = InVal;
9784   }
9785
9786   // Return the new vector
9787   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9788 }
9789
9790 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9791   // (vextract (scalar_to_vector val, 0) -> val
9792   SDValue InVec = N->getOperand(0);
9793   EVT VT = InVec.getValueType();
9794   EVT NVT = N->getValueType(0);
9795
9796   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9797     // Check if the result type doesn't match the inserted element type. A
9798     // SCALAR_TO_VECTOR may truncate the inserted element and the
9799     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9800     SDValue InOp = InVec.getOperand(0);
9801     if (InOp.getValueType() != NVT) {
9802       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9803       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9804     }
9805     return InOp;
9806   }
9807
9808   SDValue EltNo = N->getOperand(1);
9809   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9810
9811   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9812   // We only perform this optimization before the op legalization phase because
9813   // we may introduce new vector instructions which are not backed by TD
9814   // patterns. For example on AVX, extracting elements from a wide vector
9815   // without using extract_subvector. However, if we can find an underlying
9816   // scalar value, then we can always use that.
9817   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9818       && ConstEltNo) {
9819     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9820     int NumElem = VT.getVectorNumElements();
9821     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9822     // Find the new index to extract from.
9823     int OrigElt = SVOp->getMaskElt(Elt);
9824
9825     // Extracting an undef index is undef.
9826     if (OrigElt == -1)
9827       return DAG.getUNDEF(NVT);
9828
9829     // Select the right vector half to extract from.
9830     SDValue SVInVec;
9831     if (OrigElt < NumElem) {
9832       SVInVec = InVec->getOperand(0);
9833     } else {
9834       SVInVec = InVec->getOperand(1);
9835       OrigElt -= NumElem;
9836     }
9837
9838     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9839       SDValue InOp = SVInVec.getOperand(OrigElt);
9840       if (InOp.getValueType() != NVT) {
9841         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9842         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9843       }
9844
9845       return InOp;
9846     }
9847
9848     // FIXME: We should handle recursing on other vector shuffles and
9849     // scalar_to_vector here as well.
9850
9851     if (!LegalOperations) {
9852       EVT IndexTy = TLI.getVectorIdxTy();
9853       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9854                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9855     }
9856   }
9857
9858   // Perform only after legalization to ensure build_vector / vector_shuffle
9859   // optimizations have already been done.
9860   if (!LegalOperations) return SDValue();
9861
9862   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9863   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9864   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9865
9866   if (ConstEltNo) {
9867     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9868     bool NewLoad = false;
9869     bool BCNumEltsChanged = false;
9870     EVT ExtVT = VT.getVectorElementType();
9871     EVT LVT = ExtVT;
9872
9873     // If the result of load has to be truncated, then it's not necessarily
9874     // profitable.
9875     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9876       return SDValue();
9877
9878     if (InVec.getOpcode() == ISD::BITCAST) {
9879       // Don't duplicate a load with other uses.
9880       if (!InVec.hasOneUse())
9881         return SDValue();
9882
9883       EVT BCVT = InVec.getOperand(0).getValueType();
9884       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9885         return SDValue();
9886       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9887         BCNumEltsChanged = true;
9888       InVec = InVec.getOperand(0);
9889       ExtVT = BCVT.getVectorElementType();
9890       NewLoad = true;
9891     }
9892
9893     LoadSDNode *LN0 = nullptr;
9894     const ShuffleVectorSDNode *SVN = nullptr;
9895     if (ISD::isNormalLoad(InVec.getNode())) {
9896       LN0 = cast<LoadSDNode>(InVec);
9897     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9898                InVec.getOperand(0).getValueType() == ExtVT &&
9899                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9900       // Don't duplicate a load with other uses.
9901       if (!InVec.hasOneUse())
9902         return SDValue();
9903
9904       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9905     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9906       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9907       // =>
9908       // (load $addr+1*size)
9909
9910       // Don't duplicate a load with other uses.
9911       if (!InVec.hasOneUse())
9912         return SDValue();
9913
9914       // If the bit convert changed the number of elements, it is unsafe
9915       // to examine the mask.
9916       if (BCNumEltsChanged)
9917         return SDValue();
9918
9919       // Select the input vector, guarding against out of range extract vector.
9920       unsigned NumElems = VT.getVectorNumElements();
9921       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9922       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9923
9924       if (InVec.getOpcode() == ISD::BITCAST) {
9925         // Don't duplicate a load with other uses.
9926         if (!InVec.hasOneUse())
9927           return SDValue();
9928
9929         InVec = InVec.getOperand(0);
9930       }
9931       if (ISD::isNormalLoad(InVec.getNode())) {
9932         LN0 = cast<LoadSDNode>(InVec);
9933         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9934       }
9935     }
9936
9937     // Make sure we found a non-volatile load and the extractelement is
9938     // the only use.
9939     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9940       return SDValue();
9941
9942     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9943     if (Elt == -1)
9944       return DAG.getUNDEF(LVT);
9945
9946     unsigned Align = LN0->getAlignment();
9947     if (NewLoad) {
9948       // Check the resultant load doesn't need a higher alignment than the
9949       // original load.
9950       unsigned NewAlign =
9951         TLI.getDataLayout()
9952             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9953
9954       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9955         return SDValue();
9956
9957       Align = NewAlign;
9958     }
9959
9960     SDValue NewPtr = LN0->getBasePtr();
9961     unsigned PtrOff = 0;
9962
9963     if (Elt) {
9964       PtrOff = LVT.getSizeInBits() * Elt / 8;
9965       EVT PtrType = NewPtr.getValueType();
9966       if (TLI.isBigEndian())
9967         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9968       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9969                            DAG.getConstant(PtrOff, PtrType));
9970     }
9971
9972     // The replacement we need to do here is a little tricky: we need to
9973     // replace an extractelement of a load with a load.
9974     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9975     // Note that this replacement assumes that the extractvalue is the only
9976     // use of the load; that's okay because we don't want to perform this
9977     // transformation in other cases anyway.
9978     SDValue Load;
9979     SDValue Chain;
9980     if (NVT.bitsGT(LVT)) {
9981       // If the result type of vextract is wider than the load, then issue an
9982       // extending load instead.
9983       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9984         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9985       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9986                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9987                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9988                             Align, LN0->getTBAAInfo());
9989       Chain = Load.getValue(1);
9990     } else {
9991       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9992                          LN0->getPointerInfo().getWithOffset(PtrOff),
9993                          LN0->isVolatile(), LN0->isNonTemporal(),
9994                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9995       Chain = Load.getValue(1);
9996       if (NVT.bitsLT(LVT))
9997         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9998       else
9999         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10000     }
10001     WorkListRemover DeadNodes(*this);
10002     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10003     SDValue To[] = { Load, Chain };
10004     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10005     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10006     // worklist explicitly as well.
10007     AddToWorkList(Load.getNode());
10008     AddUsersToWorkList(Load.getNode()); // Add users too
10009     // Make sure to revisit this node to clean it up; it will usually be dead.
10010     AddToWorkList(N);
10011     return SDValue(N, 0);
10012   }
10013
10014   return SDValue();
10015 }
10016
10017 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10018 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10019   // We perform this optimization post type-legalization because
10020   // the type-legalizer often scalarizes integer-promoted vectors.
10021   // Performing this optimization before may create bit-casts which
10022   // will be type-legalized to complex code sequences.
10023   // We perform this optimization only before the operation legalizer because we
10024   // may introduce illegal operations.
10025   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10026     return SDValue();
10027
10028   unsigned NumInScalars = N->getNumOperands();
10029   SDLoc dl(N);
10030   EVT VT = N->getValueType(0);
10031
10032   // Check to see if this is a BUILD_VECTOR of a bunch of values
10033   // which come from any_extend or zero_extend nodes. If so, we can create
10034   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10035   // optimizations. We do not handle sign-extend because we can't fill the sign
10036   // using shuffles.
10037   EVT SourceType = MVT::Other;
10038   bool AllAnyExt = true;
10039
10040   for (unsigned i = 0; i != NumInScalars; ++i) {
10041     SDValue In = N->getOperand(i);
10042     // Ignore undef inputs.
10043     if (In.getOpcode() == ISD::UNDEF) continue;
10044
10045     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10046     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10047
10048     // Abort if the element is not an extension.
10049     if (!ZeroExt && !AnyExt) {
10050       SourceType = MVT::Other;
10051       break;
10052     }
10053
10054     // The input is a ZeroExt or AnyExt. Check the original type.
10055     EVT InTy = In.getOperand(0).getValueType();
10056
10057     // Check that all of the widened source types are the same.
10058     if (SourceType == MVT::Other)
10059       // First time.
10060       SourceType = InTy;
10061     else if (InTy != SourceType) {
10062       // Multiple income types. Abort.
10063       SourceType = MVT::Other;
10064       break;
10065     }
10066
10067     // Check if all of the extends are ANY_EXTENDs.
10068     AllAnyExt &= AnyExt;
10069   }
10070
10071   // In order to have valid types, all of the inputs must be extended from the
10072   // same source type and all of the inputs must be any or zero extend.
10073   // Scalar sizes must be a power of two.
10074   EVT OutScalarTy = VT.getScalarType();
10075   bool ValidTypes = SourceType != MVT::Other &&
10076                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10077                  isPowerOf2_32(SourceType.getSizeInBits());
10078
10079   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10080   // turn into a single shuffle instruction.
10081   if (!ValidTypes)
10082     return SDValue();
10083
10084   bool isLE = TLI.isLittleEndian();
10085   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10086   assert(ElemRatio > 1 && "Invalid element size ratio");
10087   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10088                                DAG.getConstant(0, SourceType);
10089
10090   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10091   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10092
10093   // Populate the new build_vector
10094   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10095     SDValue Cast = N->getOperand(i);
10096     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10097             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10098             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10099     SDValue In;
10100     if (Cast.getOpcode() == ISD::UNDEF)
10101       In = DAG.getUNDEF(SourceType);
10102     else
10103       In = Cast->getOperand(0);
10104     unsigned Index = isLE ? (i * ElemRatio) :
10105                             (i * ElemRatio + (ElemRatio - 1));
10106
10107     assert(Index < Ops.size() && "Invalid index");
10108     Ops[Index] = In;
10109   }
10110
10111   // The type of the new BUILD_VECTOR node.
10112   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10113   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10114          "Invalid vector size");
10115   // Check if the new vector type is legal.
10116   if (!isTypeLegal(VecVT)) return SDValue();
10117
10118   // Make the new BUILD_VECTOR.
10119   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10120
10121   // The new BUILD_VECTOR node has the potential to be further optimized.
10122   AddToWorkList(BV.getNode());
10123   // Bitcast to the desired type.
10124   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10125 }
10126
10127 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10128   EVT VT = N->getValueType(0);
10129
10130   unsigned NumInScalars = N->getNumOperands();
10131   SDLoc dl(N);
10132
10133   EVT SrcVT = MVT::Other;
10134   unsigned Opcode = ISD::DELETED_NODE;
10135   unsigned NumDefs = 0;
10136
10137   for (unsigned i = 0; i != NumInScalars; ++i) {
10138     SDValue In = N->getOperand(i);
10139     unsigned Opc = In.getOpcode();
10140
10141     if (Opc == ISD::UNDEF)
10142       continue;
10143
10144     // If all scalar values are floats and converted from integers.
10145     if (Opcode == ISD::DELETED_NODE &&
10146         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10147       Opcode = Opc;
10148     }
10149
10150     if (Opc != Opcode)
10151       return SDValue();
10152
10153     EVT InVT = In.getOperand(0).getValueType();
10154
10155     // If all scalar values are typed differently, bail out. It's chosen to
10156     // simplify BUILD_VECTOR of integer types.
10157     if (SrcVT == MVT::Other)
10158       SrcVT = InVT;
10159     if (SrcVT != InVT)
10160       return SDValue();
10161     NumDefs++;
10162   }
10163
10164   // If the vector has just one element defined, it's not worth to fold it into
10165   // a vectorized one.
10166   if (NumDefs < 2)
10167     return SDValue();
10168
10169   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10170          && "Should only handle conversion from integer to float.");
10171   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10172
10173   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10174
10175   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10176     return SDValue();
10177
10178   SmallVector<SDValue, 8> Opnds;
10179   for (unsigned i = 0; i != NumInScalars; ++i) {
10180     SDValue In = N->getOperand(i);
10181
10182     if (In.getOpcode() == ISD::UNDEF)
10183       Opnds.push_back(DAG.getUNDEF(SrcVT));
10184     else
10185       Opnds.push_back(In.getOperand(0));
10186   }
10187   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10188   AddToWorkList(BV.getNode());
10189
10190   return DAG.getNode(Opcode, dl, VT, BV);
10191 }
10192
10193 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10194   unsigned NumInScalars = N->getNumOperands();
10195   SDLoc dl(N);
10196   EVT VT = N->getValueType(0);
10197
10198   // A vector built entirely of undefs is undef.
10199   if (ISD::allOperandsUndef(N))
10200     return DAG.getUNDEF(VT);
10201
10202   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10203   if (V.getNode())
10204     return V;
10205
10206   V = reduceBuildVecConvertToConvertBuildVec(N);
10207   if (V.getNode())
10208     return V;
10209
10210   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10211   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10212   // at most two distinct vectors, turn this into a shuffle node.
10213
10214   // May only combine to shuffle after legalize if shuffle is legal.
10215   if (LegalOperations &&
10216       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10217     return SDValue();
10218
10219   SDValue VecIn1, VecIn2;
10220   for (unsigned i = 0; i != NumInScalars; ++i) {
10221     // Ignore undef inputs.
10222     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10223
10224     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10225     // constant index, bail out.
10226     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10227         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10228       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10229       break;
10230     }
10231
10232     // We allow up to two distinct input vectors.
10233     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10234     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10235       continue;
10236
10237     if (!VecIn1.getNode()) {
10238       VecIn1 = ExtractedFromVec;
10239     } else if (!VecIn2.getNode()) {
10240       VecIn2 = ExtractedFromVec;
10241     } else {
10242       // Too many inputs.
10243       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10244       break;
10245     }
10246   }
10247
10248   // If everything is good, we can make a shuffle operation.
10249   if (VecIn1.getNode()) {
10250     SmallVector<int, 8> Mask;
10251     for (unsigned i = 0; i != NumInScalars; ++i) {
10252       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10253         Mask.push_back(-1);
10254         continue;
10255       }
10256
10257       // If extracting from the first vector, just use the index directly.
10258       SDValue Extract = N->getOperand(i);
10259       SDValue ExtVal = Extract.getOperand(1);
10260       if (Extract.getOperand(0) == VecIn1) {
10261         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10262         if (ExtIndex > VT.getVectorNumElements())
10263           return SDValue();
10264
10265         Mask.push_back(ExtIndex);
10266         continue;
10267       }
10268
10269       // Otherwise, use InIdx + VecSize
10270       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10271       Mask.push_back(Idx+NumInScalars);
10272     }
10273
10274     // We can't generate a shuffle node with mismatched input and output types.
10275     // Attempt to transform a single input vector to the correct type.
10276     if ((VT != VecIn1.getValueType())) {
10277       // We don't support shuffeling between TWO values of different types.
10278       if (VecIn2.getNode())
10279         return SDValue();
10280
10281       // We only support widening of vectors which are half the size of the
10282       // output registers. For example XMM->YMM widening on X86 with AVX.
10283       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10284         return SDValue();
10285
10286       // If the input vector type has a different base type to the output
10287       // vector type, bail out.
10288       if (VecIn1.getValueType().getVectorElementType() !=
10289           VT.getVectorElementType())
10290         return SDValue();
10291
10292       // Widen the input vector by adding undef values.
10293       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10294                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10295     }
10296
10297     // If VecIn2 is unused then change it to undef.
10298     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10299
10300     // Check that we were able to transform all incoming values to the same
10301     // type.
10302     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10303         VecIn1.getValueType() != VT)
10304           return SDValue();
10305
10306     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10307     if (!isTypeLegal(VT))
10308       return SDValue();
10309
10310     // Return the new VECTOR_SHUFFLE node.
10311     SDValue Ops[2];
10312     Ops[0] = VecIn1;
10313     Ops[1] = VecIn2;
10314     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10315   }
10316
10317   return SDValue();
10318 }
10319
10320 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10321   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10322   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10323   // inputs come from at most two distinct vectors, turn this into a shuffle
10324   // node.
10325
10326   // If we only have one input vector, we don't need to do any concatenation.
10327   if (N->getNumOperands() == 1)
10328     return N->getOperand(0);
10329
10330   // Check if all of the operands are undefs.
10331   EVT VT = N->getValueType(0);
10332   if (ISD::allOperandsUndef(N))
10333     return DAG.getUNDEF(VT);
10334
10335   // Optimize concat_vectors where one of the vectors is undef.
10336   if (N->getNumOperands() == 2 &&
10337       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10338     SDValue In = N->getOperand(0);
10339     assert(In.getValueType().isVector() && "Must concat vectors");
10340
10341     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10342     if (In->getOpcode() == ISD::BITCAST &&
10343         !In->getOperand(0)->getValueType(0).isVector()) {
10344       SDValue Scalar = In->getOperand(0);
10345       EVT SclTy = Scalar->getValueType(0);
10346
10347       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10348         return SDValue();
10349
10350       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10351                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10352       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10353         return SDValue();
10354
10355       SDLoc dl = SDLoc(N);
10356       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10357       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10358     }
10359   }
10360
10361   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10362   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10363   if (N->getNumOperands() == 2 &&
10364       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10365       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10366     EVT VT = N->getValueType(0);
10367     SDValue N0 = N->getOperand(0);
10368     SDValue N1 = N->getOperand(1);
10369     SmallVector<SDValue, 8> Opnds;
10370     unsigned BuildVecNumElts =  N0.getNumOperands();
10371
10372     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10373     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10374     if (SclTy0.isFloatingPoint()) {
10375       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10376         Opnds.push_back(N0.getOperand(i));
10377       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10378         Opnds.push_back(N1.getOperand(i));
10379     } else {
10380       // If BUILD_VECTOR are from built from integer, they may have different
10381       // operand types. Get the smaller type and truncate all operands to it.
10382       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10383       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10384         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10385                         N0.getOperand(i)));
10386       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10387         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10388                         N1.getOperand(i)));
10389     }
10390
10391     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10392   }
10393
10394   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10395   // nodes often generate nop CONCAT_VECTOR nodes.
10396   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10397   // place the incoming vectors at the exact same location.
10398   SDValue SingleSource = SDValue();
10399   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10400
10401   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10402     SDValue Op = N->getOperand(i);
10403
10404     if (Op.getOpcode() == ISD::UNDEF)
10405       continue;
10406
10407     // Check if this is the identity extract:
10408     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10409       return SDValue();
10410
10411     // Find the single incoming vector for the extract_subvector.
10412     if (SingleSource.getNode()) {
10413       if (Op.getOperand(0) != SingleSource)
10414         return SDValue();
10415     } else {
10416       SingleSource = Op.getOperand(0);
10417
10418       // Check the source type is the same as the type of the result.
10419       // If not, this concat may extend the vector, so we can not
10420       // optimize it away.
10421       if (SingleSource.getValueType() != N->getValueType(0))
10422         return SDValue();
10423     }
10424
10425     unsigned IdentityIndex = i * PartNumElem;
10426     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10427     // The extract index must be constant.
10428     if (!CS)
10429       return SDValue();
10430
10431     // Check that we are reading from the identity index.
10432     if (CS->getZExtValue() != IdentityIndex)
10433       return SDValue();
10434   }
10435
10436   if (SingleSource.getNode())
10437     return SingleSource;
10438
10439   return SDValue();
10440 }
10441
10442 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10443   EVT NVT = N->getValueType(0);
10444   SDValue V = N->getOperand(0);
10445
10446   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10447     // Combine:
10448     //    (extract_subvec (concat V1, V2, ...), i)
10449     // Into:
10450     //    Vi if possible
10451     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10452     // type.
10453     if (V->getOperand(0).getValueType() != NVT)
10454       return SDValue();
10455     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10456     unsigned NumElems = NVT.getVectorNumElements();
10457     assert((Idx % NumElems) == 0 &&
10458            "IDX in concat is not a multiple of the result vector length.");
10459     return V->getOperand(Idx / NumElems);
10460   }
10461
10462   // Skip bitcasting
10463   if (V->getOpcode() == ISD::BITCAST)
10464     V = V.getOperand(0);
10465
10466   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10467     SDLoc dl(N);
10468     // Handle only simple case where vector being inserted and vector
10469     // being extracted are of same type, and are half size of larger vectors.
10470     EVT BigVT = V->getOperand(0).getValueType();
10471     EVT SmallVT = V->getOperand(1).getValueType();
10472     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10473       return SDValue();
10474
10475     // Only handle cases where both indexes are constants with the same type.
10476     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10477     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10478
10479     if (InsIdx && ExtIdx &&
10480         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10481         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10482       // Combine:
10483       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10484       // Into:
10485       //    indices are equal or bit offsets are equal => V1
10486       //    otherwise => (extract_subvec V1, ExtIdx)
10487       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10488           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10489         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10490       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10491                          DAG.getNode(ISD::BITCAST, dl,
10492                                      N->getOperand(0).getValueType(),
10493                                      V->getOperand(0)), N->getOperand(1));
10494     }
10495   }
10496
10497   return SDValue();
10498 }
10499
10500 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10501 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10502   EVT VT = N->getValueType(0);
10503   unsigned NumElts = VT.getVectorNumElements();
10504
10505   SDValue N0 = N->getOperand(0);
10506   SDValue N1 = N->getOperand(1);
10507   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10508
10509   SmallVector<SDValue, 4> Ops;
10510   EVT ConcatVT = N0.getOperand(0).getValueType();
10511   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10512   unsigned NumConcats = NumElts / NumElemsPerConcat;
10513
10514   // Look at every vector that's inserted. We're looking for exact
10515   // subvector-sized copies from a concatenated vector
10516   for (unsigned I = 0; I != NumConcats; ++I) {
10517     // Make sure we're dealing with a copy.
10518     unsigned Begin = I * NumElemsPerConcat;
10519     bool AllUndef = true, NoUndef = true;
10520     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10521       if (SVN->getMaskElt(J) >= 0)
10522         AllUndef = false;
10523       else
10524         NoUndef = false;
10525     }
10526
10527     if (NoUndef) {
10528       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10529         return SDValue();
10530
10531       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10532         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10533           return SDValue();
10534
10535       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10536       if (FirstElt < N0.getNumOperands())
10537         Ops.push_back(N0.getOperand(FirstElt));
10538       else
10539         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10540
10541     } else if (AllUndef) {
10542       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10543     } else { // Mixed with general masks and undefs, can't do optimization.
10544       return SDValue();
10545     }
10546   }
10547
10548   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10549 }
10550
10551 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10552   EVT VT = N->getValueType(0);
10553   unsigned NumElts = VT.getVectorNumElements();
10554
10555   SDValue N0 = N->getOperand(0);
10556   SDValue N1 = N->getOperand(1);
10557
10558   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10559
10560   // Canonicalize shuffle undef, undef -> undef
10561   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10562     return DAG.getUNDEF(VT);
10563
10564   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10565
10566   // Canonicalize shuffle v, v -> v, undef
10567   if (N0 == N1) {
10568     SmallVector<int, 8> NewMask;
10569     for (unsigned i = 0; i != NumElts; ++i) {
10570       int Idx = SVN->getMaskElt(i);
10571       if (Idx >= (int)NumElts) Idx -= NumElts;
10572       NewMask.push_back(Idx);
10573     }
10574     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10575                                 &NewMask[0]);
10576   }
10577
10578   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10579   if (N0.getOpcode() == ISD::UNDEF) {
10580     SmallVector<int, 8> NewMask;
10581     for (unsigned i = 0; i != NumElts; ++i) {
10582       int Idx = SVN->getMaskElt(i);
10583       if (Idx >= 0) {
10584         if (Idx >= (int)NumElts)
10585           Idx -= NumElts;
10586         else
10587           Idx = -1; // remove reference to lhs
10588       }
10589       NewMask.push_back(Idx);
10590     }
10591     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10592                                 &NewMask[0]);
10593   }
10594
10595   // Remove references to rhs if it is undef
10596   if (N1.getOpcode() == ISD::UNDEF) {
10597     bool Changed = false;
10598     SmallVector<int, 8> NewMask;
10599     for (unsigned i = 0; i != NumElts; ++i) {
10600       int Idx = SVN->getMaskElt(i);
10601       if (Idx >= (int)NumElts) {
10602         Idx = -1;
10603         Changed = true;
10604       }
10605       NewMask.push_back(Idx);
10606     }
10607     if (Changed)
10608       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10609   }
10610
10611   // If it is a splat, check if the argument vector is another splat or a
10612   // build_vector with all scalar elements the same.
10613   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10614     SDNode *V = N0.getNode();
10615
10616     // If this is a bit convert that changes the element type of the vector but
10617     // not the number of vector elements, look through it.  Be careful not to
10618     // look though conversions that change things like v4f32 to v2f64.
10619     if (V->getOpcode() == ISD::BITCAST) {
10620       SDValue ConvInput = V->getOperand(0);
10621       if (ConvInput.getValueType().isVector() &&
10622           ConvInput.getValueType().getVectorNumElements() == NumElts)
10623         V = ConvInput.getNode();
10624     }
10625
10626     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10627       assert(V->getNumOperands() == NumElts &&
10628              "BUILD_VECTOR has wrong number of operands");
10629       SDValue Base;
10630       bool AllSame = true;
10631       for (unsigned i = 0; i != NumElts; ++i) {
10632         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10633           Base = V->getOperand(i);
10634           break;
10635         }
10636       }
10637       // Splat of <u, u, u, u>, return <u, u, u, u>
10638       if (!Base.getNode())
10639         return N0;
10640       for (unsigned i = 0; i != NumElts; ++i) {
10641         if (V->getOperand(i) != Base) {
10642           AllSame = false;
10643           break;
10644         }
10645       }
10646       // Splat of <x, x, x, x>, return <x, x, x, x>
10647       if (AllSame)
10648         return N0;
10649     }
10650   }
10651
10652   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10653       Level < AfterLegalizeVectorOps &&
10654       (N1.getOpcode() == ISD::UNDEF ||
10655       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10656        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10657     SDValue V = partitionShuffleOfConcats(N, DAG);
10658
10659     if (V.getNode())
10660       return V;
10661   }
10662
10663   // If this shuffle node is simply a swizzle of another shuffle node,
10664   // then try to simplify it.
10665   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10666       N1.getOpcode() == ISD::UNDEF) {
10667
10668     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10669
10670     // The incoming shuffle must be of the same type as the result of the
10671     // current shuffle.
10672     assert(OtherSV->getOperand(0).getValueType() == VT &&
10673            "Shuffle types don't match");
10674
10675     SmallVector<int, 4> Mask;
10676     // Compute the combined shuffle mask.
10677     for (unsigned i = 0; i != NumElts; ++i) {
10678       int Idx = SVN->getMaskElt(i);
10679       assert(Idx < (int)NumElts && "Index references undef operand");
10680       // Next, this index comes from the first value, which is the incoming
10681       // shuffle. Adopt the incoming index.
10682       if (Idx >= 0)
10683         Idx = OtherSV->getMaskElt(Idx);
10684       Mask.push_back(Idx);
10685     }
10686     
10687     bool CommuteOperands = false;
10688     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10689       // To be valid, the combine shuffle mask should only reference elements
10690       // from one of the two vectors in input to the inner shufflevector.
10691       bool IsValidMask = true;
10692       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10693         // See if the combined mask only reference undefs or elements coming
10694         // from the first shufflevector operand.
10695         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10696
10697       if (!IsValidMask) {
10698         IsValidMask = true;
10699         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10700           // Check that all the elements come from the second shuffle operand.
10701           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10702         CommuteOperands = IsValidMask;
10703       }
10704
10705       // Early exit if the combined shuffle mask is not valid.
10706       if (!IsValidMask)
10707         return SDValue();
10708     }
10709
10710     // See if this pair of shuffles can be safely folded according to either
10711     // of the following rules:
10712     //   shuffle(shuffle(x, y), undef) -> x
10713     //   shuffle(shuffle(x, undef), undef) -> x
10714     //   shuffle(shuffle(x, y), undef) -> y
10715     bool IsIdentityMask = true;
10716     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10717     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10718       // Skip Undefs.
10719       if (Mask[i] < 0)
10720         continue;
10721
10722       // The combined shuffle must map each index to itself.
10723       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10724     }
10725     
10726     if (IsIdentityMask) {
10727       if (CommuteOperands)
10728         // optimize shuffle(shuffle(x, y), undef) -> y.
10729         return OtherSV->getOperand(1);
10730       
10731       // optimize shuffle(shuffle(x, undef), undef) -> x
10732       // optimize shuffle(shuffle(x, y), undef) -> x
10733       return OtherSV->getOperand(0);
10734     }
10735
10736     // It may still be beneficial to combine the two shuffles if the
10737     // resulting shuffle is legal.
10738     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10739       if (!CommuteOperands)
10740         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10741         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10742         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10743                                     &Mask[0]);
10744       
10745       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10746       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10747                                   &Mask[0]);
10748     }
10749   }
10750
10751   // Canonicalize shuffles according to rules:
10752   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10753   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10754   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10755   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10756       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10757       TLI.isTypeLegal(VT)) {
10758     // The incoming shuffle must be of the same type as the result of the
10759     // current shuffle.
10760     assert(N1->getOperand(0).getValueType() == VT &&
10761            "Shuffle types don't match");
10762
10763     SDValue SV0 = N1->getOperand(0);
10764     SDValue SV1 = N1->getOperand(1);
10765     bool HasSameOp0 = N0 == SV0;
10766     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10767     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10768       // Commute the operands of this shuffle so that next rule
10769       // will trigger.
10770       return DAG.getCommutedVectorShuffle(*SVN);
10771   }
10772
10773   // Try to fold according to rules:
10774   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10775   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10776   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10777   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10778   // Don't try to fold shuffles with illegal type.
10779   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10780       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10781     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10782
10783     // The incoming shuffle must be of the same type as the result of the
10784     // current shuffle.
10785     assert(OtherSV->getOperand(0).getValueType() == VT &&
10786            "Shuffle types don't match");
10787
10788     SDValue SV0 = OtherSV->getOperand(0);
10789     SDValue SV1 = OtherSV->getOperand(1);
10790     bool HasSameOp0 = N1 == SV0;
10791     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10792     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10793       // Early exit.
10794       return SDValue();
10795
10796     SmallVector<int, 4> Mask;
10797     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10798     // operand, and SV1 as the second operand.
10799     for (unsigned i = 0; i != NumElts; ++i) {
10800       int Idx = SVN->getMaskElt(i);
10801       if (Idx < 0) {
10802         // Propagate Undef.
10803         Mask.push_back(Idx);
10804         continue;
10805       }
10806
10807       if (Idx < (int)NumElts) {
10808         Idx = OtherSV->getMaskElt(Idx);
10809         if (IsSV1Undef && Idx >= (int) NumElts)
10810           Idx = -1;  // Propagate Undef.
10811       } else
10812         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10813
10814       Mask.push_back(Idx);
10815     }
10816
10817     // Avoid introducing shuffles with illegal mask.
10818     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10819       if (IsSV1Undef)
10820         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10821         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10822         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10823       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10824     }
10825   }
10826
10827   return SDValue();
10828 }
10829
10830 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10831   SDValue N0 = N->getOperand(0);
10832   SDValue N2 = N->getOperand(2);
10833
10834   // If the input vector is a concatenation, and the insert replaces
10835   // one of the halves, we can optimize into a single concat_vectors.
10836   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10837       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10838     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10839     EVT VT = N->getValueType(0);
10840
10841     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10842     // (concat_vectors Z, Y)
10843     if (InsIdx == 0)
10844       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10845                          N->getOperand(1), N0.getOperand(1));
10846
10847     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10848     // (concat_vectors X, Z)
10849     if (InsIdx == VT.getVectorNumElements()/2)
10850       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10851                          N0.getOperand(0), N->getOperand(1));
10852   }
10853
10854   return SDValue();
10855 }
10856
10857 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10858 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10859 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10860 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10861 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10862   EVT VT = N->getValueType(0);
10863   SDLoc dl(N);
10864   SDValue LHS = N->getOperand(0);
10865   SDValue RHS = N->getOperand(1);
10866   if (N->getOpcode() == ISD::AND) {
10867     if (RHS.getOpcode() == ISD::BITCAST)
10868       RHS = RHS.getOperand(0);
10869     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10870       SmallVector<int, 8> Indices;
10871       unsigned NumElts = RHS.getNumOperands();
10872       for (unsigned i = 0; i != NumElts; ++i) {
10873         SDValue Elt = RHS.getOperand(i);
10874         if (!isa<ConstantSDNode>(Elt))
10875           return SDValue();
10876
10877         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10878           Indices.push_back(i);
10879         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10880           Indices.push_back(NumElts);
10881         else
10882           return SDValue();
10883       }
10884
10885       // Let's see if the target supports this vector_shuffle.
10886       EVT RVT = RHS.getValueType();
10887       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10888         return SDValue();
10889
10890       // Return the new VECTOR_SHUFFLE node.
10891       EVT EltVT = RVT.getVectorElementType();
10892       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10893                                      DAG.getConstant(0, EltVT));
10894       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10895       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10896       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10897       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10898     }
10899   }
10900
10901   return SDValue();
10902 }
10903
10904 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10905 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10906   assert(N->getValueType(0).isVector() &&
10907          "SimplifyVBinOp only works on vectors!");
10908
10909   SDValue LHS = N->getOperand(0);
10910   SDValue RHS = N->getOperand(1);
10911   SDValue Shuffle = XformToShuffleWithZero(N);
10912   if (Shuffle.getNode()) return Shuffle;
10913
10914   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10915   // this operation.
10916   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10917       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10918     // Check if both vectors are constants. If not bail out.
10919     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10920           cast<BuildVectorSDNode>(RHS)->isConstant()))
10921       return SDValue();
10922
10923     SmallVector<SDValue, 8> Ops;
10924     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10925       SDValue LHSOp = LHS.getOperand(i);
10926       SDValue RHSOp = RHS.getOperand(i);
10927
10928       // Can't fold divide by zero.
10929       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10930           N->getOpcode() == ISD::FDIV) {
10931         if ((RHSOp.getOpcode() == ISD::Constant &&
10932              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10933             (RHSOp.getOpcode() == ISD::ConstantFP &&
10934              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10935           break;
10936       }
10937
10938       EVT VT = LHSOp.getValueType();
10939       EVT RVT = RHSOp.getValueType();
10940       if (RVT != VT) {
10941         // Integer BUILD_VECTOR operands may have types larger than the element
10942         // size (e.g., when the element type is not legal).  Prior to type
10943         // legalization, the types may not match between the two BUILD_VECTORS.
10944         // Truncate one of the operands to make them match.
10945         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10946           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10947         } else {
10948           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10949           VT = RVT;
10950         }
10951       }
10952       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10953                                    LHSOp, RHSOp);
10954       if (FoldOp.getOpcode() != ISD::UNDEF &&
10955           FoldOp.getOpcode() != ISD::Constant &&
10956           FoldOp.getOpcode() != ISD::ConstantFP)
10957         break;
10958       Ops.push_back(FoldOp);
10959       AddToWorkList(FoldOp.getNode());
10960     }
10961
10962     if (Ops.size() == LHS.getNumOperands())
10963       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
10964   }
10965
10966   // Type legalization might introduce new shuffles in the DAG.
10967   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
10968   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
10969   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
10970       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
10971       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
10972       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
10973     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
10974     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
10975
10976     if (SVN0->getMask().equals(SVN1->getMask())) {
10977       EVT VT = N->getValueType(0);
10978       SDValue UndefVector = LHS.getOperand(1);
10979       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
10980                                      LHS.getOperand(0), RHS.getOperand(0));
10981       AddUsersToWorkList(N);
10982       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
10983                                   &SVN0->getMask()[0]);
10984     }
10985   }
10986
10987   return SDValue();
10988 }
10989
10990 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10991 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10992   assert(N->getValueType(0).isVector() &&
10993          "SimplifyVUnaryOp only works on vectors!");
10994
10995   SDValue N0 = N->getOperand(0);
10996
10997   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10998     return SDValue();
10999
11000   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11001   SmallVector<SDValue, 8> Ops;
11002   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11003     SDValue Op = N0.getOperand(i);
11004     if (Op.getOpcode() != ISD::UNDEF &&
11005         Op.getOpcode() != ISD::ConstantFP)
11006       break;
11007     EVT EltVT = Op.getValueType();
11008     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11009     if (FoldOp.getOpcode() != ISD::UNDEF &&
11010         FoldOp.getOpcode() != ISD::ConstantFP)
11011       break;
11012     Ops.push_back(FoldOp);
11013     AddToWorkList(FoldOp.getNode());
11014   }
11015
11016   if (Ops.size() != N0.getNumOperands())
11017     return SDValue();
11018
11019   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11020 }
11021
11022 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11023                                     SDValue N1, SDValue N2){
11024   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11025
11026   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11027                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11028
11029   // If we got a simplified select_cc node back from SimplifySelectCC, then
11030   // break it down into a new SETCC node, and a new SELECT node, and then return
11031   // the SELECT node, since we were called with a SELECT node.
11032   if (SCC.getNode()) {
11033     // Check to see if we got a select_cc back (to turn into setcc/select).
11034     // Otherwise, just return whatever node we got back, like fabs.
11035     if (SCC.getOpcode() == ISD::SELECT_CC) {
11036       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11037                                   N0.getValueType(),
11038                                   SCC.getOperand(0), SCC.getOperand(1),
11039                                   SCC.getOperand(4));
11040       AddToWorkList(SETCC.getNode());
11041       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11042                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11043     }
11044
11045     return SCC;
11046   }
11047   return SDValue();
11048 }
11049
11050 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11051 /// are the two values being selected between, see if we can simplify the
11052 /// select.  Callers of this should assume that TheSelect is deleted if this
11053 /// returns true.  As such, they should return the appropriate thing (e.g. the
11054 /// node) back to the top-level of the DAG combiner loop to avoid it being
11055 /// looked at.
11056 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11057                                     SDValue RHS) {
11058
11059   // Cannot simplify select with vector condition
11060   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11061
11062   // If this is a select from two identical things, try to pull the operation
11063   // through the select.
11064   if (LHS.getOpcode() != RHS.getOpcode() ||
11065       !LHS.hasOneUse() || !RHS.hasOneUse())
11066     return false;
11067
11068   // If this is a load and the token chain is identical, replace the select
11069   // of two loads with a load through a select of the address to load from.
11070   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11071   // constants have been dropped into the constant pool.
11072   if (LHS.getOpcode() == ISD::LOAD) {
11073     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11074     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11075
11076     // Token chains must be identical.
11077     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11078         // Do not let this transformation reduce the number of volatile loads.
11079         LLD->isVolatile() || RLD->isVolatile() ||
11080         // If this is an EXTLOAD, the VT's must match.
11081         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11082         // If this is an EXTLOAD, the kind of extension must match.
11083         (LLD->getExtensionType() != RLD->getExtensionType() &&
11084          // The only exception is if one of the extensions is anyext.
11085          LLD->getExtensionType() != ISD::EXTLOAD &&
11086          RLD->getExtensionType() != ISD::EXTLOAD) ||
11087         // FIXME: this discards src value information.  This is
11088         // over-conservative. It would be beneficial to be able to remember
11089         // both potential memory locations.  Since we are discarding
11090         // src value info, don't do the transformation if the memory
11091         // locations are not in the default address space.
11092         LLD->getPointerInfo().getAddrSpace() != 0 ||
11093         RLD->getPointerInfo().getAddrSpace() != 0 ||
11094         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11095                                       LLD->getBasePtr().getValueType()))
11096       return false;
11097
11098     // Check that the select condition doesn't reach either load.  If so,
11099     // folding this will induce a cycle into the DAG.  If not, this is safe to
11100     // xform, so create a select of the addresses.
11101     SDValue Addr;
11102     if (TheSelect->getOpcode() == ISD::SELECT) {
11103       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11104       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11105           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11106         return false;
11107       // The loads must not depend on one another.
11108       if (LLD->isPredecessorOf(RLD) ||
11109           RLD->isPredecessorOf(LLD))
11110         return false;
11111       Addr = DAG.getSelect(SDLoc(TheSelect),
11112                            LLD->getBasePtr().getValueType(),
11113                            TheSelect->getOperand(0), LLD->getBasePtr(),
11114                            RLD->getBasePtr());
11115     } else {  // Otherwise SELECT_CC
11116       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11117       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11118
11119       if ((LLD->hasAnyUseOfValue(1) &&
11120            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11121           (RLD->hasAnyUseOfValue(1) &&
11122            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11123         return false;
11124
11125       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11126                          LLD->getBasePtr().getValueType(),
11127                          TheSelect->getOperand(0),
11128                          TheSelect->getOperand(1),
11129                          LLD->getBasePtr(), RLD->getBasePtr(),
11130                          TheSelect->getOperand(4));
11131     }
11132
11133     SDValue Load;
11134     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11135       Load = DAG.getLoad(TheSelect->getValueType(0),
11136                          SDLoc(TheSelect),
11137                          // FIXME: Discards pointer and TBAA info.
11138                          LLD->getChain(), Addr, MachinePointerInfo(),
11139                          LLD->isVolatile(), LLD->isNonTemporal(),
11140                          LLD->isInvariant(), LLD->getAlignment());
11141     } else {
11142       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11143                             RLD->getExtensionType() : LLD->getExtensionType(),
11144                             SDLoc(TheSelect),
11145                             TheSelect->getValueType(0),
11146                             // FIXME: Discards pointer and TBAA info.
11147                             LLD->getChain(), Addr, MachinePointerInfo(),
11148                             LLD->getMemoryVT(), LLD->isVolatile(),
11149                             LLD->isNonTemporal(), LLD->getAlignment());
11150     }
11151
11152     // Users of the select now use the result of the load.
11153     CombineTo(TheSelect, Load);
11154
11155     // Users of the old loads now use the new load's chain.  We know the
11156     // old-load value is dead now.
11157     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11158     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11159     return true;
11160   }
11161
11162   return false;
11163 }
11164
11165 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11166 /// where 'cond' is the comparison specified by CC.
11167 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11168                                       SDValue N2, SDValue N3,
11169                                       ISD::CondCode CC, bool NotExtCompare) {
11170   // (x ? y : y) -> y.
11171   if (N2 == N3) return N2;
11172
11173   EVT VT = N2.getValueType();
11174   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11175   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11176   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11177
11178   // Determine if the condition we're dealing with is constant
11179   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11180                               N0, N1, CC, DL, false);
11181   if (SCC.getNode()) AddToWorkList(SCC.getNode());
11182   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11183
11184   // fold select_cc true, x, y -> x
11185   if (SCCC && !SCCC->isNullValue())
11186     return N2;
11187   // fold select_cc false, x, y -> y
11188   if (SCCC && SCCC->isNullValue())
11189     return N3;
11190
11191   // Check to see if we can simplify the select into an fabs node
11192   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11193     // Allow either -0.0 or 0.0
11194     if (CFP->getValueAPF().isZero()) {
11195       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11196       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11197           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11198           N2 == N3.getOperand(0))
11199         return DAG.getNode(ISD::FABS, DL, VT, N0);
11200
11201       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11202       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11203           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11204           N2.getOperand(0) == N3)
11205         return DAG.getNode(ISD::FABS, DL, VT, N3);
11206     }
11207   }
11208
11209   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11210   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11211   // in it.  This is a win when the constant is not otherwise available because
11212   // it replaces two constant pool loads with one.  We only do this if the FP
11213   // type is known to be legal, because if it isn't, then we are before legalize
11214   // types an we want the other legalization to happen first (e.g. to avoid
11215   // messing with soft float) and if the ConstantFP is not legal, because if
11216   // it is legal, we may not need to store the FP constant in a constant pool.
11217   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11218     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11219       if (TLI.isTypeLegal(N2.getValueType()) &&
11220           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11221                TargetLowering::Legal &&
11222            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11223            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11224           // If both constants have multiple uses, then we won't need to do an
11225           // extra load, they are likely around in registers for other users.
11226           (TV->hasOneUse() || FV->hasOneUse())) {
11227         Constant *Elts[] = {
11228           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11229           const_cast<ConstantFP*>(TV->getConstantFPValue())
11230         };
11231         Type *FPTy = Elts[0]->getType();
11232         const DataLayout &TD = *TLI.getDataLayout();
11233
11234         // Create a ConstantArray of the two constants.
11235         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11236         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11237                                             TD.getPrefTypeAlignment(FPTy));
11238         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11239
11240         // Get the offsets to the 0 and 1 element of the array so that we can
11241         // select between them.
11242         SDValue Zero = DAG.getIntPtrConstant(0);
11243         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11244         SDValue One = DAG.getIntPtrConstant(EltSize);
11245
11246         SDValue Cond = DAG.getSetCC(DL,
11247                                     getSetCCResultType(N0.getValueType()),
11248                                     N0, N1, CC);
11249         AddToWorkList(Cond.getNode());
11250         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11251                                           Cond, One, Zero);
11252         AddToWorkList(CstOffset.getNode());
11253         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11254                             CstOffset);
11255         AddToWorkList(CPIdx.getNode());
11256         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11257                            MachinePointerInfo::getConstantPool(), false,
11258                            false, false, Alignment);
11259
11260       }
11261     }
11262
11263   // Check to see if we can perform the "gzip trick", transforming
11264   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11265   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11266       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11267        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11268     EVT XType = N0.getValueType();
11269     EVT AType = N2.getValueType();
11270     if (XType.bitsGE(AType)) {
11271       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11272       // single-bit constant.
11273       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11274         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11275         ShCtV = XType.getSizeInBits()-ShCtV-1;
11276         SDValue ShCt = DAG.getConstant(ShCtV,
11277                                        getShiftAmountTy(N0.getValueType()));
11278         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11279                                     XType, N0, ShCt);
11280         AddToWorkList(Shift.getNode());
11281
11282         if (XType.bitsGT(AType)) {
11283           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11284           AddToWorkList(Shift.getNode());
11285         }
11286
11287         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11288       }
11289
11290       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11291                                   XType, N0,
11292                                   DAG.getConstant(XType.getSizeInBits()-1,
11293                                          getShiftAmountTy(N0.getValueType())));
11294       AddToWorkList(Shift.getNode());
11295
11296       if (XType.bitsGT(AType)) {
11297         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11298         AddToWorkList(Shift.getNode());
11299       }
11300
11301       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11302     }
11303   }
11304
11305   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11306   // where y is has a single bit set.
11307   // A plaintext description would be, we can turn the SELECT_CC into an AND
11308   // when the condition can be materialized as an all-ones register.  Any
11309   // single bit-test can be materialized as an all-ones register with
11310   // shift-left and shift-right-arith.
11311   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11312       N0->getValueType(0) == VT &&
11313       N1C && N1C->isNullValue() &&
11314       N2C && N2C->isNullValue()) {
11315     SDValue AndLHS = N0->getOperand(0);
11316     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11317     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11318       // Shift the tested bit over the sign bit.
11319       APInt AndMask = ConstAndRHS->getAPIntValue();
11320       SDValue ShlAmt =
11321         DAG.getConstant(AndMask.countLeadingZeros(),
11322                         getShiftAmountTy(AndLHS.getValueType()));
11323       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11324
11325       // Now arithmetic right shift it all the way over, so the result is either
11326       // all-ones, or zero.
11327       SDValue ShrAmt =
11328         DAG.getConstant(AndMask.getBitWidth()-1,
11329                         getShiftAmountTy(Shl.getValueType()));
11330       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11331
11332       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11333     }
11334   }
11335
11336   // fold select C, 16, 0 -> shl C, 4
11337   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11338       TLI.getBooleanContents(N0.getValueType()) ==
11339           TargetLowering::ZeroOrOneBooleanContent) {
11340
11341     // If the caller doesn't want us to simplify this into a zext of a compare,
11342     // don't do it.
11343     if (NotExtCompare && N2C->getAPIntValue() == 1)
11344       return SDValue();
11345
11346     // Get a SetCC of the condition
11347     // NOTE: Don't create a SETCC if it's not legal on this target.
11348     if (!LegalOperations ||
11349         TLI.isOperationLegal(ISD::SETCC,
11350           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11351       SDValue Temp, SCC;
11352       // cast from setcc result type to select result type
11353       if (LegalTypes) {
11354         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11355                             N0, N1, CC);
11356         if (N2.getValueType().bitsLT(SCC.getValueType()))
11357           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11358                                         N2.getValueType());
11359         else
11360           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11361                              N2.getValueType(), SCC);
11362       } else {
11363         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11364         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11365                            N2.getValueType(), SCC);
11366       }
11367
11368       AddToWorkList(SCC.getNode());
11369       AddToWorkList(Temp.getNode());
11370
11371       if (N2C->getAPIntValue() == 1)
11372         return Temp;
11373
11374       // shl setcc result by log2 n2c
11375       return DAG.getNode(
11376           ISD::SHL, DL, N2.getValueType(), Temp,
11377           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11378                           getShiftAmountTy(Temp.getValueType())));
11379     }
11380   }
11381
11382   // Check to see if this is the equivalent of setcc
11383   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11384   // otherwise, go ahead with the folds.
11385   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11386     EVT XType = N0.getValueType();
11387     if (!LegalOperations ||
11388         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11389       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11390       if (Res.getValueType() != VT)
11391         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11392       return Res;
11393     }
11394
11395     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11396     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11397         (!LegalOperations ||
11398          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11399       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11400       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11401                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11402                                        getShiftAmountTy(Ctlz.getValueType())));
11403     }
11404     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11405     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11406       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11407                                   XType, DAG.getConstant(0, XType), N0);
11408       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11409       return DAG.getNode(ISD::SRL, DL, XType,
11410                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11411                          DAG.getConstant(XType.getSizeInBits()-1,
11412                                          getShiftAmountTy(XType)));
11413     }
11414     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11415     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11416       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11417                                  DAG.getConstant(XType.getSizeInBits()-1,
11418                                          getShiftAmountTy(N0.getValueType())));
11419       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11420     }
11421   }
11422
11423   // Check to see if this is an integer abs.
11424   // select_cc setg[te] X,  0,  X, -X ->
11425   // select_cc setgt    X, -1,  X, -X ->
11426   // select_cc setl[te] X,  0, -X,  X ->
11427   // select_cc setlt    X,  1, -X,  X ->
11428   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11429   if (N1C) {
11430     ConstantSDNode *SubC = nullptr;
11431     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11432          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11433         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11434       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11435     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11436               (N1C->isOne() && CC == ISD::SETLT)) &&
11437              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11438       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11439
11440     EVT XType = N0.getValueType();
11441     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11442       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11443                                   N0,
11444                                   DAG.getConstant(XType.getSizeInBits()-1,
11445                                          getShiftAmountTy(N0.getValueType())));
11446       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11447                                 XType, N0, Shift);
11448       AddToWorkList(Shift.getNode());
11449       AddToWorkList(Add.getNode());
11450       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11451     }
11452   }
11453
11454   return SDValue();
11455 }
11456
11457 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11458 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11459                                    SDValue N1, ISD::CondCode Cond,
11460                                    SDLoc DL, bool foldBooleans) {
11461   TargetLowering::DAGCombinerInfo
11462     DagCombineInfo(DAG, Level, false, this);
11463   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11464 }
11465
11466 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11467 /// return a DAG expression to select that will generate the same value by
11468 /// multiplying by a magic number.  See:
11469 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11470 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11471   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11472   if (!C)
11473     return SDValue();
11474
11475   // Avoid division by zero.
11476   if (!C->getAPIntValue())
11477     return SDValue();
11478
11479   std::vector<SDNode*> Built;
11480   SDValue S =
11481       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11482
11483   for (SDNode *N : Built)
11484     AddToWorkList(N);
11485   return S;
11486 }
11487
11488 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11489 /// return a DAG expression to select that will generate the same value by
11490 /// multiplying by a magic number.  See:
11491 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11492 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11493   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11494   if (!C)
11495     return SDValue();
11496
11497   // Avoid division by zero.
11498   if (!C->getAPIntValue())
11499     return SDValue();
11500
11501   std::vector<SDNode*> Built;
11502   SDValue S =
11503       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11504
11505   for (SDNode *N : Built)
11506     AddToWorkList(N);
11507   return S;
11508 }
11509
11510 /// FindBaseOffset - Return true if base is a frame index, which is known not
11511 // to alias with anything but itself.  Provides base object and offset as
11512 // results.
11513 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11514                            const GlobalValue *&GV, const void *&CV) {
11515   // Assume it is a primitive operation.
11516   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11517
11518   // If it's an adding a simple constant then integrate the offset.
11519   if (Base.getOpcode() == ISD::ADD) {
11520     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11521       Base = Base.getOperand(0);
11522       Offset += C->getZExtValue();
11523     }
11524   }
11525
11526   // Return the underlying GlobalValue, and update the Offset.  Return false
11527   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11528   // by multiple nodes with different offsets.
11529   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11530     GV = G->getGlobal();
11531     Offset += G->getOffset();
11532     return false;
11533   }
11534
11535   // Return the underlying Constant value, and update the Offset.  Return false
11536   // for ConstantSDNodes since the same constant pool entry may be represented
11537   // by multiple nodes with different offsets.
11538   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11539     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11540                                          : (const void *)C->getConstVal();
11541     Offset += C->getOffset();
11542     return false;
11543   }
11544   // If it's any of the following then it can't alias with anything but itself.
11545   return isa<FrameIndexSDNode>(Base);
11546 }
11547
11548 /// isAlias - Return true if there is any possibility that the two addresses
11549 /// overlap.
11550 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11551   // If they are the same then they must be aliases.
11552   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11553
11554   // If they are both volatile then they cannot be reordered.
11555   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11556
11557   // Gather base node and offset information.
11558   SDValue Base1, Base2;
11559   int64_t Offset1, Offset2;
11560   const GlobalValue *GV1, *GV2;
11561   const void *CV1, *CV2;
11562   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11563                                       Base1, Offset1, GV1, CV1);
11564   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11565                                       Base2, Offset2, GV2, CV2);
11566
11567   // If they have a same base address then check to see if they overlap.
11568   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11569     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11570              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11571
11572   // It is possible for different frame indices to alias each other, mostly
11573   // when tail call optimization reuses return address slots for arguments.
11574   // To catch this case, look up the actual index of frame indices to compute
11575   // the real alias relationship.
11576   if (isFrameIndex1 && isFrameIndex2) {
11577     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11578     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11579     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11580     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11581              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11582   }
11583
11584   // Otherwise, if we know what the bases are, and they aren't identical, then
11585   // we know they cannot alias.
11586   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11587     return false;
11588
11589   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11590   // compared to the size and offset of the access, we may be able to prove they
11591   // do not alias.  This check is conservative for now to catch cases created by
11592   // splitting vector types.
11593   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11594       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11595       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11596        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11597       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11598     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11599     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11600
11601     // There is no overlap between these relatively aligned accesses of similar
11602     // size, return no alias.
11603     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11604         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11605       return false;
11606   }
11607
11608   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11609     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11610 #ifndef NDEBUG
11611   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11612       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11613     UseAA = false;
11614 #endif
11615   if (UseAA &&
11616       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11617     // Use alias analysis information.
11618     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11619                                  Op1->getSrcValueOffset());
11620     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11621         Op0->getSrcValueOffset() - MinOffset;
11622     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11623         Op1->getSrcValueOffset() - MinOffset;
11624     AliasAnalysis::AliasResult AAResult =
11625         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11626                                          Overlap1,
11627                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11628                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11629                                          Overlap2,
11630                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11631     if (AAResult == AliasAnalysis::NoAlias)
11632       return false;
11633   }
11634
11635   // Otherwise we have to assume they alias.
11636   return true;
11637 }
11638
11639 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11640 /// looking for aliasing nodes and adding them to the Aliases vector.
11641 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11642                                    SmallVectorImpl<SDValue> &Aliases) {
11643   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11644   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11645
11646   // Get alias information for node.
11647   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11648
11649   // Starting off.
11650   Chains.push_back(OriginalChain);
11651   unsigned Depth = 0;
11652
11653   // Look at each chain and determine if it is an alias.  If so, add it to the
11654   // aliases list.  If not, then continue up the chain looking for the next
11655   // candidate.
11656   while (!Chains.empty()) {
11657     SDValue Chain = Chains.back();
11658     Chains.pop_back();
11659
11660     // For TokenFactor nodes, look at each operand and only continue up the
11661     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11662     // find more and revert to original chain since the xform is unlikely to be
11663     // profitable.
11664     //
11665     // FIXME: The depth check could be made to return the last non-aliasing
11666     // chain we found before we hit a tokenfactor rather than the original
11667     // chain.
11668     if (Depth > 6 || Aliases.size() == 2) {
11669       Aliases.clear();
11670       Aliases.push_back(OriginalChain);
11671       return;
11672     }
11673
11674     // Don't bother if we've been before.
11675     if (!Visited.insert(Chain.getNode()))
11676       continue;
11677
11678     switch (Chain.getOpcode()) {
11679     case ISD::EntryToken:
11680       // Entry token is ideal chain operand, but handled in FindBetterChain.
11681       break;
11682
11683     case ISD::LOAD:
11684     case ISD::STORE: {
11685       // Get alias information for Chain.
11686       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11687           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11688
11689       // If chain is alias then stop here.
11690       if (!(IsLoad && IsOpLoad) &&
11691           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11692         Aliases.push_back(Chain);
11693       } else {
11694         // Look further up the chain.
11695         Chains.push_back(Chain.getOperand(0));
11696         ++Depth;
11697       }
11698       break;
11699     }
11700
11701     case ISD::TokenFactor:
11702       // We have to check each of the operands of the token factor for "small"
11703       // token factors, so we queue them up.  Adding the operands to the queue
11704       // (stack) in reverse order maintains the original order and increases the
11705       // likelihood that getNode will find a matching token factor (CSE.)
11706       if (Chain.getNumOperands() > 16) {
11707         Aliases.push_back(Chain);
11708         break;
11709       }
11710       for (unsigned n = Chain.getNumOperands(); n;)
11711         Chains.push_back(Chain.getOperand(--n));
11712       ++Depth;
11713       break;
11714
11715     default:
11716       // For all other instructions we will just have to take what we can get.
11717       Aliases.push_back(Chain);
11718       break;
11719     }
11720   }
11721
11722   // We need to be careful here to also search for aliases through the
11723   // value operand of a store, etc. Consider the following situation:
11724   //   Token1 = ...
11725   //   L1 = load Token1, %52
11726   //   S1 = store Token1, L1, %51
11727   //   L2 = load Token1, %52+8
11728   //   S2 = store Token1, L2, %51+8
11729   //   Token2 = Token(S1, S2)
11730   //   L3 = load Token2, %53
11731   //   S3 = store Token2, L3, %52
11732   //   L4 = load Token2, %53+8
11733   //   S4 = store Token2, L4, %52+8
11734   // If we search for aliases of S3 (which loads address %52), and we look
11735   // only through the chain, then we'll miss the trivial dependence on L1
11736   // (which also loads from %52). We then might change all loads and
11737   // stores to use Token1 as their chain operand, which could result in
11738   // copying %53 into %52 before copying %52 into %51 (which should
11739   // happen first).
11740   //
11741   // The problem is, however, that searching for such data dependencies
11742   // can become expensive, and the cost is not directly related to the
11743   // chain depth. Instead, we'll rule out such configurations here by
11744   // insisting that we've visited all chain users (except for users
11745   // of the original chain, which is not necessary). When doing this,
11746   // we need to look through nodes we don't care about (otherwise, things
11747   // like register copies will interfere with trivial cases).
11748
11749   SmallVector<const SDNode *, 16> Worklist;
11750   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11751        IE = Visited.end(); I != IE; ++I)
11752     if (*I != OriginalChain.getNode())
11753       Worklist.push_back(*I);
11754
11755   while (!Worklist.empty()) {
11756     const SDNode *M = Worklist.pop_back_val();
11757
11758     // We have already visited M, and want to make sure we've visited any uses
11759     // of M that we care about. For uses that we've not visisted, and don't
11760     // care about, queue them to the worklist.
11761
11762     for (SDNode::use_iterator UI = M->use_begin(),
11763          UIE = M->use_end(); UI != UIE; ++UI)
11764       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11765         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11766           // We've not visited this use, and we care about it (it could have an
11767           // ordering dependency with the original node).
11768           Aliases.clear();
11769           Aliases.push_back(OriginalChain);
11770           return;
11771         }
11772
11773         // We've not visited this use, but we don't care about it. Mark it as
11774         // visited and enqueue it to the worklist.
11775         Worklist.push_back(*UI);
11776       }
11777   }
11778 }
11779
11780 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11781 /// for a better chain (aliasing node.)
11782 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11783   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11784
11785   // Accumulate all the aliases to this node.
11786   GatherAllAliases(N, OldChain, Aliases);
11787
11788   // If no operands then chain to entry token.
11789   if (Aliases.size() == 0)
11790     return DAG.getEntryNode();
11791
11792   // If a single operand then chain to it.  We don't need to revisit it.
11793   if (Aliases.size() == 1)
11794     return Aliases[0];
11795
11796   // Construct a custom tailored token factor.
11797   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11798 }
11799
11800 // SelectionDAG::Combine - This is the entry point for the file.
11801 //
11802 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11803                            CodeGenOpt::Level OptLevel) {
11804   /// run - This is the main entry point to this class.
11805   ///
11806   DAGCombiner(*this, AA, OptLevel).Run(Level);
11807 }