Break PseudoSourceValue out of the Value hierarchy. It is now the root of its own...
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 STATISTIC(NodesCombined   , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
49
50 namespace {
51   static cl::opt<bool>
52     CombinerAA("combiner-alias-analysis", cl::Hidden,
53                cl::desc("Enable DAG combiner alias-analysis heuristics"));
54
55   static cl::opt<bool>
56     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57                cl::desc("Enable DAG combiner's use of IR alias analysis"));
58
59   static cl::opt<bool>
60     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
61                cl::desc("Enable DAG combiner's use of TBAA"));
62
63 #ifndef NDEBUG
64   static cl::opt<std::string>
65     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
66                cl::desc("Only use DAG-combiner alias analysis in this"
67                         " function"));
68 #endif
69
70   /// Hidden option to stress test load slicing, i.e., when this option
71   /// is enabled, load slicing bypasses most of its profitability guards.
72   static cl::opt<bool>
73   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
74                     cl::desc("Bypass the profitability model of load "
75                              "slicing"),
76                     cl::init(false));
77
78 //------------------------------ DAGCombiner ---------------------------------//
79
80   class DAGCombiner {
81     SelectionDAG &DAG;
82     const TargetLowering &TLI;
83     CombineLevel Level;
84     CodeGenOpt::Level OptLevel;
85     bool LegalOperations;
86     bool LegalTypes;
87     bool ForCodeSize;
88
89     // Worklist of all of the nodes that need to be simplified.
90     //
91     // This has the semantics that when adding to the worklist,
92     // the item added must be next to be processed. It should
93     // also only appear once. The naive approach to this takes
94     // linear time.
95     //
96     // To reduce the insert/remove time to logarithmic, we use
97     // a set and a vector to maintain our worklist.
98     //
99     // The set contains the items on the worklist, but does not
100     // maintain the order they should be visited.
101     //
102     // The vector maintains the order nodes should be visited, but may
103     // contain duplicate or removed nodes. When choosing a node to
104     // visit, we pop off the order stack until we find an item that is
105     // also in the contents set. All operations are O(log N).
106     SmallPtrSet<SDNode*, 64> WorkListContents;
107     SmallVector<SDNode*, 64> WorkListOrder;
108
109     // AA - Used for DAG load/store alias analysis.
110     AliasAnalysis &AA;
111
112     /// AddUsersToWorkList - When an instruction is simplified, add all users of
113     /// the instruction to the work lists because they might get more simplified
114     /// now.
115     ///
116     void AddUsersToWorkList(SDNode *N) {
117       for (SDNode *Node : N->uses())
118         AddToWorkList(Node);
119     }
120
121     /// visit - call the node-specific routine that knows how to fold each
122     /// particular type of node.
123     SDValue visit(SDNode *N);
124
125   public:
126     /// AddToWorkList - Add to the work list making sure its instance is at the
127     /// back (next to be processed.)
128     void AddToWorkList(SDNode *N) {
129       WorkListContents.insert(N);
130       WorkListOrder.push_back(N);
131     }
132
133     /// removeFromWorkList - remove all instances of N from the worklist.
134     ///
135     void removeFromWorkList(SDNode *N) {
136       WorkListContents.erase(N);
137     }
138
139     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
140                       bool AddTo = true);
141
142     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
143       return CombineTo(N, &Res, 1, AddTo);
144     }
145
146     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
147                       bool AddTo = true) {
148       SDValue To[] = { Res0, Res1 };
149       return CombineTo(N, To, 2, AddTo);
150     }
151
152     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
153
154   private:
155
156     /// SimplifyDemandedBits - Check the specified integer node value to see if
157     /// it can be simplified or if things it uses can be simplified by bit
158     /// propagation.  If so, return true.
159     bool SimplifyDemandedBits(SDValue Op) {
160       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
161       APInt Demanded = APInt::getAllOnesValue(BitWidth);
162       return SimplifyDemandedBits(Op, Demanded);
163     }
164
165     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
166
167     bool CombineToPreIndexedLoadStore(SDNode *N);
168     bool CombineToPostIndexedLoadStore(SDNode *N);
169     bool SliceUpLoad(SDNode *N);
170
171     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
172     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
173     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
174     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
175     SDValue PromoteIntBinOp(SDValue Op);
176     SDValue PromoteIntShiftOp(SDValue Op);
177     SDValue PromoteExtend(SDValue Op);
178     bool PromoteLoad(SDValue Op);
179
180     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
181                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
182                          ISD::NodeType ExtType);
183
184     /// combine - call the node-specific routine that knows how to fold each
185     /// particular type of node. If that doesn't do anything, try the
186     /// target-specific DAG combines.
187     SDValue combine(SDNode *N);
188
189     // Visitation implementation - Implement dag node combining for different
190     // node types.  The semantics are as follows:
191     // Return Value:
192     //   SDValue.getNode() == 0 - No change was made
193     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
194     //   otherwise              - N should be replaced by the returned Operand.
195     //
196     SDValue visitTokenFactor(SDNode *N);
197     SDValue visitMERGE_VALUES(SDNode *N);
198     SDValue visitADD(SDNode *N);
199     SDValue visitSUB(SDNode *N);
200     SDValue visitADDC(SDNode *N);
201     SDValue visitSUBC(SDNode *N);
202     SDValue visitADDE(SDNode *N);
203     SDValue visitSUBE(SDNode *N);
204     SDValue visitMUL(SDNode *N);
205     SDValue visitSDIV(SDNode *N);
206     SDValue visitUDIV(SDNode *N);
207     SDValue visitSREM(SDNode *N);
208     SDValue visitUREM(SDNode *N);
209     SDValue visitMULHU(SDNode *N);
210     SDValue visitMULHS(SDNode *N);
211     SDValue visitSMUL_LOHI(SDNode *N);
212     SDValue visitUMUL_LOHI(SDNode *N);
213     SDValue visitSMULO(SDNode *N);
214     SDValue visitUMULO(SDNode *N);
215     SDValue visitSDIVREM(SDNode *N);
216     SDValue visitUDIVREM(SDNode *N);
217     SDValue visitAND(SDNode *N);
218     SDValue visitOR(SDNode *N);
219     SDValue visitXOR(SDNode *N);
220     SDValue SimplifyVBinOp(SDNode *N);
221     SDValue SimplifyVUnaryOp(SDNode *N);
222     SDValue visitSHL(SDNode *N);
223     SDValue visitSRA(SDNode *N);
224     SDValue visitSRL(SDNode *N);
225     SDValue visitRotate(SDNode *N);
226     SDValue visitCTLZ(SDNode *N);
227     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
228     SDValue visitCTTZ(SDNode *N);
229     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
230     SDValue visitCTPOP(SDNode *N);
231     SDValue visitSELECT(SDNode *N);
232     SDValue visitVSELECT(SDNode *N);
233     SDValue visitSELECT_CC(SDNode *N);
234     SDValue visitSETCC(SDNode *N);
235     SDValue visitSIGN_EXTEND(SDNode *N);
236     SDValue visitZERO_EXTEND(SDNode *N);
237     SDValue visitANY_EXTEND(SDNode *N);
238     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
239     SDValue visitTRUNCATE(SDNode *N);
240     SDValue visitBITCAST(SDNode *N);
241     SDValue visitBUILD_PAIR(SDNode *N);
242     SDValue visitFADD(SDNode *N);
243     SDValue visitFSUB(SDNode *N);
244     SDValue visitFMUL(SDNode *N);
245     SDValue visitFMA(SDNode *N);
246     SDValue visitFDIV(SDNode *N);
247     SDValue visitFREM(SDNode *N);
248     SDValue visitFCOPYSIGN(SDNode *N);
249     SDValue visitSINT_TO_FP(SDNode *N);
250     SDValue visitUINT_TO_FP(SDNode *N);
251     SDValue visitFP_TO_SINT(SDNode *N);
252     SDValue visitFP_TO_UINT(SDNode *N);
253     SDValue visitFP_ROUND(SDNode *N);
254     SDValue visitFP_ROUND_INREG(SDNode *N);
255     SDValue visitFP_EXTEND(SDNode *N);
256     SDValue visitFNEG(SDNode *N);
257     SDValue visitFABS(SDNode *N);
258     SDValue visitFCEIL(SDNode *N);
259     SDValue visitFTRUNC(SDNode *N);
260     SDValue visitFFLOOR(SDNode *N);
261     SDValue visitBRCOND(SDNode *N);
262     SDValue visitBR_CC(SDNode *N);
263     SDValue visitLOAD(SDNode *N);
264     SDValue visitSTORE(SDNode *N);
265     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
266     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
267     SDValue visitBUILD_VECTOR(SDNode *N);
268     SDValue visitCONCAT_VECTORS(SDNode *N);
269     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
270     SDValue visitVECTOR_SHUFFLE(SDNode *N);
271     SDValue visitINSERT_SUBVECTOR(SDNode *N);
272
273     SDValue XformToShuffleWithZero(SDNode *N);
274     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
275
276     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
277
278     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
279     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
280     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
281     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
282                              SDValue N3, ISD::CondCode CC,
283                              bool NotExtCompare = false);
284     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
285                           SDLoc DL, bool foldBooleans = true);
286
287     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
288                            SDValue &CC) const;
289     bool isOneUseSetCC(SDValue N) const;
290
291     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
292                                          unsigned HiOp);
293     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
294     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
295     SDValue BuildSDIV(SDNode *N);
296     SDValue BuildUDIV(SDNode *N);
297     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
298                                bool DemandHighBits = true);
299     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
300     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
301                               SDValue InnerPos, SDValue InnerNeg,
302                               unsigned PosOpcode, unsigned NegOpcode,
303                               SDLoc DL);
304     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
305     SDValue ReduceLoadWidth(SDNode *N);
306     SDValue ReduceLoadOpStoreWidth(SDNode *N);
307     SDValue TransformFPLoadStorePair(SDNode *N);
308     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
309     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
310
311     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
312
313     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
314     /// looking for aliasing nodes and adding them to the Aliases vector.
315     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
316                           SmallVectorImpl<SDValue> &Aliases);
317
318     /// isAlias - Return true if there is any possibility that the two addresses
319     /// overlap.
320     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
321
322     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
323     /// looking for a better chain (aliasing node.)
324     SDValue FindBetterChain(SDNode *N, SDValue Chain);
325
326     /// Merge consecutive store operations into a wide store.
327     /// This optimization uses wide integers or vectors when possible.
328     /// \return True if some memory operations were changed.
329     bool MergeConsecutiveStores(StoreSDNode *N);
330
331     /// \brief Try to transform a truncation where C is a constant:
332     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
333     ///
334     /// \p N needs to be a truncation and its first operand an AND. Other
335     /// requirements are checked by the function (e.g. that trunc is
336     /// single-use) and if missed an empty SDValue is returned.
337     SDValue distributeTruncateThroughAnd(SDNode *N);
338
339   public:
340     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
341         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
342           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
343       AttributeSet FnAttrs =
344           DAG.getMachineFunction().getFunction()->getAttributes();
345       ForCodeSize =
346           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
347                                Attribute::OptimizeForSize) ||
348           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
349     }
350
351     /// Run - runs the dag combiner on all nodes in the work list
352     void Run(CombineLevel AtLevel);
353
354     SelectionDAG &getDAG() const { return DAG; }
355
356     /// getShiftAmountTy - Returns a type large enough to hold any valid
357     /// shift amount - before type legalization these can be huge.
358     EVT getShiftAmountTy(EVT LHSTy) {
359       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
360       if (LHSTy.isVector())
361         return LHSTy;
362       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
363                         : TLI.getPointerTy();
364     }
365
366     /// isTypeLegal - This method returns true if we are running before type
367     /// legalization or if the specified VT is legal.
368     bool isTypeLegal(const EVT &VT) {
369       if (!LegalTypes) return true;
370       return TLI.isTypeLegal(VT);
371     }
372
373     /// getSetCCResultType - Convenience wrapper around
374     /// TargetLowering::getSetCCResultType
375     EVT getSetCCResultType(EVT VT) const {
376       return TLI.getSetCCResultType(*DAG.getContext(), VT);
377     }
378   };
379 }
380
381
382 namespace {
383 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
384 /// nodes from the worklist.
385 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
386   DAGCombiner &DC;
387 public:
388   explicit WorkListRemover(DAGCombiner &dc)
389     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
390
391   void NodeDeleted(SDNode *N, SDNode *E) override {
392     DC.removeFromWorkList(N);
393   }
394 };
395 }
396
397 //===----------------------------------------------------------------------===//
398 //  TargetLowering::DAGCombinerInfo implementation
399 //===----------------------------------------------------------------------===//
400
401 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
402   ((DAGCombiner*)DC)->AddToWorkList(N);
403 }
404
405 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
406   ((DAGCombiner*)DC)->removeFromWorkList(N);
407 }
408
409 SDValue TargetLowering::DAGCombinerInfo::
410 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
411   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
412 }
413
414 SDValue TargetLowering::DAGCombinerInfo::
415 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
416   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
417 }
418
419
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
422   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
423 }
424
425 void TargetLowering::DAGCombinerInfo::
426 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
427   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
428 }
429
430 //===----------------------------------------------------------------------===//
431 // Helper Functions
432 //===----------------------------------------------------------------------===//
433
434 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
435 /// specified expression for the same cost as the expression itself, or 2 if we
436 /// can compute the negated form more cheaply than the expression itself.
437 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
438                                const TargetLowering &TLI,
439                                const TargetOptions *Options,
440                                unsigned Depth = 0) {
441   // fneg is removable even if it has multiple uses.
442   if (Op.getOpcode() == ISD::FNEG) return 2;
443
444   // Don't allow anything with multiple uses.
445   if (!Op.hasOneUse()) return 0;
446
447   // Don't recurse exponentially.
448   if (Depth > 6) return 0;
449
450   switch (Op.getOpcode()) {
451   default: return false;
452   case ISD::ConstantFP:
453     // Don't invert constant FP values after legalize.  The negated constant
454     // isn't necessarily legal.
455     return LegalOperations ? 0 : 1;
456   case ISD::FADD:
457     // FIXME: determine better conditions for this xform.
458     if (!Options->UnsafeFPMath) return 0;
459
460     // After operation legalization, it might not be legal to create new FSUBs.
461     if (LegalOperations &&
462         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
463       return 0;
464
465     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
466     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
467                                     Options, Depth + 1))
468       return V;
469     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
470     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
471                               Depth + 1);
472   case ISD::FSUB:
473     // We can't turn -(A-B) into B-A when we honor signed zeros.
474     if (!Options->UnsafeFPMath) return 0;
475
476     // fold (fneg (fsub A, B)) -> (fsub B, A)
477     return 1;
478
479   case ISD::FMUL:
480   case ISD::FDIV:
481     if (Options->HonorSignDependentRoundingFPMath()) return 0;
482
483     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
484     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
485                                     Options, Depth + 1))
486       return V;
487
488     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
489                               Depth + 1);
490
491   case ISD::FP_EXTEND:
492   case ISD::FP_ROUND:
493   case ISD::FSIN:
494     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
495                               Depth + 1);
496   }
497 }
498
499 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
500 /// returns the newly negated expression.
501 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
502                                     bool LegalOperations, unsigned Depth = 0) {
503   // fneg is removable even if it has multiple uses.
504   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
505
506   // Don't allow anything with multiple uses.
507   assert(Op.hasOneUse() && "Unknown reuse!");
508
509   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
510   switch (Op.getOpcode()) {
511   default: llvm_unreachable("Unknown code");
512   case ISD::ConstantFP: {
513     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
514     V.changeSign();
515     return DAG.getConstantFP(V, Op.getValueType());
516   }
517   case ISD::FADD:
518     // FIXME: determine better conditions for this xform.
519     assert(DAG.getTarget().Options.UnsafeFPMath);
520
521     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
522     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523                            DAG.getTargetLoweringInfo(),
524                            &DAG.getTarget().Options, Depth+1))
525       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
526                          GetNegatedExpression(Op.getOperand(0), DAG,
527                                               LegalOperations, Depth+1),
528                          Op.getOperand(1));
529     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
530     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
531                        GetNegatedExpression(Op.getOperand(1), DAG,
532                                             LegalOperations, Depth+1),
533                        Op.getOperand(0));
534   case ISD::FSUB:
535     // We can't turn -(A-B) into B-A when we honor signed zeros.
536     assert(DAG.getTarget().Options.UnsafeFPMath);
537
538     // fold (fneg (fsub 0, B)) -> B
539     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
540       if (N0CFP->getValueAPF().isZero())
541         return Op.getOperand(1);
542
543     // fold (fneg (fsub A, B)) -> (fsub B, A)
544     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
545                        Op.getOperand(1), Op.getOperand(0));
546
547   case ISD::FMUL:
548   case ISD::FDIV:
549     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
550
551     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
552     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
553                            DAG.getTargetLoweringInfo(),
554                            &DAG.getTarget().Options, Depth+1))
555       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
556                          GetNegatedExpression(Op.getOperand(0), DAG,
557                                               LegalOperations, Depth+1),
558                          Op.getOperand(1));
559
560     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
561     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
562                        Op.getOperand(0),
563                        GetNegatedExpression(Op.getOperand(1), DAG,
564                                             LegalOperations, Depth+1));
565
566   case ISD::FP_EXTEND:
567   case ISD::FSIN:
568     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
569                        GetNegatedExpression(Op.getOperand(0), DAG,
570                                             LegalOperations, Depth+1));
571   case ISD::FP_ROUND:
572       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
573                          GetNegatedExpression(Op.getOperand(0), DAG,
574                                               LegalOperations, Depth+1),
575                          Op.getOperand(1));
576   }
577 }
578
579 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
580 // that selects between the target values used for true and false, making it
581 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
582 // the appropriate nodes based on the type of node we are checking. This
583 // simplifies life a bit for the callers.
584 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
585                                     SDValue &CC) const {
586   if (N.getOpcode() == ISD::SETCC) {
587     LHS = N.getOperand(0);
588     RHS = N.getOperand(1);
589     CC  = N.getOperand(2);
590     return true;
591   }
592
593   if (N.getOpcode() != ISD::SELECT_CC ||
594       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
595       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
596     return false;
597
598   LHS = N.getOperand(0);
599   RHS = N.getOperand(1);
600   CC  = N.getOperand(4);
601   return true;
602 }
603
604 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
605 // one use.  If this is true, it allows the users to invert the operation for
606 // free when it is profitable to do so.
607 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
608   SDValue N0, N1, N2;
609   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
610     return true;
611   return false;
612 }
613
614 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
615 /// elements are all the same constant or undefined.
616 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
617   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
618   if (!C)
619     return false;
620
621   APInt SplatUndef;
622   unsigned SplatBitSize;
623   bool HasAnyUndefs;
624   EVT EltVT = N->getValueType(0).getVectorElementType();
625   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
626                              HasAnyUndefs) &&
627           EltVT.getSizeInBits() >= SplatBitSize);
628 }
629
630 // \brief Returns the SDNode if it is a constant BuildVector or constant.
631 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
632   if (isa<ConstantSDNode>(N))
633     return N.getNode();
634   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
635   if(BV && BV->isConstant())
636     return BV;
637   return nullptr;
638 }
639
640 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
641 // int.
642 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
643   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
644     return CN;
645
646   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N))
647     return BV->getConstantSplatValue();
648
649   return nullptr;
650 }
651
652 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
653                                     SDValue N0, SDValue N1) {
654   EVT VT = N0.getValueType();
655   if (N0.getOpcode() == Opc) {
656     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
657       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
658         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
659         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
660         if (!OpNode.getNode())
661           return SDValue();
662         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
663       }
664       if (N0.hasOneUse()) {
665         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
666         // use
667         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
668         if (!OpNode.getNode())
669           return SDValue();
670         AddToWorkList(OpNode.getNode());
671         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
672       }
673     }
674   }
675
676   if (N1.getOpcode() == Opc) {
677     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
678       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
679         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
680         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
681         if (!OpNode.getNode())
682           return SDValue();
683         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
684       }
685       if (N1.hasOneUse()) {
686         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
687         // use
688         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
689         if (!OpNode.getNode())
690           return SDValue();
691         AddToWorkList(OpNode.getNode());
692         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
693       }
694     }
695   }
696
697   return SDValue();
698 }
699
700 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
701                                bool AddTo) {
702   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
703   ++NodesCombined;
704   DEBUG(dbgs() << "\nReplacing.1 ";
705         N->dump(&DAG);
706         dbgs() << "\nWith: ";
707         To[0].getNode()->dump(&DAG);
708         dbgs() << " and " << NumTo-1 << " other values\n";
709         for (unsigned i = 0, e = NumTo; i != e; ++i)
710           assert((!To[i].getNode() ||
711                   N->getValueType(i) == To[i].getValueType()) &&
712                  "Cannot combine value to value of different type!"));
713   WorkListRemover DeadNodes(*this);
714   DAG.ReplaceAllUsesWith(N, To);
715   if (AddTo) {
716     // Push the new nodes and any users onto the worklist
717     for (unsigned i = 0, e = NumTo; i != e; ++i) {
718       if (To[i].getNode()) {
719         AddToWorkList(To[i].getNode());
720         AddUsersToWorkList(To[i].getNode());
721       }
722     }
723   }
724
725   // Finally, if the node is now dead, remove it from the graph.  The node
726   // may not be dead if the replacement process recursively simplified to
727   // something else needing this node.
728   if (N->use_empty()) {
729     // Nodes can be reintroduced into the worklist.  Make sure we do not
730     // process a node that has been replaced.
731     removeFromWorkList(N);
732
733     // Finally, since the node is now dead, remove it from the graph.
734     DAG.DeleteNode(N);
735   }
736   return SDValue(N, 0);
737 }
738
739 void DAGCombiner::
740 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
741   // Replace all uses.  If any nodes become isomorphic to other nodes and
742   // are deleted, make sure to remove them from our worklist.
743   WorkListRemover DeadNodes(*this);
744   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
745
746   // Push the new node and any (possibly new) users onto the worklist.
747   AddToWorkList(TLO.New.getNode());
748   AddUsersToWorkList(TLO.New.getNode());
749
750   // Finally, if the node is now dead, remove it from the graph.  The node
751   // may not be dead if the replacement process recursively simplified to
752   // something else needing this node.
753   if (TLO.Old.getNode()->use_empty()) {
754     removeFromWorkList(TLO.Old.getNode());
755
756     // If the operands of this node are only used by the node, they will now
757     // be dead.  Make sure to visit them first to delete dead nodes early.
758     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
759       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
760         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
761
762     DAG.DeleteNode(TLO.Old.getNode());
763   }
764 }
765
766 /// SimplifyDemandedBits - Check the specified integer node value to see if
767 /// it can be simplified or if things it uses can be simplified by bit
768 /// propagation.  If so, return true.
769 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
770   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
771   APInt KnownZero, KnownOne;
772   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
773     return false;
774
775   // Revisit the node.
776   AddToWorkList(Op.getNode());
777
778   // Replace the old value with the new one.
779   ++NodesCombined;
780   DEBUG(dbgs() << "\nReplacing.2 ";
781         TLO.Old.getNode()->dump(&DAG);
782         dbgs() << "\nWith: ";
783         TLO.New.getNode()->dump(&DAG);
784         dbgs() << '\n');
785
786   CommitTargetLoweringOpt(TLO);
787   return true;
788 }
789
790 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
791   SDLoc dl(Load);
792   EVT VT = Load->getValueType(0);
793   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
794
795   DEBUG(dbgs() << "\nReplacing.9 ";
796         Load->dump(&DAG);
797         dbgs() << "\nWith: ";
798         Trunc.getNode()->dump(&DAG);
799         dbgs() << '\n');
800   WorkListRemover DeadNodes(*this);
801   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
802   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
803   removeFromWorkList(Load);
804   DAG.DeleteNode(Load);
805   AddToWorkList(Trunc.getNode());
806 }
807
808 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
809   Replace = false;
810   SDLoc dl(Op);
811   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
812     EVT MemVT = LD->getMemoryVT();
813     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
814       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
815                                                   : ISD::EXTLOAD)
816       : LD->getExtensionType();
817     Replace = true;
818     return DAG.getExtLoad(ExtType, dl, PVT,
819                           LD->getChain(), LD->getBasePtr(),
820                           MemVT, LD->getMemOperand());
821   }
822
823   unsigned Opc = Op.getOpcode();
824   switch (Opc) {
825   default: break;
826   case ISD::AssertSext:
827     return DAG.getNode(ISD::AssertSext, dl, PVT,
828                        SExtPromoteOperand(Op.getOperand(0), PVT),
829                        Op.getOperand(1));
830   case ISD::AssertZext:
831     return DAG.getNode(ISD::AssertZext, dl, PVT,
832                        ZExtPromoteOperand(Op.getOperand(0), PVT),
833                        Op.getOperand(1));
834   case ISD::Constant: {
835     unsigned ExtOpc =
836       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
837     return DAG.getNode(ExtOpc, dl, PVT, Op);
838   }
839   }
840
841   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
842     return SDValue();
843   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
844 }
845
846 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
847   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
848     return SDValue();
849   EVT OldVT = Op.getValueType();
850   SDLoc dl(Op);
851   bool Replace = false;
852   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
853   if (!NewOp.getNode())
854     return SDValue();
855   AddToWorkList(NewOp.getNode());
856
857   if (Replace)
858     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
859   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
860                      DAG.getValueType(OldVT));
861 }
862
863 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
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.getZeroExtendInReg(NewOp, dl, OldVT);
875 }
876
877 /// PromoteIntBinOp - Promote the specified integer binary operation if the
878 /// target indicates it is beneficial. e.g. On x86, it's usually better to
879 /// promote i16 operations to i32 since i16 instructions are longer.
880 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
881   if (!LegalOperations)
882     return SDValue();
883
884   EVT VT = Op.getValueType();
885   if (VT.isVector() || !VT.isInteger())
886     return SDValue();
887
888   // If operation type is 'undesirable', e.g. i16 on x86, consider
889   // promoting it.
890   unsigned Opc = Op.getOpcode();
891   if (TLI.isTypeDesirableForOp(Opc, VT))
892     return SDValue();
893
894   EVT PVT = VT;
895   // Consult target whether it is a good idea to promote this operation and
896   // what's the right type to promote it to.
897   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
898     assert(PVT != VT && "Don't know what type to promote to!");
899
900     bool Replace0 = false;
901     SDValue N0 = Op.getOperand(0);
902     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
903     if (!NN0.getNode())
904       return SDValue();
905
906     bool Replace1 = false;
907     SDValue N1 = Op.getOperand(1);
908     SDValue NN1;
909     if (N0 == N1)
910       NN1 = NN0;
911     else {
912       NN1 = PromoteOperand(N1, PVT, Replace1);
913       if (!NN1.getNode())
914         return SDValue();
915     }
916
917     AddToWorkList(NN0.getNode());
918     if (NN1.getNode())
919       AddToWorkList(NN1.getNode());
920
921     if (Replace0)
922       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
923     if (Replace1)
924       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
925
926     DEBUG(dbgs() << "\nPromoting ";
927           Op.getNode()->dump(&DAG));
928     SDLoc dl(Op);
929     return DAG.getNode(ISD::TRUNCATE, dl, VT,
930                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
931   }
932   return SDValue();
933 }
934
935 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
936 /// target indicates it is beneficial. e.g. On x86, it's usually better to
937 /// promote i16 operations to i32 since i16 instructions are longer.
938 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
939   if (!LegalOperations)
940     return SDValue();
941
942   EVT VT = Op.getValueType();
943   if (VT.isVector() || !VT.isInteger())
944     return SDValue();
945
946   // If operation type is 'undesirable', e.g. i16 on x86, consider
947   // promoting it.
948   unsigned Opc = Op.getOpcode();
949   if (TLI.isTypeDesirableForOp(Opc, VT))
950     return SDValue();
951
952   EVT PVT = VT;
953   // Consult target whether it is a good idea to promote this operation and
954   // what's the right type to promote it to.
955   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
956     assert(PVT != VT && "Don't know what type to promote to!");
957
958     bool Replace = false;
959     SDValue N0 = Op.getOperand(0);
960     if (Opc == ISD::SRA)
961       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
962     else if (Opc == ISD::SRL)
963       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
964     else
965       N0 = PromoteOperand(N0, PVT, Replace);
966     if (!N0.getNode())
967       return SDValue();
968
969     AddToWorkList(N0.getNode());
970     if (Replace)
971       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
972
973     DEBUG(dbgs() << "\nPromoting ";
974           Op.getNode()->dump(&DAG));
975     SDLoc dl(Op);
976     return DAG.getNode(ISD::TRUNCATE, dl, VT,
977                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
978   }
979   return SDValue();
980 }
981
982 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001     // fold (aext (aext x)) -> (aext x)
1002     // fold (aext (zext x)) -> (zext x)
1003     // fold (aext (sext x)) -> (sext x)
1004     DEBUG(dbgs() << "\nPromoting ";
1005           Op.getNode()->dump(&DAG));
1006     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1007   }
1008   return SDValue();
1009 }
1010
1011 bool DAGCombiner::PromoteLoad(SDValue Op) {
1012   if (!LegalOperations)
1013     return false;
1014
1015   EVT VT = Op.getValueType();
1016   if (VT.isVector() || !VT.isInteger())
1017     return false;
1018
1019   // If operation type is 'undesirable', e.g. i16 on x86, consider
1020   // promoting it.
1021   unsigned Opc = Op.getOpcode();
1022   if (TLI.isTypeDesirableForOp(Opc, VT))
1023     return false;
1024
1025   EVT PVT = VT;
1026   // Consult target whether it is a good idea to promote this operation and
1027   // what's the right type to promote it to.
1028   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1029     assert(PVT != VT && "Don't know what type to promote to!");
1030
1031     SDLoc dl(Op);
1032     SDNode *N = Op.getNode();
1033     LoadSDNode *LD = cast<LoadSDNode>(N);
1034     EVT MemVT = LD->getMemoryVT();
1035     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1036       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1037                                                   : ISD::EXTLOAD)
1038       : LD->getExtensionType();
1039     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1040                                    LD->getChain(), LD->getBasePtr(),
1041                                    MemVT, LD->getMemOperand());
1042     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1043
1044     DEBUG(dbgs() << "\nPromoting ";
1045           N->dump(&DAG);
1046           dbgs() << "\nTo: ";
1047           Result.getNode()->dump(&DAG);
1048           dbgs() << '\n');
1049     WorkListRemover DeadNodes(*this);
1050     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1051     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1052     removeFromWorkList(N);
1053     DAG.DeleteNode(N);
1054     AddToWorkList(Result.getNode());
1055     return true;
1056   }
1057   return false;
1058 }
1059
1060
1061 //===----------------------------------------------------------------------===//
1062 //  Main DAG Combiner implementation
1063 //===----------------------------------------------------------------------===//
1064
1065 void DAGCombiner::Run(CombineLevel AtLevel) {
1066   // set the instance variables, so that the various visit routines may use it.
1067   Level = AtLevel;
1068   LegalOperations = Level >= AfterLegalizeVectorOps;
1069   LegalTypes = Level >= AfterLegalizeTypes;
1070
1071   // Add all the dag nodes to the worklist.
1072   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1073        E = DAG.allnodes_end(); I != E; ++I)
1074     AddToWorkList(I);
1075
1076   // Create a dummy node (which is not added to allnodes), that adds a reference
1077   // to the root node, preventing it from being deleted, and tracking any
1078   // changes of the root.
1079   HandleSDNode Dummy(DAG.getRoot());
1080
1081   // The root of the dag may dangle to deleted nodes until the dag combiner is
1082   // done.  Set it to null to avoid confusion.
1083   DAG.setRoot(SDValue());
1084
1085   // while the worklist isn't empty, find a node and
1086   // try and combine it.
1087   while (!WorkListContents.empty()) {
1088     SDNode *N;
1089     // The WorkListOrder holds the SDNodes in order, but it may contain
1090     // duplicates.
1091     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1092     // worklist *should* contain, and check the node we want to visit is should
1093     // actually be visited.
1094     do {
1095       N = WorkListOrder.pop_back_val();
1096     } while (!WorkListContents.erase(N));
1097
1098     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1099     // N is deleted from the DAG, since they too may now be dead or may have a
1100     // reduced number of uses, allowing other xforms.
1101     if (N->use_empty() && N != &Dummy) {
1102       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1103         AddToWorkList(N->getOperand(i).getNode());
1104
1105       DAG.DeleteNode(N);
1106       continue;
1107     }
1108
1109     SDValue RV = combine(N);
1110
1111     if (!RV.getNode())
1112       continue;
1113
1114     ++NodesCombined;
1115
1116     // If we get back the same node we passed in, rather than a new node or
1117     // zero, we know that the node must have defined multiple values and
1118     // CombineTo was used.  Since CombineTo takes care of the worklist
1119     // mechanics for us, we have no work to do in this case.
1120     if (RV.getNode() == N)
1121       continue;
1122
1123     assert(N->getOpcode() != ISD::DELETED_NODE &&
1124            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1125            "Node was deleted but visit returned new node!");
1126
1127     DEBUG(dbgs() << "\nReplacing.3 ";
1128           N->dump(&DAG);
1129           dbgs() << "\nWith: ";
1130           RV.getNode()->dump(&DAG);
1131           dbgs() << '\n');
1132
1133     // Transfer debug value.
1134     DAG.TransferDbgValues(SDValue(N, 0), RV);
1135     WorkListRemover DeadNodes(*this);
1136     if (N->getNumValues() == RV.getNode()->getNumValues())
1137       DAG.ReplaceAllUsesWith(N, RV.getNode());
1138     else {
1139       assert(N->getValueType(0) == RV.getValueType() &&
1140              N->getNumValues() == 1 && "Type mismatch");
1141       SDValue OpV = RV;
1142       DAG.ReplaceAllUsesWith(N, &OpV);
1143     }
1144
1145     // Push the new node and any users onto the worklist
1146     AddToWorkList(RV.getNode());
1147     AddUsersToWorkList(RV.getNode());
1148
1149     // Add any uses of the old node to the worklist in case this node is the
1150     // last one that uses them.  They may become dead after this node is
1151     // deleted.
1152     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1153       AddToWorkList(N->getOperand(i).getNode());
1154
1155     // Finally, if the node is now dead, remove it from the graph.  The node
1156     // may not be dead if the replacement process recursively simplified to
1157     // something else needing this node.
1158     if (N->use_empty()) {
1159       // Nodes can be reintroduced into the worklist.  Make sure we do not
1160       // process a node that has been replaced.
1161       removeFromWorkList(N);
1162
1163       // Finally, since the node is now dead, remove it from the graph.
1164       DAG.DeleteNode(N);
1165     }
1166   }
1167
1168   // If the root changed (e.g. it was a dead load, update the root).
1169   DAG.setRoot(Dummy.getValue());
1170   DAG.RemoveDeadNodes();
1171 }
1172
1173 SDValue DAGCombiner::visit(SDNode *N) {
1174   switch (N->getOpcode()) {
1175   default: break;
1176   case ISD::TokenFactor:        return visitTokenFactor(N);
1177   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1178   case ISD::ADD:                return visitADD(N);
1179   case ISD::SUB:                return visitSUB(N);
1180   case ISD::ADDC:               return visitADDC(N);
1181   case ISD::SUBC:               return visitSUBC(N);
1182   case ISD::ADDE:               return visitADDE(N);
1183   case ISD::SUBE:               return visitSUBE(N);
1184   case ISD::MUL:                return visitMUL(N);
1185   case ISD::SDIV:               return visitSDIV(N);
1186   case ISD::UDIV:               return visitUDIV(N);
1187   case ISD::SREM:               return visitSREM(N);
1188   case ISD::UREM:               return visitUREM(N);
1189   case ISD::MULHU:              return visitMULHU(N);
1190   case ISD::MULHS:              return visitMULHS(N);
1191   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1192   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1193   case ISD::SMULO:              return visitSMULO(N);
1194   case ISD::UMULO:              return visitUMULO(N);
1195   case ISD::SDIVREM:            return visitSDIVREM(N);
1196   case ISD::UDIVREM:            return visitUDIVREM(N);
1197   case ISD::AND:                return visitAND(N);
1198   case ISD::OR:                 return visitOR(N);
1199   case ISD::XOR:                return visitXOR(N);
1200   case ISD::SHL:                return visitSHL(N);
1201   case ISD::SRA:                return visitSRA(N);
1202   case ISD::SRL:                return visitSRL(N);
1203   case ISD::ROTR:
1204   case ISD::ROTL:               return visitRotate(N);
1205   case ISD::CTLZ:               return visitCTLZ(N);
1206   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1207   case ISD::CTTZ:               return visitCTTZ(N);
1208   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1209   case ISD::CTPOP:              return visitCTPOP(N);
1210   case ISD::SELECT:             return visitSELECT(N);
1211   case ISD::VSELECT:            return visitVSELECT(N);
1212   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1213   case ISD::SETCC:              return visitSETCC(N);
1214   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1215   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1216   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1217   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1218   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1219   case ISD::BITCAST:            return visitBITCAST(N);
1220   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1221   case ISD::FADD:               return visitFADD(N);
1222   case ISD::FSUB:               return visitFSUB(N);
1223   case ISD::FMUL:               return visitFMUL(N);
1224   case ISD::FMA:                return visitFMA(N);
1225   case ISD::FDIV:               return visitFDIV(N);
1226   case ISD::FREM:               return visitFREM(N);
1227   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1228   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1229   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1230   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1231   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1232   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1233   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1234   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1235   case ISD::FNEG:               return visitFNEG(N);
1236   case ISD::FABS:               return visitFABS(N);
1237   case ISD::FFLOOR:             return visitFFLOOR(N);
1238   case ISD::FCEIL:              return visitFCEIL(N);
1239   case ISD::FTRUNC:             return visitFTRUNC(N);
1240   case ISD::BRCOND:             return visitBRCOND(N);
1241   case ISD::BR_CC:              return visitBR_CC(N);
1242   case ISD::LOAD:               return visitLOAD(N);
1243   case ISD::STORE:              return visitSTORE(N);
1244   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1245   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1246   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1247   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1248   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1249   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1250   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1251   }
1252   return SDValue();
1253 }
1254
1255 SDValue DAGCombiner::combine(SDNode *N) {
1256   SDValue RV = visit(N);
1257
1258   // If nothing happened, try a target-specific DAG combine.
1259   if (!RV.getNode()) {
1260     assert(N->getOpcode() != ISD::DELETED_NODE &&
1261            "Node was deleted but visit returned NULL!");
1262
1263     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1264         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1265
1266       // Expose the DAG combiner to the target combiner impls.
1267       TargetLowering::DAGCombinerInfo
1268         DagCombineInfo(DAG, Level, false, this);
1269
1270       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1271     }
1272   }
1273
1274   // If nothing happened still, try promoting the operation.
1275   if (!RV.getNode()) {
1276     switch (N->getOpcode()) {
1277     default: break;
1278     case ISD::ADD:
1279     case ISD::SUB:
1280     case ISD::MUL:
1281     case ISD::AND:
1282     case ISD::OR:
1283     case ISD::XOR:
1284       RV = PromoteIntBinOp(SDValue(N, 0));
1285       break;
1286     case ISD::SHL:
1287     case ISD::SRA:
1288     case ISD::SRL:
1289       RV = PromoteIntShiftOp(SDValue(N, 0));
1290       break;
1291     case ISD::SIGN_EXTEND:
1292     case ISD::ZERO_EXTEND:
1293     case ISD::ANY_EXTEND:
1294       RV = PromoteExtend(SDValue(N, 0));
1295       break;
1296     case ISD::LOAD:
1297       if (PromoteLoad(SDValue(N, 0)))
1298         RV = SDValue(N, 0);
1299       break;
1300     }
1301   }
1302
1303   // If N is a commutative binary node, try commuting it to enable more
1304   // sdisel CSE.
1305   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1306       N->getNumValues() == 1) {
1307     SDValue N0 = N->getOperand(0);
1308     SDValue N1 = N->getOperand(1);
1309
1310     // Constant operands are canonicalized to RHS.
1311     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1312       SDValue Ops[] = { N1, N0 };
1313       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1314                                             Ops, 2);
1315       if (CSENode)
1316         return SDValue(CSENode, 0);
1317     }
1318   }
1319
1320   return RV;
1321 }
1322
1323 /// getInputChainForNode - Given a node, return its input chain if it has one,
1324 /// otherwise return a null sd operand.
1325 static SDValue getInputChainForNode(SDNode *N) {
1326   if (unsigned NumOps = N->getNumOperands()) {
1327     if (N->getOperand(0).getValueType() == MVT::Other)
1328       return N->getOperand(0);
1329     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1330       return N->getOperand(NumOps-1);
1331     for (unsigned i = 1; i < NumOps-1; ++i)
1332       if (N->getOperand(i).getValueType() == MVT::Other)
1333         return N->getOperand(i);
1334   }
1335   return SDValue();
1336 }
1337
1338 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1339   // If N has two operands, where one has an input chain equal to the other,
1340   // the 'other' chain is redundant.
1341   if (N->getNumOperands() == 2) {
1342     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1343       return N->getOperand(0);
1344     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1345       return N->getOperand(1);
1346   }
1347
1348   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1349   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1350   SmallPtrSet<SDNode*, 16> SeenOps;
1351   bool Changed = false;             // If we should replace this token factor.
1352
1353   // Start out with this token factor.
1354   TFs.push_back(N);
1355
1356   // Iterate through token factors.  The TFs grows when new token factors are
1357   // encountered.
1358   for (unsigned i = 0; i < TFs.size(); ++i) {
1359     SDNode *TF = TFs[i];
1360
1361     // Check each of the operands.
1362     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1363       SDValue Op = TF->getOperand(i);
1364
1365       switch (Op.getOpcode()) {
1366       case ISD::EntryToken:
1367         // Entry tokens don't need to be added to the list. They are
1368         // rededundant.
1369         Changed = true;
1370         break;
1371
1372       case ISD::TokenFactor:
1373         if (Op.hasOneUse() &&
1374             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1375           // Queue up for processing.
1376           TFs.push_back(Op.getNode());
1377           // Clean up in case the token factor is removed.
1378           AddToWorkList(Op.getNode());
1379           Changed = true;
1380           break;
1381         }
1382         // Fall thru
1383
1384       default:
1385         // Only add if it isn't already in the list.
1386         if (SeenOps.insert(Op.getNode()))
1387           Ops.push_back(Op);
1388         else
1389           Changed = true;
1390         break;
1391       }
1392     }
1393   }
1394
1395   SDValue Result;
1396
1397   // If we've change things around then replace token factor.
1398   if (Changed) {
1399     if (Ops.empty()) {
1400       // The entry token is the only possible outcome.
1401       Result = DAG.getEntryNode();
1402     } else {
1403       // New and improved token factor.
1404       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1405                            MVT::Other, &Ops[0], Ops.size());
1406     }
1407
1408     // Don't add users to work list.
1409     return CombineTo(N, Result, false);
1410   }
1411
1412   return Result;
1413 }
1414
1415 /// MERGE_VALUES can always be eliminated.
1416 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1417   WorkListRemover DeadNodes(*this);
1418   // Replacing results may cause a different MERGE_VALUES to suddenly
1419   // be CSE'd with N, and carry its uses with it. Iterate until no
1420   // uses remain, to ensure that the node can be safely deleted.
1421   // First add the users of this node to the work list so that they
1422   // can be tried again once they have new operands.
1423   AddUsersToWorkList(N);
1424   do {
1425     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1426       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1427   } while (!N->use_empty());
1428   removeFromWorkList(N);
1429   DAG.DeleteNode(N);
1430   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1431 }
1432
1433 static
1434 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1435                               SelectionDAG &DAG) {
1436   EVT VT = N0.getValueType();
1437   SDValue N00 = N0.getOperand(0);
1438   SDValue N01 = N0.getOperand(1);
1439   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1440
1441   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1442       isa<ConstantSDNode>(N00.getOperand(1))) {
1443     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1444     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1445                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1446                                  N00.getOperand(0), N01),
1447                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1448                                  N00.getOperand(1), N01));
1449     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1450   }
1451
1452   return SDValue();
1453 }
1454
1455 SDValue DAGCombiner::visitADD(SDNode *N) {
1456   SDValue N0 = N->getOperand(0);
1457   SDValue N1 = N->getOperand(1);
1458   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1459   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1460   EVT VT = N0.getValueType();
1461
1462   // fold vector ops
1463   if (VT.isVector()) {
1464     SDValue FoldedVOp = SimplifyVBinOp(N);
1465     if (FoldedVOp.getNode()) return FoldedVOp;
1466
1467     // fold (add x, 0) -> x, vector edition
1468     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1469       return N0;
1470     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1471       return N1;
1472   }
1473
1474   // fold (add x, undef) -> undef
1475   if (N0.getOpcode() == ISD::UNDEF)
1476     return N0;
1477   if (N1.getOpcode() == ISD::UNDEF)
1478     return N1;
1479   // fold (add c1, c2) -> c1+c2
1480   if (N0C && N1C)
1481     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1482   // canonicalize constant to RHS
1483   if (N0C && !N1C)
1484     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1485   // fold (add x, 0) -> x
1486   if (N1C && N1C->isNullValue())
1487     return N0;
1488   // fold (add Sym, c) -> Sym+c
1489   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1490     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1491         GA->getOpcode() == ISD::GlobalAddress)
1492       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1493                                   GA->getOffset() +
1494                                     (uint64_t)N1C->getSExtValue());
1495   // fold ((c1-A)+c2) -> (c1+c2)-A
1496   if (N1C && N0.getOpcode() == ISD::SUB)
1497     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1498       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1499                          DAG.getConstant(N1C->getAPIntValue()+
1500                                          N0C->getAPIntValue(), VT),
1501                          N0.getOperand(1));
1502   // reassociate add
1503   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1504   if (RADD.getNode())
1505     return RADD;
1506   // fold ((0-A) + B) -> B-A
1507   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1508       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1509     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1510   // fold (A + (0-B)) -> A-B
1511   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1512       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1513     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1514   // fold (A+(B-A)) -> B
1515   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1516     return N1.getOperand(0);
1517   // fold ((B-A)+A) -> B
1518   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1519     return N0.getOperand(0);
1520   // fold (A+(B-(A+C))) to (B-C)
1521   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1522       N0 == N1.getOperand(1).getOperand(0))
1523     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1524                        N1.getOperand(1).getOperand(1));
1525   // fold (A+(B-(C+A))) to (B-C)
1526   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1527       N0 == N1.getOperand(1).getOperand(1))
1528     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1529                        N1.getOperand(1).getOperand(0));
1530   // fold (A+((B-A)+or-C)) to (B+or-C)
1531   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1532       N1.getOperand(0).getOpcode() == ISD::SUB &&
1533       N0 == N1.getOperand(0).getOperand(1))
1534     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1535                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1536
1537   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1538   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1539     SDValue N00 = N0.getOperand(0);
1540     SDValue N01 = N0.getOperand(1);
1541     SDValue N10 = N1.getOperand(0);
1542     SDValue N11 = N1.getOperand(1);
1543
1544     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1545       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1546                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1547                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1548   }
1549
1550   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1551     return SDValue(N, 0);
1552
1553   // fold (a+b) -> (a|b) iff a and b share no bits.
1554   if (VT.isInteger() && !VT.isVector()) {
1555     APInt LHSZero, LHSOne;
1556     APInt RHSZero, RHSOne;
1557     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1558
1559     if (LHSZero.getBoolValue()) {
1560       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1561
1562       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1563       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1564       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1565         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1566           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1567       }
1568     }
1569   }
1570
1571   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1572   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1573     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1574     if (Result.getNode()) return Result;
1575   }
1576   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1577     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1578     if (Result.getNode()) return Result;
1579   }
1580
1581   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1582   if (N1.getOpcode() == ISD::SHL &&
1583       N1.getOperand(0).getOpcode() == ISD::SUB)
1584     if (ConstantSDNode *C =
1585           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1586       if (C->getAPIntValue() == 0)
1587         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1588                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1589                                        N1.getOperand(0).getOperand(1),
1590                                        N1.getOperand(1)));
1591   if (N0.getOpcode() == ISD::SHL &&
1592       N0.getOperand(0).getOpcode() == ISD::SUB)
1593     if (ConstantSDNode *C =
1594           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1595       if (C->getAPIntValue() == 0)
1596         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1597                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1598                                        N0.getOperand(0).getOperand(1),
1599                                        N0.getOperand(1)));
1600
1601   if (N1.getOpcode() == ISD::AND) {
1602     SDValue AndOp0 = N1.getOperand(0);
1603     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1604     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1605     unsigned DestBits = VT.getScalarType().getSizeInBits();
1606
1607     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1608     // and similar xforms where the inner op is either ~0 or 0.
1609     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1610       SDLoc DL(N);
1611       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1612     }
1613   }
1614
1615   // add (sext i1), X -> sub X, (zext i1)
1616   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1617       N0.getOperand(0).getValueType() == MVT::i1 &&
1618       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1619     SDLoc DL(N);
1620     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1621     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1622   }
1623
1624   return SDValue();
1625 }
1626
1627 SDValue DAGCombiner::visitADDC(SDNode *N) {
1628   SDValue N0 = N->getOperand(0);
1629   SDValue N1 = N->getOperand(1);
1630   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1631   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1632   EVT VT = N0.getValueType();
1633
1634   // If the flag result is dead, turn this into an ADD.
1635   if (!N->hasAnyUseOfValue(1))
1636     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1637                      DAG.getNode(ISD::CARRY_FALSE,
1638                                  SDLoc(N), MVT::Glue));
1639
1640   // canonicalize constant to RHS.
1641   if (N0C && !N1C)
1642     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1643
1644   // fold (addc x, 0) -> x + no carry out
1645   if (N1C && N1C->isNullValue())
1646     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1647                                         SDLoc(N), MVT::Glue));
1648
1649   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1650   APInt LHSZero, LHSOne;
1651   APInt RHSZero, RHSOne;
1652   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1653
1654   if (LHSZero.getBoolValue()) {
1655     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1656
1657     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1658     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1659     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1660       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1661                        DAG.getNode(ISD::CARRY_FALSE,
1662                                    SDLoc(N), MVT::Glue));
1663   }
1664
1665   return SDValue();
1666 }
1667
1668 SDValue DAGCombiner::visitADDE(SDNode *N) {
1669   SDValue N0 = N->getOperand(0);
1670   SDValue N1 = N->getOperand(1);
1671   SDValue CarryIn = N->getOperand(2);
1672   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1673   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1674
1675   // canonicalize constant to RHS
1676   if (N0C && !N1C)
1677     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1678                        N1, N0, CarryIn);
1679
1680   // fold (adde x, y, false) -> (addc x, y)
1681   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1682     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1683
1684   return SDValue();
1685 }
1686
1687 // Since it may not be valid to emit a fold to zero for vector initializers
1688 // check if we can before folding.
1689 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1690                              SelectionDAG &DAG,
1691                              bool LegalOperations, bool LegalTypes) {
1692   if (!VT.isVector())
1693     return DAG.getConstant(0, VT);
1694   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1695     return DAG.getConstant(0, VT);
1696   return SDValue();
1697 }
1698
1699 SDValue DAGCombiner::visitSUB(SDNode *N) {
1700   SDValue N0 = N->getOperand(0);
1701   SDValue N1 = N->getOperand(1);
1702   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1703   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1704   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1705     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1706   EVT VT = N0.getValueType();
1707
1708   // fold vector ops
1709   if (VT.isVector()) {
1710     SDValue FoldedVOp = SimplifyVBinOp(N);
1711     if (FoldedVOp.getNode()) return FoldedVOp;
1712
1713     // fold (sub x, 0) -> x, vector edition
1714     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1715       return N0;
1716   }
1717
1718   // fold (sub x, x) -> 0
1719   // FIXME: Refactor this and xor and other similar operations together.
1720   if (N0 == N1)
1721     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1722   // fold (sub c1, c2) -> c1-c2
1723   if (N0C && N1C)
1724     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1725   // fold (sub x, c) -> (add x, -c)
1726   if (N1C)
1727     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1728                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1729   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1730   if (N0C && N0C->isAllOnesValue())
1731     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1732   // fold A-(A-B) -> B
1733   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1734     return N1.getOperand(1);
1735   // fold (A+B)-A -> B
1736   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1737     return N0.getOperand(1);
1738   // fold (A+B)-B -> A
1739   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1740     return N0.getOperand(0);
1741   // fold C2-(A+C1) -> (C2-C1)-A
1742   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1743     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1744                                    VT);
1745     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1746                        N1.getOperand(0));
1747   }
1748   // fold ((A+(B+or-C))-B) -> A+or-C
1749   if (N0.getOpcode() == ISD::ADD &&
1750       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1751        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1752       N0.getOperand(1).getOperand(0) == N1)
1753     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1754                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1755   // fold ((A+(C+B))-B) -> A+C
1756   if (N0.getOpcode() == ISD::ADD &&
1757       N0.getOperand(1).getOpcode() == ISD::ADD &&
1758       N0.getOperand(1).getOperand(1) == N1)
1759     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1760                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1761   // fold ((A-(B-C))-C) -> A-B
1762   if (N0.getOpcode() == ISD::SUB &&
1763       N0.getOperand(1).getOpcode() == ISD::SUB &&
1764       N0.getOperand(1).getOperand(1) == N1)
1765     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1766                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1767
1768   // If either operand of a sub is undef, the result is undef
1769   if (N0.getOpcode() == ISD::UNDEF)
1770     return N0;
1771   if (N1.getOpcode() == ISD::UNDEF)
1772     return N1;
1773
1774   // If the relocation model supports it, consider symbol offsets.
1775   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1776     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1777       // fold (sub Sym, c) -> Sym-c
1778       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1779         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1780                                     GA->getOffset() -
1781                                       (uint64_t)N1C->getSExtValue());
1782       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1783       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1784         if (GA->getGlobal() == GB->getGlobal())
1785           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1786                                  VT);
1787     }
1788
1789   return SDValue();
1790 }
1791
1792 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1793   SDValue N0 = N->getOperand(0);
1794   SDValue N1 = N->getOperand(1);
1795   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1796   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1797   EVT VT = N0.getValueType();
1798
1799   // If the flag result is dead, turn this into an SUB.
1800   if (!N->hasAnyUseOfValue(1))
1801     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1802                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1803                                  MVT::Glue));
1804
1805   // fold (subc x, x) -> 0 + no borrow
1806   if (N0 == N1)
1807     return CombineTo(N, DAG.getConstant(0, VT),
1808                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1809                                  MVT::Glue));
1810
1811   // fold (subc x, 0) -> x + no borrow
1812   if (N1C && N1C->isNullValue())
1813     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1814                                         MVT::Glue));
1815
1816   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1817   if (N0C && N0C->isAllOnesValue())
1818     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1819                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1820                                  MVT::Glue));
1821
1822   return SDValue();
1823 }
1824
1825 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1826   SDValue N0 = N->getOperand(0);
1827   SDValue N1 = N->getOperand(1);
1828   SDValue CarryIn = N->getOperand(2);
1829
1830   // fold (sube x, y, false) -> (subc x, y)
1831   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1832     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1833
1834   return SDValue();
1835 }
1836
1837 SDValue DAGCombiner::visitMUL(SDNode *N) {
1838   SDValue N0 = N->getOperand(0);
1839   SDValue N1 = N->getOperand(1);
1840   EVT VT = N0.getValueType();
1841
1842   // fold (mul x, undef) -> 0
1843   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1844     return DAG.getConstant(0, VT);
1845
1846   bool N0IsConst = false;
1847   bool N1IsConst = false;
1848   APInt ConstValue0, ConstValue1;
1849   // fold vector ops
1850   if (VT.isVector()) {
1851     SDValue FoldedVOp = SimplifyVBinOp(N);
1852     if (FoldedVOp.getNode()) return FoldedVOp;
1853
1854     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1855     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1856   } else {
1857     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1858     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1859                             : APInt();
1860     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1861     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1862                             : APInt();
1863   }
1864
1865   // fold (mul c1, c2) -> c1*c2
1866   if (N0IsConst && N1IsConst)
1867     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1868
1869   // canonicalize constant to RHS
1870   if (N0IsConst && !N1IsConst)
1871     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1872   // fold (mul x, 0) -> 0
1873   if (N1IsConst && ConstValue1 == 0)
1874     return N1;
1875   // We require a splat of the entire scalar bit width for non-contiguous
1876   // bit patterns.
1877   bool IsFullSplat =
1878     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1879   // fold (mul x, 1) -> x
1880   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1881     return N0;
1882   // fold (mul x, -1) -> 0-x
1883   if (N1IsConst && ConstValue1.isAllOnesValue())
1884     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1885                        DAG.getConstant(0, VT), N0);
1886   // fold (mul x, (1 << c)) -> x << c
1887   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1888     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1889                        DAG.getConstant(ConstValue1.logBase2(),
1890                                        getShiftAmountTy(N0.getValueType())));
1891   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1892   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1893     unsigned Log2Val = (-ConstValue1).logBase2();
1894     // FIXME: If the input is something that is easily negated (e.g. a
1895     // single-use add), we should put the negate there.
1896     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897                        DAG.getConstant(0, VT),
1898                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1899                             DAG.getConstant(Log2Val,
1900                                       getShiftAmountTy(N0.getValueType()))));
1901   }
1902
1903   APInt Val;
1904   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1905   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1906       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1907                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1908     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1909                              N1, N0.getOperand(1));
1910     AddToWorkList(C3.getNode());
1911     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1912                        N0.getOperand(0), C3);
1913   }
1914
1915   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1916   // use.
1917   {
1918     SDValue Sh(nullptr,0), Y(nullptr,0);
1919     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1920     if (N0.getOpcode() == ISD::SHL &&
1921         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1922                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1923         N0.getNode()->hasOneUse()) {
1924       Sh = N0; Y = N1;
1925     } else if (N1.getOpcode() == ISD::SHL &&
1926                isa<ConstantSDNode>(N1.getOperand(1)) &&
1927                N1.getNode()->hasOneUse()) {
1928       Sh = N1; Y = N0;
1929     }
1930
1931     if (Sh.getNode()) {
1932       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1933                                 Sh.getOperand(0), Y);
1934       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1935                          Mul, Sh.getOperand(1));
1936     }
1937   }
1938
1939   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1940   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1941       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1942                      isa<ConstantSDNode>(N0.getOperand(1))))
1943     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1944                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1945                                    N0.getOperand(0), N1),
1946                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1947                                    N0.getOperand(1), N1));
1948
1949   // reassociate mul
1950   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1951   if (RMUL.getNode())
1952     return RMUL;
1953
1954   return SDValue();
1955 }
1956
1957 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1958   SDValue N0 = N->getOperand(0);
1959   SDValue N1 = N->getOperand(1);
1960   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1961   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1962   EVT VT = N->getValueType(0);
1963
1964   // fold vector ops
1965   if (VT.isVector()) {
1966     SDValue FoldedVOp = SimplifyVBinOp(N);
1967     if (FoldedVOp.getNode()) return FoldedVOp;
1968   }
1969
1970   // fold (sdiv c1, c2) -> c1/c2
1971   if (N0C && N1C && !N1C->isNullValue())
1972     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1973   // fold (sdiv X, 1) -> X
1974   if (N1C && N1C->getAPIntValue() == 1LL)
1975     return N0;
1976   // fold (sdiv X, -1) -> 0-X
1977   if (N1C && N1C->isAllOnesValue())
1978     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979                        DAG.getConstant(0, VT), N0);
1980   // If we know the sign bits of both operands are zero, strength reduce to a
1981   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1982   if (!VT.isVector()) {
1983     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1984       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1985                          N0, N1);
1986   }
1987   // fold (sdiv X, pow2) -> simple ops after legalize
1988   if (N1C && !N1C->isNullValue() &&
1989       (N1C->getAPIntValue().isPowerOf2() ||
1990        (-N1C->getAPIntValue()).isPowerOf2())) {
1991     // If dividing by powers of two is cheap, then don't perform the following
1992     // fold.
1993     if (TLI.isPow2DivCheap())
1994       return SDValue();
1995
1996     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1997
1998     // Splat the sign bit into the register
1999     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2000                               DAG.getConstant(VT.getSizeInBits()-1,
2001                                        getShiftAmountTy(N0.getValueType())));
2002     AddToWorkList(SGN.getNode());
2003
2004     // Add (N0 < 0) ? abs2 - 1 : 0;
2005     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2006                               DAG.getConstant(VT.getSizeInBits() - lg2,
2007                                        getShiftAmountTy(SGN.getValueType())));
2008     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2009     AddToWorkList(SRL.getNode());
2010     AddToWorkList(ADD.getNode());    // Divide by pow2
2011     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2012                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2013
2014     // If we're dividing by a positive value, we're done.  Otherwise, we must
2015     // negate the result.
2016     if (N1C->getAPIntValue().isNonNegative())
2017       return SRA;
2018
2019     AddToWorkList(SRA.getNode());
2020     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2021                        DAG.getConstant(0, VT), SRA);
2022   }
2023
2024   // if integer divide is expensive and we satisfy the requirements, emit an
2025   // alternate sequence.
2026   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2027     SDValue Op = BuildSDIV(N);
2028     if (Op.getNode()) return Op;
2029   }
2030
2031   // undef / X -> 0
2032   if (N0.getOpcode() == ISD::UNDEF)
2033     return DAG.getConstant(0, VT);
2034   // X / undef -> undef
2035   if (N1.getOpcode() == ISD::UNDEF)
2036     return N1;
2037
2038   return SDValue();
2039 }
2040
2041 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2042   SDValue N0 = N->getOperand(0);
2043   SDValue N1 = N->getOperand(1);
2044   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2045   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2046   EVT VT = N->getValueType(0);
2047
2048   // fold vector ops
2049   if (VT.isVector()) {
2050     SDValue FoldedVOp = SimplifyVBinOp(N);
2051     if (FoldedVOp.getNode()) return FoldedVOp;
2052   }
2053
2054   // fold (udiv c1, c2) -> c1/c2
2055   if (N0C && N1C && !N1C->isNullValue())
2056     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2057   // fold (udiv x, (1 << c)) -> x >>u c
2058   if (N1C && N1C->getAPIntValue().isPowerOf2())
2059     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2060                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2061                                        getShiftAmountTy(N0.getValueType())));
2062   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2063   if (N1.getOpcode() == ISD::SHL) {
2064     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2065       if (SHC->getAPIntValue().isPowerOf2()) {
2066         EVT ADDVT = N1.getOperand(1).getValueType();
2067         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2068                                   N1.getOperand(1),
2069                                   DAG.getConstant(SHC->getAPIntValue()
2070                                                                   .logBase2(),
2071                                                   ADDVT));
2072         AddToWorkList(Add.getNode());
2073         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2074       }
2075     }
2076   }
2077   // fold (udiv x, c) -> alternate
2078   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2079     SDValue Op = BuildUDIV(N);
2080     if (Op.getNode()) return Op;
2081   }
2082
2083   // undef / X -> 0
2084   if (N0.getOpcode() == ISD::UNDEF)
2085     return DAG.getConstant(0, VT);
2086   // X / undef -> undef
2087   if (N1.getOpcode() == ISD::UNDEF)
2088     return N1;
2089
2090   return SDValue();
2091 }
2092
2093 SDValue DAGCombiner::visitSREM(SDNode *N) {
2094   SDValue N0 = N->getOperand(0);
2095   SDValue N1 = N->getOperand(1);
2096   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2097   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2098   EVT VT = N->getValueType(0);
2099
2100   // fold (srem c1, c2) -> c1%c2
2101   if (N0C && N1C && !N1C->isNullValue())
2102     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2103   // If we know the sign bits of both operands are zero, strength reduce to a
2104   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2105   if (!VT.isVector()) {
2106     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2107       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2108   }
2109
2110   // If X/C can be simplified by the division-by-constant logic, lower
2111   // X%C to the equivalent of X-X/C*C.
2112   if (N1C && !N1C->isNullValue()) {
2113     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2114     AddToWorkList(Div.getNode());
2115     SDValue OptimizedDiv = combine(Div.getNode());
2116     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2117       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2118                                 OptimizedDiv, N1);
2119       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2120       AddToWorkList(Mul.getNode());
2121       return Sub;
2122     }
2123   }
2124
2125   // undef % X -> 0
2126   if (N0.getOpcode() == ISD::UNDEF)
2127     return DAG.getConstant(0, VT);
2128   // X % undef -> undef
2129   if (N1.getOpcode() == ISD::UNDEF)
2130     return N1;
2131
2132   return SDValue();
2133 }
2134
2135 SDValue DAGCombiner::visitUREM(SDNode *N) {
2136   SDValue N0 = N->getOperand(0);
2137   SDValue N1 = N->getOperand(1);
2138   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2139   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2140   EVT VT = N->getValueType(0);
2141
2142   // fold (urem c1, c2) -> c1%c2
2143   if (N0C && N1C && !N1C->isNullValue())
2144     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2145   // fold (urem x, pow2) -> (and x, pow2-1)
2146   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2147     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2148                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2149   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2150   if (N1.getOpcode() == ISD::SHL) {
2151     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2152       if (SHC->getAPIntValue().isPowerOf2()) {
2153         SDValue Add =
2154           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2155                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2156                                  VT));
2157         AddToWorkList(Add.getNode());
2158         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2159       }
2160     }
2161   }
2162
2163   // If X/C can be simplified by the division-by-constant logic, lower
2164   // X%C to the equivalent of X-X/C*C.
2165   if (N1C && !N1C->isNullValue()) {
2166     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2167     AddToWorkList(Div.getNode());
2168     SDValue OptimizedDiv = combine(Div.getNode());
2169     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2170       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2171                                 OptimizedDiv, N1);
2172       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2173       AddToWorkList(Mul.getNode());
2174       return Sub;
2175     }
2176   }
2177
2178   // undef % X -> 0
2179   if (N0.getOpcode() == ISD::UNDEF)
2180     return DAG.getConstant(0, VT);
2181   // X % undef -> undef
2182   if (N1.getOpcode() == ISD::UNDEF)
2183     return N1;
2184
2185   return SDValue();
2186 }
2187
2188 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2189   SDValue N0 = N->getOperand(0);
2190   SDValue N1 = N->getOperand(1);
2191   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2192   EVT VT = N->getValueType(0);
2193   SDLoc DL(N);
2194
2195   // fold (mulhs x, 0) -> 0
2196   if (N1C && N1C->isNullValue())
2197     return N1;
2198   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2199   if (N1C && N1C->getAPIntValue() == 1)
2200     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2201                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2202                                        getShiftAmountTy(N0.getValueType())));
2203   // fold (mulhs x, undef) -> 0
2204   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2205     return DAG.getConstant(0, VT);
2206
2207   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2208   // plus a shift.
2209   if (VT.isSimple() && !VT.isVector()) {
2210     MVT Simple = VT.getSimpleVT();
2211     unsigned SimpleSize = Simple.getSizeInBits();
2212     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2213     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2214       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2215       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2216       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2217       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2218             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2219       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2220     }
2221   }
2222
2223   return SDValue();
2224 }
2225
2226 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2227   SDValue N0 = N->getOperand(0);
2228   SDValue N1 = N->getOperand(1);
2229   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2230   EVT VT = N->getValueType(0);
2231   SDLoc DL(N);
2232
2233   // fold (mulhu x, 0) -> 0
2234   if (N1C && N1C->isNullValue())
2235     return N1;
2236   // fold (mulhu x, 1) -> 0
2237   if (N1C && N1C->getAPIntValue() == 1)
2238     return DAG.getConstant(0, N0.getValueType());
2239   // fold (mulhu x, undef) -> 0
2240   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2241     return DAG.getConstant(0, VT);
2242
2243   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2244   // plus a shift.
2245   if (VT.isSimple() && !VT.isVector()) {
2246     MVT Simple = VT.getSimpleVT();
2247     unsigned SimpleSize = Simple.getSizeInBits();
2248     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2249     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2250       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2251       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2252       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2253       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2254             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2255       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2256     }
2257   }
2258
2259   return SDValue();
2260 }
2261
2262 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2263 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2264 /// that are being performed. Return true if a simplification was made.
2265 ///
2266 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2267                                                 unsigned HiOp) {
2268   // If the high half is not needed, just compute the low half.
2269   bool HiExists = N->hasAnyUseOfValue(1);
2270   if (!HiExists &&
2271       (!LegalOperations ||
2272        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2273     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2274                               N->op_begin(), N->getNumOperands());
2275     return CombineTo(N, Res, Res);
2276   }
2277
2278   // If the low half is not needed, just compute the high half.
2279   bool LoExists = N->hasAnyUseOfValue(0);
2280   if (!LoExists &&
2281       (!LegalOperations ||
2282        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2283     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2284                               N->op_begin(), N->getNumOperands());
2285     return CombineTo(N, Res, Res);
2286   }
2287
2288   // If both halves are used, return as it is.
2289   if (LoExists && HiExists)
2290     return SDValue();
2291
2292   // If the two computed results can be simplified separately, separate them.
2293   if (LoExists) {
2294     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2295                              N->op_begin(), N->getNumOperands());
2296     AddToWorkList(Lo.getNode());
2297     SDValue LoOpt = combine(Lo.getNode());
2298     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2299         (!LegalOperations ||
2300          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2301       return CombineTo(N, LoOpt, LoOpt);
2302   }
2303
2304   if (HiExists) {
2305     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2306                              N->op_begin(), N->getNumOperands());
2307     AddToWorkList(Hi.getNode());
2308     SDValue HiOpt = combine(Hi.getNode());
2309     if (HiOpt.getNode() && HiOpt != Hi &&
2310         (!LegalOperations ||
2311          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2312       return CombineTo(N, HiOpt, HiOpt);
2313   }
2314
2315   return SDValue();
2316 }
2317
2318 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2319   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2320   if (Res.getNode()) return Res;
2321
2322   EVT VT = N->getValueType(0);
2323   SDLoc DL(N);
2324
2325   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2326   // plus a shift.
2327   if (VT.isSimple() && !VT.isVector()) {
2328     MVT Simple = VT.getSimpleVT();
2329     unsigned SimpleSize = Simple.getSizeInBits();
2330     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2331     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2332       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2333       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2334       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2335       // Compute the high part as N1.
2336       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2337             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2338       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2339       // Compute the low part as N0.
2340       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2341       return CombineTo(N, Lo, Hi);
2342     }
2343   }
2344
2345   return SDValue();
2346 }
2347
2348 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2349   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2350   if (Res.getNode()) return Res;
2351
2352   EVT VT = N->getValueType(0);
2353   SDLoc DL(N);
2354
2355   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2356   // plus a shift.
2357   if (VT.isSimple() && !VT.isVector()) {
2358     MVT Simple = VT.getSimpleVT();
2359     unsigned SimpleSize = Simple.getSizeInBits();
2360     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2361     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2362       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2363       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2364       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2365       // Compute the high part as N1.
2366       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2367             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2368       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2369       // Compute the low part as N0.
2370       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2371       return CombineTo(N, Lo, Hi);
2372     }
2373   }
2374
2375   return SDValue();
2376 }
2377
2378 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2379   // (smulo x, 2) -> (saddo x, x)
2380   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2381     if (C2->getAPIntValue() == 2)
2382       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2383                          N->getOperand(0), N->getOperand(0));
2384
2385   return SDValue();
2386 }
2387
2388 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2389   // (umulo x, 2) -> (uaddo x, x)
2390   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2391     if (C2->getAPIntValue() == 2)
2392       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2393                          N->getOperand(0), N->getOperand(0));
2394
2395   return SDValue();
2396 }
2397
2398 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2399   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2400   if (Res.getNode()) return Res;
2401
2402   return SDValue();
2403 }
2404
2405 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2406   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2407   if (Res.getNode()) return Res;
2408
2409   return SDValue();
2410 }
2411
2412 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2413 /// two operands of the same opcode, try to simplify it.
2414 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2415   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2416   EVT VT = N0.getValueType();
2417   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2418
2419   // Bail early if none of these transforms apply.
2420   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2421
2422   // For each of OP in AND/OR/XOR:
2423   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2424   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2425   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2426   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2427   //
2428   // do not sink logical op inside of a vector extend, since it may combine
2429   // into a vsetcc.
2430   EVT Op0VT = N0.getOperand(0).getValueType();
2431   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2432        N0.getOpcode() == ISD::SIGN_EXTEND ||
2433        // Avoid infinite looping with PromoteIntBinOp.
2434        (N0.getOpcode() == ISD::ANY_EXTEND &&
2435         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2436        (N0.getOpcode() == ISD::TRUNCATE &&
2437         (!TLI.isZExtFree(VT, Op0VT) ||
2438          !TLI.isTruncateFree(Op0VT, VT)) &&
2439         TLI.isTypeLegal(Op0VT))) &&
2440       !VT.isVector() &&
2441       Op0VT == N1.getOperand(0).getValueType() &&
2442       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2443     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2444                                  N0.getOperand(0).getValueType(),
2445                                  N0.getOperand(0), N1.getOperand(0));
2446     AddToWorkList(ORNode.getNode());
2447     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2448   }
2449
2450   // For each of OP in SHL/SRL/SRA/AND...
2451   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2452   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2453   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2454   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2455        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2456       N0.getOperand(1) == N1.getOperand(1)) {
2457     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2458                                  N0.getOperand(0).getValueType(),
2459                                  N0.getOperand(0), N1.getOperand(0));
2460     AddToWorkList(ORNode.getNode());
2461     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2462                        ORNode, N0.getOperand(1));
2463   }
2464
2465   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2466   // Only perform this optimization after type legalization and before
2467   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2468   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2469   // we don't want to undo this promotion.
2470   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2471   // on scalars.
2472   if ((N0.getOpcode() == ISD::BITCAST ||
2473        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2474       Level == AfterLegalizeTypes) {
2475     SDValue In0 = N0.getOperand(0);
2476     SDValue In1 = N1.getOperand(0);
2477     EVT In0Ty = In0.getValueType();
2478     EVT In1Ty = In1.getValueType();
2479     SDLoc DL(N);
2480     // If both incoming values are integers, and the original types are the
2481     // same.
2482     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2483       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2484       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2485       AddToWorkList(Op.getNode());
2486       return BC;
2487     }
2488   }
2489
2490   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2491   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2492   // If both shuffles use the same mask, and both shuffle within a single
2493   // vector, then it is worthwhile to move the swizzle after the operation.
2494   // The type-legalizer generates this pattern when loading illegal
2495   // vector types from memory. In many cases this allows additional shuffle
2496   // optimizations.
2497   // There are other cases where moving the shuffle after the xor/and/or
2498   // is profitable even if shuffles don't perform a swizzle.
2499   // If both shuffles use the same mask, and both shuffles have the same first
2500   // or second operand, then it might still be profitable to move the shuffle
2501   // after the xor/and/or operation.
2502   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2503     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2504     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2505
2506     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2507            "Inputs to shuffles are not the same type");
2508  
2509     // Check that both shuffles use the same mask. The masks are known to be of
2510     // the same length because the result vector type is the same.
2511     // Check also that shuffles have only one use to avoid introducing extra
2512     // instructions.
2513     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2514         SVN0->getMask().equals(SVN1->getMask())) {
2515       SDValue ShOp = N0->getOperand(1);
2516
2517       // Don't try to fold this node if it requires introducing a
2518       // build vector of all zeros that might be illegal at this stage.
2519       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2520         if (!LegalTypes)
2521           ShOp = DAG.getConstant(0, VT);
2522         else
2523           ShOp = SDValue();
2524       }
2525
2526       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2527       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2528       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2529       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2530         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2531                                       N0->getOperand(0), N1->getOperand(0));
2532         AddToWorkList(NewNode.getNode());
2533         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2534                                     &SVN0->getMask()[0]);
2535       }
2536
2537       // Don't try to fold this node if it requires introducing a
2538       // build vector of all zeros that might be illegal at this stage.
2539       ShOp = N0->getOperand(0);
2540       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2541         if (!LegalTypes)
2542           ShOp = DAG.getConstant(0, VT);
2543         else
2544           ShOp = SDValue();
2545       }
2546
2547       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2548       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2549       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2550       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2551         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2552                                       N0->getOperand(1), N1->getOperand(1));
2553         AddToWorkList(NewNode.getNode());
2554         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2555                                     &SVN0->getMask()[0]);
2556       }
2557     }
2558   }
2559
2560   return SDValue();
2561 }
2562
2563 SDValue DAGCombiner::visitAND(SDNode *N) {
2564   SDValue N0 = N->getOperand(0);
2565   SDValue N1 = N->getOperand(1);
2566   SDValue LL, LR, RL, RR, CC0, CC1;
2567   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2568   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2569   EVT VT = N1.getValueType();
2570   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2571
2572   // fold vector ops
2573   if (VT.isVector()) {
2574     SDValue FoldedVOp = SimplifyVBinOp(N);
2575     if (FoldedVOp.getNode()) return FoldedVOp;
2576
2577     // fold (and x, 0) -> 0, vector edition
2578     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2579       return N0;
2580     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2581       return N1;
2582
2583     // fold (and x, -1) -> x, vector edition
2584     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2585       return N1;
2586     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2587       return N0;
2588   }
2589
2590   // fold (and x, undef) -> 0
2591   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2592     return DAG.getConstant(0, VT);
2593   // fold (and c1, c2) -> c1&c2
2594   if (N0C && N1C)
2595     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2596   // canonicalize constant to RHS
2597   if (N0C && !N1C)
2598     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2599   // fold (and x, -1) -> x
2600   if (N1C && N1C->isAllOnesValue())
2601     return N0;
2602   // if (and x, c) is known to be zero, return 0
2603   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2604                                    APInt::getAllOnesValue(BitWidth)))
2605     return DAG.getConstant(0, VT);
2606   // reassociate and
2607   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2608   if (RAND.getNode())
2609     return RAND;
2610   // fold (and (or x, C), D) -> D if (C & D) == D
2611   if (N1C && N0.getOpcode() == ISD::OR)
2612     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2613       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2614         return N1;
2615   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2616   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2617     SDValue N0Op0 = N0.getOperand(0);
2618     APInt Mask = ~N1C->getAPIntValue();
2619     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2620     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2621       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2622                                  N0.getValueType(), N0Op0);
2623
2624       // Replace uses of the AND with uses of the Zero extend node.
2625       CombineTo(N, Zext);
2626
2627       // We actually want to replace all uses of the any_extend with the
2628       // zero_extend, to avoid duplicating things.  This will later cause this
2629       // AND to be folded.
2630       CombineTo(N0.getNode(), Zext);
2631       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2632     }
2633   }
2634   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2635   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2636   // already be zero by virtue of the width of the base type of the load.
2637   //
2638   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2639   // more cases.
2640   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2641        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2642       N0.getOpcode() == ISD::LOAD) {
2643     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2644                                          N0 : N0.getOperand(0) );
2645
2646     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2647     // This can be a pure constant or a vector splat, in which case we treat the
2648     // vector as a scalar and use the splat value.
2649     APInt Constant = APInt::getNullValue(1);
2650     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2651       Constant = C->getAPIntValue();
2652     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2653       APInt SplatValue, SplatUndef;
2654       unsigned SplatBitSize;
2655       bool HasAnyUndefs;
2656       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2657                                              SplatBitSize, HasAnyUndefs);
2658       if (IsSplat) {
2659         // Undef bits can contribute to a possible optimisation if set, so
2660         // set them.
2661         SplatValue |= SplatUndef;
2662
2663         // The splat value may be something like "0x00FFFFFF", which means 0 for
2664         // the first vector value and FF for the rest, repeating. We need a mask
2665         // that will apply equally to all members of the vector, so AND all the
2666         // lanes of the constant together.
2667         EVT VT = Vector->getValueType(0);
2668         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2669
2670         // If the splat value has been compressed to a bitlength lower
2671         // than the size of the vector lane, we need to re-expand it to
2672         // the lane size.
2673         if (BitWidth > SplatBitSize)
2674           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2675                SplatBitSize < BitWidth;
2676                SplatBitSize = SplatBitSize * 2)
2677             SplatValue |= SplatValue.shl(SplatBitSize);
2678
2679         Constant = APInt::getAllOnesValue(BitWidth);
2680         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2681           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2682       }
2683     }
2684
2685     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2686     // actually legal and isn't going to get expanded, else this is a false
2687     // optimisation.
2688     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2689                                                     Load->getMemoryVT());
2690
2691     // Resize the constant to the same size as the original memory access before
2692     // extension. If it is still the AllOnesValue then this AND is completely
2693     // unneeded.
2694     Constant =
2695       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2696
2697     bool B;
2698     switch (Load->getExtensionType()) {
2699     default: B = false; break;
2700     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2701     case ISD::ZEXTLOAD:
2702     case ISD::NON_EXTLOAD: B = true; break;
2703     }
2704
2705     if (B && Constant.isAllOnesValue()) {
2706       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2707       // preserve semantics once we get rid of the AND.
2708       SDValue NewLoad(Load, 0);
2709       if (Load->getExtensionType() == ISD::EXTLOAD) {
2710         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2711                               Load->getValueType(0), SDLoc(Load),
2712                               Load->getChain(), Load->getBasePtr(),
2713                               Load->getOffset(), Load->getMemoryVT(),
2714                               Load->getMemOperand());
2715         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2716         if (Load->getNumValues() == 3) {
2717           // PRE/POST_INC loads have 3 values.
2718           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2719                            NewLoad.getValue(2) };
2720           CombineTo(Load, To, 3, true);
2721         } else {
2722           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2723         }
2724       }
2725
2726       // Fold the AND away, taking care not to fold to the old load node if we
2727       // replaced it.
2728       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2729
2730       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2731     }
2732   }
2733   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2734   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2735     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2736     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2737
2738     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2739         LL.getValueType().isInteger()) {
2740       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2741       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2742         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2743                                      LR.getValueType(), LL, RL);
2744         AddToWorkList(ORNode.getNode());
2745         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2746       }
2747       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2748       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2749         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2750                                       LR.getValueType(), LL, RL);
2751         AddToWorkList(ANDNode.getNode());
2752         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2753       }
2754       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2755       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2756         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2757                                      LR.getValueType(), LL, RL);
2758         AddToWorkList(ORNode.getNode());
2759         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2760       }
2761     }
2762     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2763     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2764         Op0 == Op1 && LL.getValueType().isInteger() &&
2765       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2766                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2767                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2768                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2769       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2770                                     LL, DAG.getConstant(1, LL.getValueType()));
2771       AddToWorkList(ADDNode.getNode());
2772       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2773                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2774     }
2775     // canonicalize equivalent to ll == rl
2776     if (LL == RR && LR == RL) {
2777       Op1 = ISD::getSetCCSwappedOperands(Op1);
2778       std::swap(RL, RR);
2779     }
2780     if (LL == RL && LR == RR) {
2781       bool isInteger = LL.getValueType().isInteger();
2782       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2783       if (Result != ISD::SETCC_INVALID &&
2784           (!LegalOperations ||
2785            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2786             TLI.isOperationLegal(ISD::SETCC,
2787                             getSetCCResultType(N0.getSimpleValueType())))))
2788         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2789                             LL, LR, Result);
2790     }
2791   }
2792
2793   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2794   if (N0.getOpcode() == N1.getOpcode()) {
2795     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2796     if (Tmp.getNode()) return Tmp;
2797   }
2798
2799   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2800   // fold (and (sra)) -> (and (srl)) when possible.
2801   if (!VT.isVector() &&
2802       SimplifyDemandedBits(SDValue(N, 0)))
2803     return SDValue(N, 0);
2804
2805   // fold (zext_inreg (extload x)) -> (zextload x)
2806   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2807     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2808     EVT MemVT = LN0->getMemoryVT();
2809     // If we zero all the possible extended bits, then we can turn this into
2810     // a zextload if we are running before legalize or the operation is legal.
2811     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2812     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2813                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2814         ((!LegalOperations && !LN0->isVolatile()) ||
2815          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2816       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2817                                        LN0->getChain(), LN0->getBasePtr(),
2818                                        MemVT, LN0->getMemOperand());
2819       AddToWorkList(N);
2820       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2821       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2822     }
2823   }
2824   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2825   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2826       N0.hasOneUse()) {
2827     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2828     EVT MemVT = LN0->getMemoryVT();
2829     // If we zero all the possible extended bits, then we can turn this into
2830     // a zextload if we are running before legalize or the operation is legal.
2831     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2832     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2833                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2834         ((!LegalOperations && !LN0->isVolatile()) ||
2835          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2836       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2837                                        LN0->getChain(), LN0->getBasePtr(),
2838                                        MemVT, LN0->getMemOperand());
2839       AddToWorkList(N);
2840       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2841       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2842     }
2843   }
2844
2845   // fold (and (load x), 255) -> (zextload x, i8)
2846   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2847   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2848   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2849               (N0.getOpcode() == ISD::ANY_EXTEND &&
2850                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2851     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2852     LoadSDNode *LN0 = HasAnyExt
2853       ? cast<LoadSDNode>(N0.getOperand(0))
2854       : cast<LoadSDNode>(N0);
2855     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2856         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2857       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2858       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2859         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2860         EVT LoadedVT = LN0->getMemoryVT();
2861
2862         if (ExtVT == LoadedVT &&
2863             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2864           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2865
2866           SDValue NewLoad =
2867             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2868                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2869                            LN0->getMemOperand());
2870           AddToWorkList(N);
2871           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2872           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2873         }
2874
2875         // Do not change the width of a volatile load.
2876         // Do not generate loads of non-round integer types since these can
2877         // be expensive (and would be wrong if the type is not byte sized).
2878         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2879             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2880           EVT PtrType = LN0->getOperand(1).getValueType();
2881
2882           unsigned Alignment = LN0->getAlignment();
2883           SDValue NewPtr = LN0->getBasePtr();
2884
2885           // For big endian targets, we need to add an offset to the pointer
2886           // to load the correct bytes.  For little endian systems, we merely
2887           // need to read fewer bytes from the same pointer.
2888           if (TLI.isBigEndian()) {
2889             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2890             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2891             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2892             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2893                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2894             Alignment = MinAlign(Alignment, PtrOff);
2895           }
2896
2897           AddToWorkList(NewPtr.getNode());
2898
2899           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2900           SDValue Load =
2901             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2902                            LN0->getChain(), NewPtr,
2903                            LN0->getPointerInfo(),
2904                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2905                            Alignment, LN0->getTBAAInfo());
2906           AddToWorkList(N);
2907           CombineTo(LN0, Load, Load.getValue(1));
2908           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2909         }
2910       }
2911     }
2912   }
2913
2914   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2915       VT.getSizeInBits() <= 64) {
2916     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2917       APInt ADDC = ADDI->getAPIntValue();
2918       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2919         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2920         // immediate for an add, but it is legal if its top c2 bits are set,
2921         // transform the ADD so the immediate doesn't need to be materialized
2922         // in a register.
2923         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2924           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2925                                              SRLI->getZExtValue());
2926           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2927             ADDC |= Mask;
2928             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2929               SDValue NewAdd =
2930                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2931                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2932               CombineTo(N0.getNode(), NewAdd);
2933               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2934             }
2935           }
2936         }
2937       }
2938     }
2939   }
2940
2941   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2942   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2943     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2944                                        N0.getOperand(1), false);
2945     if (BSwap.getNode())
2946       return BSwap;
2947   }
2948
2949   return SDValue();
2950 }
2951
2952 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2953 ///
2954 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2955                                         bool DemandHighBits) {
2956   if (!LegalOperations)
2957     return SDValue();
2958
2959   EVT VT = N->getValueType(0);
2960   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2961     return SDValue();
2962   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2963     return SDValue();
2964
2965   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2966   bool LookPassAnd0 = false;
2967   bool LookPassAnd1 = false;
2968   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2969       std::swap(N0, N1);
2970   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2971       std::swap(N0, N1);
2972   if (N0.getOpcode() == ISD::AND) {
2973     if (!N0.getNode()->hasOneUse())
2974       return SDValue();
2975     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2976     if (!N01C || N01C->getZExtValue() != 0xFF00)
2977       return SDValue();
2978     N0 = N0.getOperand(0);
2979     LookPassAnd0 = true;
2980   }
2981
2982   if (N1.getOpcode() == ISD::AND) {
2983     if (!N1.getNode()->hasOneUse())
2984       return SDValue();
2985     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2986     if (!N11C || N11C->getZExtValue() != 0xFF)
2987       return SDValue();
2988     N1 = N1.getOperand(0);
2989     LookPassAnd1 = true;
2990   }
2991
2992   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2993     std::swap(N0, N1);
2994   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2995     return SDValue();
2996   if (!N0.getNode()->hasOneUse() ||
2997       !N1.getNode()->hasOneUse())
2998     return SDValue();
2999
3000   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3001   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3002   if (!N01C || !N11C)
3003     return SDValue();
3004   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3005     return SDValue();
3006
3007   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3008   SDValue N00 = N0->getOperand(0);
3009   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3010     if (!N00.getNode()->hasOneUse())
3011       return SDValue();
3012     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3013     if (!N001C || N001C->getZExtValue() != 0xFF)
3014       return SDValue();
3015     N00 = N00.getOperand(0);
3016     LookPassAnd0 = true;
3017   }
3018
3019   SDValue N10 = N1->getOperand(0);
3020   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3021     if (!N10.getNode()->hasOneUse())
3022       return SDValue();
3023     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3024     if (!N101C || N101C->getZExtValue() != 0xFF00)
3025       return SDValue();
3026     N10 = N10.getOperand(0);
3027     LookPassAnd1 = true;
3028   }
3029
3030   if (N00 != N10)
3031     return SDValue();
3032
3033   // Make sure everything beyond the low halfword gets set to zero since the SRL
3034   // 16 will clear the top bits.
3035   unsigned OpSizeInBits = VT.getSizeInBits();
3036   if (DemandHighBits && OpSizeInBits > 16) {
3037     // If the left-shift isn't masked out then the only way this is a bswap is
3038     // if all bits beyond the low 8 are 0. In that case the entire pattern
3039     // reduces to a left shift anyway: leave it for other parts of the combiner.
3040     if (!LookPassAnd0)
3041       return SDValue();
3042
3043     // However, if the right shift isn't masked out then it might be because
3044     // it's not needed. See if we can spot that too.
3045     if (!LookPassAnd1 &&
3046         !DAG.MaskedValueIsZero(
3047             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3048       return SDValue();
3049   }
3050
3051   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3052   if (OpSizeInBits > 16)
3053     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3054                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3055   return Res;
3056 }
3057
3058 /// isBSwapHWordElement - Return true if the specified node is an element
3059 /// that makes up a 32-bit packed halfword byteswap. i.e.
3060 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3061 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3062   if (!N.getNode()->hasOneUse())
3063     return false;
3064
3065   unsigned Opc = N.getOpcode();
3066   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3067     return false;
3068
3069   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3070   if (!N1C)
3071     return false;
3072
3073   unsigned Num;
3074   switch (N1C->getZExtValue()) {
3075   default:
3076     return false;
3077   case 0xFF:       Num = 0; break;
3078   case 0xFF00:     Num = 1; break;
3079   case 0xFF0000:   Num = 2; break;
3080   case 0xFF000000: Num = 3; break;
3081   }
3082
3083   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3084   SDValue N0 = N.getOperand(0);
3085   if (Opc == ISD::AND) {
3086     if (Num == 0 || Num == 2) {
3087       // (x >> 8) & 0xff
3088       // (x >> 8) & 0xff0000
3089       if (N0.getOpcode() != ISD::SRL)
3090         return false;
3091       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3092       if (!C || C->getZExtValue() != 8)
3093         return false;
3094     } else {
3095       // (x << 8) & 0xff00
3096       // (x << 8) & 0xff000000
3097       if (N0.getOpcode() != ISD::SHL)
3098         return false;
3099       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3100       if (!C || C->getZExtValue() != 8)
3101         return false;
3102     }
3103   } else if (Opc == ISD::SHL) {
3104     // (x & 0xff) << 8
3105     // (x & 0xff0000) << 8
3106     if (Num != 0 && Num != 2)
3107       return false;
3108     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3109     if (!C || C->getZExtValue() != 8)
3110       return false;
3111   } else { // Opc == ISD::SRL
3112     // (x & 0xff00) >> 8
3113     // (x & 0xff000000) >> 8
3114     if (Num != 1 && Num != 3)
3115       return false;
3116     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3117     if (!C || C->getZExtValue() != 8)
3118       return false;
3119   }
3120
3121   if (Parts[Num])
3122     return false;
3123
3124   Parts[Num] = N0.getOperand(0).getNode();
3125   return true;
3126 }
3127
3128 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3129 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3130 /// => (rotl (bswap x), 16)
3131 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3132   if (!LegalOperations)
3133     return SDValue();
3134
3135   EVT VT = N->getValueType(0);
3136   if (VT != MVT::i32)
3137     return SDValue();
3138   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3139     return SDValue();
3140
3141   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3142   // Look for either
3143   // (or (or (and), (and)), (or (and), (and)))
3144   // (or (or (or (and), (and)), (and)), (and))
3145   if (N0.getOpcode() != ISD::OR)
3146     return SDValue();
3147   SDValue N00 = N0.getOperand(0);
3148   SDValue N01 = N0.getOperand(1);
3149
3150   if (N1.getOpcode() == ISD::OR &&
3151       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3152     // (or (or (and), (and)), (or (and), (and)))
3153     SDValue N000 = N00.getOperand(0);
3154     if (!isBSwapHWordElement(N000, Parts))
3155       return SDValue();
3156
3157     SDValue N001 = N00.getOperand(1);
3158     if (!isBSwapHWordElement(N001, Parts))
3159       return SDValue();
3160     SDValue N010 = N01.getOperand(0);
3161     if (!isBSwapHWordElement(N010, Parts))
3162       return SDValue();
3163     SDValue N011 = N01.getOperand(1);
3164     if (!isBSwapHWordElement(N011, Parts))
3165       return SDValue();
3166   } else {
3167     // (or (or (or (and), (and)), (and)), (and))
3168     if (!isBSwapHWordElement(N1, Parts))
3169       return SDValue();
3170     if (!isBSwapHWordElement(N01, Parts))
3171       return SDValue();
3172     if (N00.getOpcode() != ISD::OR)
3173       return SDValue();
3174     SDValue N000 = N00.getOperand(0);
3175     if (!isBSwapHWordElement(N000, Parts))
3176       return SDValue();
3177     SDValue N001 = N00.getOperand(1);
3178     if (!isBSwapHWordElement(N001, Parts))
3179       return SDValue();
3180   }
3181
3182   // Make sure the parts are all coming from the same node.
3183   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3184     return SDValue();
3185
3186   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3187                               SDValue(Parts[0],0));
3188
3189   // Result of the bswap should be rotated by 16. If it's not legal, then
3190   // do  (x << 16) | (x >> 16).
3191   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3192   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3193     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3194   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3195     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3196   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3197                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3198                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3199 }
3200
3201 SDValue DAGCombiner::visitOR(SDNode *N) {
3202   SDValue N0 = N->getOperand(0);
3203   SDValue N1 = N->getOperand(1);
3204   SDValue LL, LR, RL, RR, CC0, CC1;
3205   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3206   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3207   EVT VT = N1.getValueType();
3208
3209   // fold vector ops
3210   if (VT.isVector()) {
3211     SDValue FoldedVOp = SimplifyVBinOp(N);
3212     if (FoldedVOp.getNode()) return FoldedVOp;
3213
3214     // fold (or x, 0) -> x, vector edition
3215     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3216       return N1;
3217     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3218       return N0;
3219
3220     // fold (or x, -1) -> -1, vector edition
3221     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3222       return N0;
3223     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3224       return N1;
3225
3226     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3227     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3228     // Do this only if the resulting shuffle is legal.
3229     if (isa<ShuffleVectorSDNode>(N0) &&
3230         isa<ShuffleVectorSDNode>(N1) &&
3231         N0->getOperand(1) == N1->getOperand(1) &&
3232         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3233       bool CanFold = true;
3234       unsigned NumElts = VT.getVectorNumElements();
3235       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3236       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3237       // We construct two shuffle masks:
3238       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3239       // and N1 as the second operand.
3240       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3241       // and N0 as the second operand.
3242       // We do this because OR is commutable and therefore there might be
3243       // two ways to fold this node into a shuffle.
3244       SmallVector<int,4> Mask1;
3245       SmallVector<int,4> Mask2;
3246       
3247       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3248         int M0 = SV0->getMaskElt(i);
3249         int M1 = SV1->getMaskElt(i);
3250    
3251         // Both shuffle indexes are undef. Propagate Undef.
3252         if (M0 < 0 && M1 < 0) {
3253           Mask1.push_back(M0);
3254           Mask2.push_back(M0);
3255           continue;
3256         }
3257
3258         if (M0 < 0 || M1 < 0 ||
3259             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3260             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3261           CanFold = false;
3262           break;
3263         }
3264         
3265         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3266         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3267       }
3268
3269       if (CanFold) {
3270         // Fold this sequence only if the resulting shuffle is 'legal'.
3271         if (TLI.isShuffleMaskLegal(Mask1, VT))
3272           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3273                                       N1->getOperand(0), &Mask1[0]);
3274         if (TLI.isShuffleMaskLegal(Mask2, VT))
3275           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3276                                       N0->getOperand(0), &Mask2[0]);
3277       }
3278     }
3279   }
3280
3281   // fold (or x, undef) -> -1
3282   if (!LegalOperations &&
3283       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3284     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3285     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3286   }
3287   // fold (or c1, c2) -> c1|c2
3288   if (N0C && N1C)
3289     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3290   // canonicalize constant to RHS
3291   if (N0C && !N1C)
3292     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3293   // fold (or x, 0) -> x
3294   if (N1C && N1C->isNullValue())
3295     return N0;
3296   // fold (or x, -1) -> -1
3297   if (N1C && N1C->isAllOnesValue())
3298     return N1;
3299   // fold (or x, c) -> c iff (x & ~c) == 0
3300   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3301     return N1;
3302
3303   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3304   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3305   if (BSwap.getNode())
3306     return BSwap;
3307   BSwap = MatchBSwapHWordLow(N, N0, N1);
3308   if (BSwap.getNode())
3309     return BSwap;
3310
3311   // reassociate or
3312   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3313   if (ROR.getNode())
3314     return ROR;
3315   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3316   // iff (c1 & c2) == 0.
3317   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3318              isa<ConstantSDNode>(N0.getOperand(1))) {
3319     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3320     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3321       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3322       if (!COR.getNode())
3323         return SDValue();
3324       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3325                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3326                                      N0.getOperand(0), N1), COR);
3327     }
3328   }
3329   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3330   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3331     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3332     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3333
3334     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3335         LL.getValueType().isInteger()) {
3336       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3337       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3338       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3339           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3340         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3341                                      LR.getValueType(), LL, RL);
3342         AddToWorkList(ORNode.getNode());
3343         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3344       }
3345       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3346       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3347       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3348           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3349         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3350                                       LR.getValueType(), LL, RL);
3351         AddToWorkList(ANDNode.getNode());
3352         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3353       }
3354     }
3355     // canonicalize equivalent to ll == rl
3356     if (LL == RR && LR == RL) {
3357       Op1 = ISD::getSetCCSwappedOperands(Op1);
3358       std::swap(RL, RR);
3359     }
3360     if (LL == RL && LR == RR) {
3361       bool isInteger = LL.getValueType().isInteger();
3362       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3363       if (Result != ISD::SETCC_INVALID &&
3364           (!LegalOperations ||
3365            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3366             TLI.isOperationLegal(ISD::SETCC,
3367               getSetCCResultType(N0.getValueType())))))
3368         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3369                             LL, LR, Result);
3370     }
3371   }
3372
3373   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3374   if (N0.getOpcode() == N1.getOpcode()) {
3375     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3376     if (Tmp.getNode()) return Tmp;
3377   }
3378
3379   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3380   if (N0.getOpcode() == ISD::AND &&
3381       N1.getOpcode() == ISD::AND &&
3382       N0.getOperand(1).getOpcode() == ISD::Constant &&
3383       N1.getOperand(1).getOpcode() == ISD::Constant &&
3384       // Don't increase # computations.
3385       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3386     // We can only do this xform if we know that bits from X that are set in C2
3387     // but not in C1 are already zero.  Likewise for Y.
3388     const APInt &LHSMask =
3389       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3390     const APInt &RHSMask =
3391       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3392
3393     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3394         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3395       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3396                               N0.getOperand(0), N1.getOperand(0));
3397       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3398                          DAG.getConstant(LHSMask | RHSMask, VT));
3399     }
3400   }
3401
3402   // See if this is some rotate idiom.
3403   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3404     return SDValue(Rot, 0);
3405
3406   // Simplify the operands using demanded-bits information.
3407   if (!VT.isVector() &&
3408       SimplifyDemandedBits(SDValue(N, 0)))
3409     return SDValue(N, 0);
3410
3411   return SDValue();
3412 }
3413
3414 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3415 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3416   if (Op.getOpcode() == ISD::AND) {
3417     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3418       Mask = Op.getOperand(1);
3419       Op = Op.getOperand(0);
3420     } else {
3421       return false;
3422     }
3423   }
3424
3425   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3426     Shift = Op;
3427     return true;
3428   }
3429
3430   return false;
3431 }
3432
3433 // Return true if we can prove that, whenever Neg and Pos are both in the
3434 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3435 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3436 //
3437 //     (or (shift1 X, Neg), (shift2 X, Pos))
3438 //
3439 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3440 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3441 // to consider shift amounts with defined behavior.
3442 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3443   // If OpSize is a power of 2 then:
3444   //
3445   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3446   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3447   //
3448   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3449   // for the stronger condition:
3450   //
3451   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3452   //
3453   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3454   // we can just replace Neg with Neg' for the rest of the function.
3455   //
3456   // In other cases we check for the even stronger condition:
3457   //
3458   //     Neg == OpSize - Pos                                    [B]
3459   //
3460   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3461   // behavior if Pos == 0 (and consequently Neg == OpSize).
3462   //
3463   // We could actually use [A] whenever OpSize is a power of 2, but the
3464   // only extra cases that it would match are those uninteresting ones
3465   // where Neg and Pos are never in range at the same time.  E.g. for
3466   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3467   // as well as (sub 32, Pos), but:
3468   //
3469   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3470   //
3471   // always invokes undefined behavior for 32-bit X.
3472   //
3473   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3474   unsigned MaskLoBits = 0;
3475   if (Neg.getOpcode() == ISD::AND &&
3476       isPowerOf2_64(OpSize) &&
3477       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3478       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3479     Neg = Neg.getOperand(0);
3480     MaskLoBits = Log2_64(OpSize);
3481   }
3482
3483   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3484   if (Neg.getOpcode() != ISD::SUB)
3485     return 0;
3486   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3487   if (!NegC)
3488     return 0;
3489   SDValue NegOp1 = Neg.getOperand(1);
3490
3491   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3492   // Pos'.  The truncation is redundant for the purpose of the equality.
3493   if (MaskLoBits &&
3494       Pos.getOpcode() == ISD::AND &&
3495       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3496       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3497     Pos = Pos.getOperand(0);
3498
3499   // The condition we need is now:
3500   //
3501   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3502   //
3503   // If NegOp1 == Pos then we need:
3504   //
3505   //              OpSize & Mask == NegC & Mask
3506   //
3507   // (because "x & Mask" is a truncation and distributes through subtraction).
3508   APInt Width;
3509   if (Pos == NegOp1)
3510     Width = NegC->getAPIntValue();
3511   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3512   // Then the condition we want to prove becomes:
3513   //
3514   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3515   //
3516   // which, again because "x & Mask" is a truncation, becomes:
3517   //
3518   //                NegC & Mask == (OpSize - PosC) & Mask
3519   //              OpSize & Mask == (NegC + PosC) & Mask
3520   else if (Pos.getOpcode() == ISD::ADD &&
3521            Pos.getOperand(0) == NegOp1 &&
3522            Pos.getOperand(1).getOpcode() == ISD::Constant)
3523     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3524              NegC->getAPIntValue());
3525   else
3526     return false;
3527
3528   // Now we just need to check that OpSize & Mask == Width & Mask.
3529   if (MaskLoBits)
3530     // Opsize & Mask is 0 since Mask is Opsize - 1.
3531     return Width.getLoBits(MaskLoBits) == 0;
3532   return Width == OpSize;
3533 }
3534
3535 // A subroutine of MatchRotate used once we have found an OR of two opposite
3536 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3537 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3538 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3539 // Neg with outer conversions stripped away.
3540 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3541                                        SDValue Neg, SDValue InnerPos,
3542                                        SDValue InnerNeg, unsigned PosOpcode,
3543                                        unsigned NegOpcode, SDLoc DL) {
3544   // fold (or (shl x, (*ext y)),
3545   //          (srl x, (*ext (sub 32, y)))) ->
3546   //   (rotl x, y) or (rotr x, (sub 32, y))
3547   //
3548   // fold (or (shl x, (*ext (sub 32, y))),
3549   //          (srl x, (*ext y))) ->
3550   //   (rotr x, y) or (rotl x, (sub 32, y))
3551   EVT VT = Shifted.getValueType();
3552   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3553     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3554     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3555                        HasPos ? Pos : Neg).getNode();
3556   }
3557
3558   // fold (or (shl (*ext x), (*ext y)),
3559   //          (srl (*ext x), (*ext (sub 32, y)))) ->
3560   //   (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3561   //
3562   // fold (or (shl (*ext x), (*ext (sub 32, y))),
3563   //          (srl (*ext x), (*ext y))) ->
3564   //   (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3565   if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3566       Shifted.getOpcode() == ISD::ANY_EXTEND) {
3567     SDValue InnerShifted = Shifted.getOperand(0);
3568     EVT InnerVT = InnerShifted.getValueType();
3569     bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3570     if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3571       if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3572         SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3573                                 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3574         return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3575       }
3576     }
3577   }
3578
3579   return nullptr;
3580 }
3581
3582 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3583 // idioms for rotate, and if the target supports rotation instructions, generate
3584 // a rot[lr].
3585 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3586   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3587   EVT VT = LHS.getValueType();
3588   if (!TLI.isTypeLegal(VT)) return nullptr;
3589
3590   // The target must have at least one rotate flavor.
3591   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3592   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3593   if (!HasROTL && !HasROTR) return nullptr;
3594
3595   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3596   SDValue LHSShift;   // The shift.
3597   SDValue LHSMask;    // AND value if any.
3598   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3599     return nullptr; // Not part of a rotate.
3600
3601   SDValue RHSShift;   // The shift.
3602   SDValue RHSMask;    // AND value if any.
3603   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3604     return nullptr; // Not part of a rotate.
3605
3606   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3607     return nullptr;   // Not shifting the same value.
3608
3609   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3610     return nullptr;   // Shifts must disagree.
3611
3612   // Canonicalize shl to left side in a shl/srl pair.
3613   if (RHSShift.getOpcode() == ISD::SHL) {
3614     std::swap(LHS, RHS);
3615     std::swap(LHSShift, RHSShift);
3616     std::swap(LHSMask , RHSMask );
3617   }
3618
3619   unsigned OpSizeInBits = VT.getSizeInBits();
3620   SDValue LHSShiftArg = LHSShift.getOperand(0);
3621   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3622   SDValue RHSShiftArg = RHSShift.getOperand(0);
3623   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3624
3625   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3626   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3627   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3628       RHSShiftAmt.getOpcode() == ISD::Constant) {
3629     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3630     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3631     if ((LShVal + RShVal) != OpSizeInBits)
3632       return nullptr;
3633
3634     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3635                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3636
3637     // If there is an AND of either shifted operand, apply it to the result.
3638     if (LHSMask.getNode() || RHSMask.getNode()) {
3639       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3640
3641       if (LHSMask.getNode()) {
3642         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3643         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3644       }
3645       if (RHSMask.getNode()) {
3646         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3647         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3648       }
3649
3650       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3651     }
3652
3653     return Rot.getNode();
3654   }
3655
3656   // If there is a mask here, and we have a variable shift, we can't be sure
3657   // that we're masking out the right stuff.
3658   if (LHSMask.getNode() || RHSMask.getNode())
3659     return nullptr;
3660
3661   // If the shift amount is sign/zext/any-extended just peel it off.
3662   SDValue LExtOp0 = LHSShiftAmt;
3663   SDValue RExtOp0 = RHSShiftAmt;
3664   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3665        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3666        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3667        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3668       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3669        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3670        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3671        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3672     LExtOp0 = LHSShiftAmt.getOperand(0);
3673     RExtOp0 = RHSShiftAmt.getOperand(0);
3674   }
3675
3676   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3677                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3678   if (TryL)
3679     return TryL;
3680
3681   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3682                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3683   if (TryR)
3684     return TryR;
3685
3686   return nullptr;
3687 }
3688
3689 SDValue DAGCombiner::visitXOR(SDNode *N) {
3690   SDValue N0 = N->getOperand(0);
3691   SDValue N1 = N->getOperand(1);
3692   SDValue LHS, RHS, CC;
3693   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3694   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3695   EVT VT = N0.getValueType();
3696
3697   // fold vector ops
3698   if (VT.isVector()) {
3699     SDValue FoldedVOp = SimplifyVBinOp(N);
3700     if (FoldedVOp.getNode()) return FoldedVOp;
3701
3702     // fold (xor x, 0) -> x, vector edition
3703     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3704       return N1;
3705     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3706       return N0;
3707   }
3708
3709   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3710   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3711     return DAG.getConstant(0, VT);
3712   // fold (xor x, undef) -> undef
3713   if (N0.getOpcode() == ISD::UNDEF)
3714     return N0;
3715   if (N1.getOpcode() == ISD::UNDEF)
3716     return N1;
3717   // fold (xor c1, c2) -> c1^c2
3718   if (N0C && N1C)
3719     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3720   // canonicalize constant to RHS
3721   if (N0C && !N1C)
3722     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3723   // fold (xor x, 0) -> x
3724   if (N1C && N1C->isNullValue())
3725     return N0;
3726   // reassociate xor
3727   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3728   if (RXOR.getNode())
3729     return RXOR;
3730
3731   // fold !(x cc y) -> (x !cc y)
3732   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3733     bool isInt = LHS.getValueType().isInteger();
3734     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3735                                                isInt);
3736
3737     if (!LegalOperations ||
3738         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3739       switch (N0.getOpcode()) {
3740       default:
3741         llvm_unreachable("Unhandled SetCC Equivalent!");
3742       case ISD::SETCC:
3743         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3744       case ISD::SELECT_CC:
3745         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3746                                N0.getOperand(3), NotCC);
3747       }
3748     }
3749   }
3750
3751   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3752   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3753       N0.getNode()->hasOneUse() &&
3754       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3755     SDValue V = N0.getOperand(0);
3756     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3757                     DAG.getConstant(1, V.getValueType()));
3758     AddToWorkList(V.getNode());
3759     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3760   }
3761
3762   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3763   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3764       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3765     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3766     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3767       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3768       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3769       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3770       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3771       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3772     }
3773   }
3774   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3775   if (N1C && N1C->isAllOnesValue() &&
3776       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3777     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3778     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3779       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3780       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3781       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3782       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3783       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3784     }
3785   }
3786   // fold (xor (and x, y), y) -> (and (not x), y)
3787   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3788       N0->getOperand(1) == N1) {
3789     SDValue X = N0->getOperand(0);
3790     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3791     AddToWorkList(NotX.getNode());
3792     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3793   }
3794   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3795   if (N1C && N0.getOpcode() == ISD::XOR) {
3796     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3797     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3798     if (N00C)
3799       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3800                          DAG.getConstant(N1C->getAPIntValue() ^
3801                                          N00C->getAPIntValue(), VT));
3802     if (N01C)
3803       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3804                          DAG.getConstant(N1C->getAPIntValue() ^
3805                                          N01C->getAPIntValue(), VT));
3806   }
3807   // fold (xor x, x) -> 0
3808   if (N0 == N1)
3809     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3810
3811   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3812   if (N0.getOpcode() == N1.getOpcode()) {
3813     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3814     if (Tmp.getNode()) return Tmp;
3815   }
3816
3817   // Simplify the expression using non-local knowledge.
3818   if (!VT.isVector() &&
3819       SimplifyDemandedBits(SDValue(N, 0)))
3820     return SDValue(N, 0);
3821
3822   return SDValue();
3823 }
3824
3825 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3826 /// the shift amount is a constant.
3827 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3828   // We can't and shouldn't fold opaque constants.
3829   if (Amt->isOpaque())
3830     return SDValue();
3831
3832   SDNode *LHS = N->getOperand(0).getNode();
3833   if (!LHS->hasOneUse()) return SDValue();
3834
3835   // We want to pull some binops through shifts, so that we have (and (shift))
3836   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3837   // thing happens with address calculations, so it's important to canonicalize
3838   // it.
3839   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3840
3841   switch (LHS->getOpcode()) {
3842   default: return SDValue();
3843   case ISD::OR:
3844   case ISD::XOR:
3845     HighBitSet = false; // We can only transform sra if the high bit is clear.
3846     break;
3847   case ISD::AND:
3848     HighBitSet = true;  // We can only transform sra if the high bit is set.
3849     break;
3850   case ISD::ADD:
3851     if (N->getOpcode() != ISD::SHL)
3852       return SDValue(); // only shl(add) not sr[al](add).
3853     HighBitSet = false; // We can only transform sra if the high bit is clear.
3854     break;
3855   }
3856
3857   // We require the RHS of the binop to be a constant and not opaque as well.
3858   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3859   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3860
3861   // FIXME: disable this unless the input to the binop is a shift by a constant.
3862   // If it is not a shift, it pessimizes some common cases like:
3863   //
3864   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3865   //    int bar(int *X, int i) { return X[i & 255]; }
3866   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3867   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3868        BinOpLHSVal->getOpcode() != ISD::SRA &&
3869        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3870       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3871     return SDValue();
3872
3873   EVT VT = N->getValueType(0);
3874
3875   // If this is a signed shift right, and the high bit is modified by the
3876   // logical operation, do not perform the transformation. The highBitSet
3877   // boolean indicates the value of the high bit of the constant which would
3878   // cause it to be modified for this operation.
3879   if (N->getOpcode() == ISD::SRA) {
3880     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3881     if (BinOpRHSSignSet != HighBitSet)
3882       return SDValue();
3883   }
3884
3885   // Fold the constants, shifting the binop RHS by the shift amount.
3886   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3887                                N->getValueType(0),
3888                                LHS->getOperand(1), N->getOperand(1));
3889   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3890
3891   // Create the new shift.
3892   SDValue NewShift = DAG.getNode(N->getOpcode(),
3893                                  SDLoc(LHS->getOperand(0)),
3894                                  VT, LHS->getOperand(0), N->getOperand(1));
3895
3896   // Create the new binop.
3897   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3898 }
3899
3900 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3901   assert(N->getOpcode() == ISD::TRUNCATE);
3902   assert(N->getOperand(0).getOpcode() == ISD::AND);
3903
3904   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3905   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3906     SDValue N01 = N->getOperand(0).getOperand(1);
3907
3908     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3909       EVT TruncVT = N->getValueType(0);
3910       SDValue N00 = N->getOperand(0).getOperand(0);
3911       APInt TruncC = N01C->getAPIntValue();
3912       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3913
3914       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3915                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3916                          DAG.getConstant(TruncC, TruncVT));
3917     }
3918   }
3919
3920   return SDValue();
3921 }
3922
3923 SDValue DAGCombiner::visitRotate(SDNode *N) {
3924   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3925   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3926       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3927     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3928     if (NewOp1.getNode())
3929       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3930                          N->getOperand(0), NewOp1);
3931   }
3932   return SDValue();
3933 }
3934
3935 SDValue DAGCombiner::visitSHL(SDNode *N) {
3936   SDValue N0 = N->getOperand(0);
3937   SDValue N1 = N->getOperand(1);
3938   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3940   EVT VT = N0.getValueType();
3941   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3942
3943   // fold vector ops
3944   if (VT.isVector()) {
3945     SDValue FoldedVOp = SimplifyVBinOp(N);
3946     if (FoldedVOp.getNode()) return FoldedVOp;
3947
3948     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3949     // If setcc produces all-one true value then:
3950     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3951     if (N1CV && N1CV->isConstant()) {
3952       if (N0.getOpcode() == ISD::AND &&
3953           TLI.getBooleanContents(true) ==
3954           TargetLowering::ZeroOrNegativeOneBooleanContent) {
3955         SDValue N00 = N0->getOperand(0);
3956         SDValue N01 = N0->getOperand(1);
3957         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3958
3959         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3960           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3961           if (C.getNode())
3962             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3963         }
3964       } else {
3965         N1C = isConstOrConstSplat(N1);
3966       }
3967     }
3968   }
3969
3970   // fold (shl c1, c2) -> c1<<c2
3971   if (N0C && N1C)
3972     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3973   // fold (shl 0, x) -> 0
3974   if (N0C && N0C->isNullValue())
3975     return N0;
3976   // fold (shl x, c >= size(x)) -> undef
3977   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3978     return DAG.getUNDEF(VT);
3979   // fold (shl x, 0) -> x
3980   if (N1C && N1C->isNullValue())
3981     return N0;
3982   // fold (shl undef, x) -> 0
3983   if (N0.getOpcode() == ISD::UNDEF)
3984     return DAG.getConstant(0, VT);
3985   // if (shl x, c) is known to be zero, return 0
3986   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3987                             APInt::getAllOnesValue(OpSizeInBits)))
3988     return DAG.getConstant(0, VT);
3989   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3990   if (N1.getOpcode() == ISD::TRUNCATE &&
3991       N1.getOperand(0).getOpcode() == ISD::AND) {
3992     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3993     if (NewOp1.getNode())
3994       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3995   }
3996
3997   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3998     return SDValue(N, 0);
3999
4000   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4001   if (N1C && N0.getOpcode() == ISD::SHL) {
4002     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4003       uint64_t c1 = N0C1->getZExtValue();
4004       uint64_t c2 = N1C->getZExtValue();
4005       if (c1 + c2 >= OpSizeInBits)
4006         return DAG.getConstant(0, VT);
4007       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4008                          DAG.getConstant(c1 + c2, N1.getValueType()));
4009     }
4010   }
4011
4012   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4013   // For this to be valid, the second form must not preserve any of the bits
4014   // that are shifted out by the inner shift in the first form.  This means
4015   // the outer shift size must be >= the number of bits added by the ext.
4016   // As a corollary, we don't care what kind of ext it is.
4017   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4018               N0.getOpcode() == ISD::ANY_EXTEND ||
4019               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4020       N0.getOperand(0).getOpcode() == ISD::SHL) {
4021     SDValue N0Op0 = N0.getOperand(0);
4022     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4023       uint64_t c1 = N0Op0C1->getZExtValue();
4024       uint64_t c2 = N1C->getZExtValue();
4025       EVT InnerShiftVT = N0Op0.getValueType();
4026       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4027       if (c2 >= OpSizeInBits - InnerShiftSize) {
4028         if (c1 + c2 >= OpSizeInBits)
4029           return DAG.getConstant(0, VT);
4030         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4031                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4032                                        N0Op0->getOperand(0)),
4033                            DAG.getConstant(c1 + c2, N1.getValueType()));
4034       }
4035     }
4036   }
4037
4038   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4039   // Only fold this if the inner zext has no other uses to avoid increasing
4040   // the total number of instructions.
4041   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4042       N0.getOperand(0).getOpcode() == ISD::SRL) {
4043     SDValue N0Op0 = N0.getOperand(0);
4044     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4045       uint64_t c1 = N0Op0C1->getZExtValue();
4046       if (c1 < VT.getScalarSizeInBits()) {
4047         uint64_t c2 = N1C->getZExtValue();
4048         if (c1 == c2) {
4049           SDValue NewOp0 = N0.getOperand(0);
4050           EVT CountVT = NewOp0.getOperand(1).getValueType();
4051           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4052                                        NewOp0, DAG.getConstant(c2, CountVT));
4053           AddToWorkList(NewSHL.getNode());
4054           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4055         }
4056       }
4057     }
4058   }
4059
4060   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4061   //                               (and (srl x, (sub c1, c2), MASK)
4062   // Only fold this if the inner shift has no other uses -- if it does, folding
4063   // this will increase the total number of instructions.
4064   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4065     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4066       uint64_t c1 = N0C1->getZExtValue();
4067       if (c1 < OpSizeInBits) {
4068         uint64_t c2 = N1C->getZExtValue();
4069         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4070         SDValue Shift;
4071         if (c2 > c1) {
4072           Mask = Mask.shl(c2 - c1);
4073           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4074                               DAG.getConstant(c2 - c1, N1.getValueType()));
4075         } else {
4076           Mask = Mask.lshr(c1 - c2);
4077           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4078                               DAG.getConstant(c1 - c2, N1.getValueType()));
4079         }
4080         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4081                            DAG.getConstant(Mask, VT));
4082       }
4083     }
4084   }
4085   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4086   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4087     unsigned BitSize = VT.getScalarSizeInBits();
4088     SDValue HiBitsMask =
4089       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4090                                             BitSize - N1C->getZExtValue()), VT);
4091     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4092                        HiBitsMask);
4093   }
4094
4095   if (N1C) {
4096     SDValue NewSHL = visitShiftByConstant(N, N1C);
4097     if (NewSHL.getNode())
4098       return NewSHL;
4099   }
4100
4101   return SDValue();
4102 }
4103
4104 SDValue DAGCombiner::visitSRA(SDNode *N) {
4105   SDValue N0 = N->getOperand(0);
4106   SDValue N1 = N->getOperand(1);
4107   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4108   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4109   EVT VT = N0.getValueType();
4110   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4111
4112   // fold vector ops
4113   if (VT.isVector()) {
4114     SDValue FoldedVOp = SimplifyVBinOp(N);
4115     if (FoldedVOp.getNode()) return FoldedVOp;
4116
4117     N1C = isConstOrConstSplat(N1);
4118   }
4119
4120   // fold (sra c1, c2) -> (sra c1, c2)
4121   if (N0C && N1C)
4122     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4123   // fold (sra 0, x) -> 0
4124   if (N0C && N0C->isNullValue())
4125     return N0;
4126   // fold (sra -1, x) -> -1
4127   if (N0C && N0C->isAllOnesValue())
4128     return N0;
4129   // fold (sra x, (setge c, size(x))) -> undef
4130   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4131     return DAG.getUNDEF(VT);
4132   // fold (sra x, 0) -> x
4133   if (N1C && N1C->isNullValue())
4134     return N0;
4135   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4136   // sext_inreg.
4137   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4138     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4139     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4140     if (VT.isVector())
4141       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4142                                ExtVT, VT.getVectorNumElements());
4143     if ((!LegalOperations ||
4144          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4145       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4146                          N0.getOperand(0), DAG.getValueType(ExtVT));
4147   }
4148
4149   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4150   if (N1C && N0.getOpcode() == ISD::SRA) {
4151     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4152       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4153       if (Sum >= OpSizeInBits)
4154         Sum = OpSizeInBits - 1;
4155       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4156                          DAG.getConstant(Sum, N1.getValueType()));
4157     }
4158   }
4159
4160   // fold (sra (shl X, m), (sub result_size, n))
4161   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4162   // result_size - n != m.
4163   // If truncate is free for the target sext(shl) is likely to result in better
4164   // code.
4165   if (N0.getOpcode() == ISD::SHL && N1C) {
4166     // Get the two constanst of the shifts, CN0 = m, CN = n.
4167     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4168     if (N01C) {
4169       LLVMContext &Ctx = *DAG.getContext();
4170       // Determine what the truncate's result bitsize and type would be.
4171       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4172
4173       if (VT.isVector())
4174         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4175
4176       // Determine the residual right-shift amount.
4177       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4178
4179       // If the shift is not a no-op (in which case this should be just a sign
4180       // extend already), the truncated to type is legal, sign_extend is legal
4181       // on that type, and the truncate to that type is both legal and free,
4182       // perform the transform.
4183       if ((ShiftAmt > 0) &&
4184           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4185           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4186           TLI.isTruncateFree(VT, TruncVT)) {
4187
4188           SDValue Amt = DAG.getConstant(ShiftAmt,
4189               getShiftAmountTy(N0.getOperand(0).getValueType()));
4190           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4191                                       N0.getOperand(0), Amt);
4192           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4193                                       Shift);
4194           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4195                              N->getValueType(0), Trunc);
4196       }
4197     }
4198   }
4199
4200   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4201   if (N1.getOpcode() == ISD::TRUNCATE &&
4202       N1.getOperand(0).getOpcode() == ISD::AND) {
4203     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4204     if (NewOp1.getNode())
4205       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4206   }
4207
4208   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4209   //      if c1 is equal to the number of bits the trunc removes
4210   if (N0.getOpcode() == ISD::TRUNCATE &&
4211       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4212        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4213       N0.getOperand(0).hasOneUse() &&
4214       N0.getOperand(0).getOperand(1).hasOneUse() &&
4215       N1C) {
4216     SDValue N0Op0 = N0.getOperand(0);
4217     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4218       unsigned LargeShiftVal = LargeShift->getZExtValue();
4219       EVT LargeVT = N0Op0.getValueType();
4220
4221       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4222         SDValue Amt =
4223           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4224                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4225         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4226                                   N0Op0.getOperand(0), Amt);
4227         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4228       }
4229     }
4230   }
4231
4232   // Simplify, based on bits shifted out of the LHS.
4233   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4234     return SDValue(N, 0);
4235
4236
4237   // If the sign bit is known to be zero, switch this to a SRL.
4238   if (DAG.SignBitIsZero(N0))
4239     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4240
4241   if (N1C) {
4242     SDValue NewSRA = visitShiftByConstant(N, N1C);
4243     if (NewSRA.getNode())
4244       return NewSRA;
4245   }
4246
4247   return SDValue();
4248 }
4249
4250 SDValue DAGCombiner::visitSRL(SDNode *N) {
4251   SDValue N0 = N->getOperand(0);
4252   SDValue N1 = N->getOperand(1);
4253   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4254   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4255   EVT VT = N0.getValueType();
4256   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4257
4258   // fold vector ops
4259   if (VT.isVector()) {
4260     SDValue FoldedVOp = SimplifyVBinOp(N);
4261     if (FoldedVOp.getNode()) return FoldedVOp;
4262
4263     N1C = isConstOrConstSplat(N1);
4264   }
4265
4266   // fold (srl c1, c2) -> c1 >>u c2
4267   if (N0C && N1C)
4268     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4269   // fold (srl 0, x) -> 0
4270   if (N0C && N0C->isNullValue())
4271     return N0;
4272   // fold (srl x, c >= size(x)) -> undef
4273   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4274     return DAG.getUNDEF(VT);
4275   // fold (srl x, 0) -> x
4276   if (N1C && N1C->isNullValue())
4277     return N0;
4278   // if (srl x, c) is known to be zero, return 0
4279   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4280                                    APInt::getAllOnesValue(OpSizeInBits)))
4281     return DAG.getConstant(0, VT);
4282
4283   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4284   if (N1C && N0.getOpcode() == ISD::SRL) {
4285     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4286       uint64_t c1 = N01C->getZExtValue();
4287       uint64_t c2 = N1C->getZExtValue();
4288       if (c1 + c2 >= OpSizeInBits)
4289         return DAG.getConstant(0, VT);
4290       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4291                          DAG.getConstant(c1 + c2, N1.getValueType()));
4292     }
4293   }
4294
4295   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4296   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4297       N0.getOperand(0).getOpcode() == ISD::SRL &&
4298       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4299     uint64_t c1 =
4300       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4301     uint64_t c2 = N1C->getZExtValue();
4302     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4303     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4304     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4305     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4306     if (c1 + OpSizeInBits == InnerShiftSize) {
4307       if (c1 + c2 >= InnerShiftSize)
4308         return DAG.getConstant(0, VT);
4309       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4310                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4311                                      N0.getOperand(0)->getOperand(0),
4312                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4313     }
4314   }
4315
4316   // fold (srl (shl x, c), c) -> (and x, cst2)
4317   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4318     unsigned BitSize = N0.getScalarValueSizeInBits();
4319     if (BitSize <= 64) {
4320       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4321       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4322                          DAG.getConstant(~0ULL >> ShAmt, VT));
4323     }
4324   }
4325
4326   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4327   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4328     // Shifting in all undef bits?
4329     EVT SmallVT = N0.getOperand(0).getValueType();
4330     unsigned BitSize = SmallVT.getScalarSizeInBits();
4331     if (N1C->getZExtValue() >= BitSize)
4332       return DAG.getUNDEF(VT);
4333
4334     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4335       uint64_t ShiftAmt = N1C->getZExtValue();
4336       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4337                                        N0.getOperand(0),
4338                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4339       AddToWorkList(SmallShift.getNode());
4340       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4341       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4342                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4343                          DAG.getConstant(Mask, VT));
4344     }
4345   }
4346
4347   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4348   // bit, which is unmodified by sra.
4349   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4350     if (N0.getOpcode() == ISD::SRA)
4351       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4352   }
4353
4354   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4355   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4356       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4357     APInt KnownZero, KnownOne;
4358     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4359
4360     // If any of the input bits are KnownOne, then the input couldn't be all
4361     // zeros, thus the result of the srl will always be zero.
4362     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4363
4364     // If all of the bits input the to ctlz node are known to be zero, then
4365     // the result of the ctlz is "32" and the result of the shift is one.
4366     APInt UnknownBits = ~KnownZero;
4367     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4368
4369     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4370     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4371       // Okay, we know that only that the single bit specified by UnknownBits
4372       // could be set on input to the CTLZ node. If this bit is set, the SRL
4373       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4374       // to an SRL/XOR pair, which is likely to simplify more.
4375       unsigned ShAmt = UnknownBits.countTrailingZeros();
4376       SDValue Op = N0.getOperand(0);
4377
4378       if (ShAmt) {
4379         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4380                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4381         AddToWorkList(Op.getNode());
4382       }
4383
4384       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4385                          Op, DAG.getConstant(1, VT));
4386     }
4387   }
4388
4389   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4390   if (N1.getOpcode() == ISD::TRUNCATE &&
4391       N1.getOperand(0).getOpcode() == ISD::AND) {
4392     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4393     if (NewOp1.getNode())
4394       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4395   }
4396
4397   // fold operands of srl based on knowledge that the low bits are not
4398   // demanded.
4399   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4400     return SDValue(N, 0);
4401
4402   if (N1C) {
4403     SDValue NewSRL = visitShiftByConstant(N, N1C);
4404     if (NewSRL.getNode())
4405       return NewSRL;
4406   }
4407
4408   // Attempt to convert a srl of a load into a narrower zero-extending load.
4409   SDValue NarrowLoad = ReduceLoadWidth(N);
4410   if (NarrowLoad.getNode())
4411     return NarrowLoad;
4412
4413   // Here is a common situation. We want to optimize:
4414   //
4415   //   %a = ...
4416   //   %b = and i32 %a, 2
4417   //   %c = srl i32 %b, 1
4418   //   brcond i32 %c ...
4419   //
4420   // into
4421   //
4422   //   %a = ...
4423   //   %b = and %a, 2
4424   //   %c = setcc eq %b, 0
4425   //   brcond %c ...
4426   //
4427   // However when after the source operand of SRL is optimized into AND, the SRL
4428   // itself may not be optimized further. Look for it and add the BRCOND into
4429   // the worklist.
4430   if (N->hasOneUse()) {
4431     SDNode *Use = *N->use_begin();
4432     if (Use->getOpcode() == ISD::BRCOND)
4433       AddToWorkList(Use);
4434     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4435       // Also look pass the truncate.
4436       Use = *Use->use_begin();
4437       if (Use->getOpcode() == ISD::BRCOND)
4438         AddToWorkList(Use);
4439     }
4440   }
4441
4442   return SDValue();
4443 }
4444
4445 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4446   SDValue N0 = N->getOperand(0);
4447   EVT VT = N->getValueType(0);
4448
4449   // fold (ctlz c1) -> c2
4450   if (isa<ConstantSDNode>(N0))
4451     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4452   return SDValue();
4453 }
4454
4455 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4456   SDValue N0 = N->getOperand(0);
4457   EVT VT = N->getValueType(0);
4458
4459   // fold (ctlz_zero_undef c1) -> c2
4460   if (isa<ConstantSDNode>(N0))
4461     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4462   return SDValue();
4463 }
4464
4465 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4466   SDValue N0 = N->getOperand(0);
4467   EVT VT = N->getValueType(0);
4468
4469   // fold (cttz c1) -> c2
4470   if (isa<ConstantSDNode>(N0))
4471     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4472   return SDValue();
4473 }
4474
4475 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4476   SDValue N0 = N->getOperand(0);
4477   EVT VT = N->getValueType(0);
4478
4479   // fold (cttz_zero_undef c1) -> c2
4480   if (isa<ConstantSDNode>(N0))
4481     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4482   return SDValue();
4483 }
4484
4485 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4486   SDValue N0 = N->getOperand(0);
4487   EVT VT = N->getValueType(0);
4488
4489   // fold (ctpop c1) -> c2
4490   if (isa<ConstantSDNode>(N0))
4491     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4492   return SDValue();
4493 }
4494
4495 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4496   SDValue N0 = N->getOperand(0);
4497   SDValue N1 = N->getOperand(1);
4498   SDValue N2 = N->getOperand(2);
4499   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4500   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4501   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4502   EVT VT = N->getValueType(0);
4503   EVT VT0 = N0.getValueType();
4504
4505   // fold (select C, X, X) -> X
4506   if (N1 == N2)
4507     return N1;
4508   // fold (select true, X, Y) -> X
4509   if (N0C && !N0C->isNullValue())
4510     return N1;
4511   // fold (select false, X, Y) -> Y
4512   if (N0C && N0C->isNullValue())
4513     return N2;
4514   // fold (select C, 1, X) -> (or C, X)
4515   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4516     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4517   // fold (select C, 0, 1) -> (xor C, 1)
4518   if (VT.isInteger() &&
4519       (VT0 == MVT::i1 ||
4520        (VT0.isInteger() &&
4521         TLI.getBooleanContents(false) ==
4522         TargetLowering::ZeroOrOneBooleanContent)) &&
4523       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4524     SDValue XORNode;
4525     if (VT == VT0)
4526       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4527                          N0, DAG.getConstant(1, VT0));
4528     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4529                           N0, DAG.getConstant(1, VT0));
4530     AddToWorkList(XORNode.getNode());
4531     if (VT.bitsGT(VT0))
4532       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4533     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4534   }
4535   // fold (select C, 0, X) -> (and (not C), X)
4536   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4537     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4538     AddToWorkList(NOTNode.getNode());
4539     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4540   }
4541   // fold (select C, X, 1) -> (or (not C), X)
4542   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4543     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4544     AddToWorkList(NOTNode.getNode());
4545     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4546   }
4547   // fold (select C, X, 0) -> (and C, X)
4548   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4549     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4550   // fold (select X, X, Y) -> (or X, Y)
4551   // fold (select X, 1, Y) -> (or X, Y)
4552   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4553     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4554   // fold (select X, Y, X) -> (and X, Y)
4555   // fold (select X, Y, 0) -> (and X, Y)
4556   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4557     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4558
4559   // If we can fold this based on the true/false value, do so.
4560   if (SimplifySelectOps(N, N1, N2))
4561     return SDValue(N, 0);  // Don't revisit N.
4562
4563   // fold selects based on a setcc into other things, such as min/max/abs
4564   if (N0.getOpcode() == ISD::SETCC) {
4565     // FIXME:
4566     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4567     // having to say they don't support SELECT_CC on every type the DAG knows
4568     // about, since there is no way to mark an opcode illegal at all value types
4569     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4570         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4571       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4572                          N0.getOperand(0), N0.getOperand(1),
4573                          N1, N2, N0.getOperand(2));
4574     return SimplifySelect(SDLoc(N), N0, N1, N2);
4575   }
4576
4577   return SDValue();
4578 }
4579
4580 static
4581 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4582   SDLoc DL(N);
4583   EVT LoVT, HiVT;
4584   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4585
4586   // Split the inputs.
4587   SDValue Lo, Hi, LL, LH, RL, RH;
4588   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4589   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4590
4591   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4592   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4593
4594   return std::make_pair(Lo, Hi);
4595 }
4596
4597 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4598   SDValue N0 = N->getOperand(0);
4599   SDValue N1 = N->getOperand(1);
4600   SDValue N2 = N->getOperand(2);
4601   SDLoc DL(N);
4602
4603   // Canonicalize integer abs.
4604   // vselect (setg[te] X,  0),  X, -X ->
4605   // vselect (setgt    X, -1),  X, -X ->
4606   // vselect (setl[te] X,  0), -X,  X ->
4607   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4608   if (N0.getOpcode() == ISD::SETCC) {
4609     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4610     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4611     bool isAbs = false;
4612     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4613
4614     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4615          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4616         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4617       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4618     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4619              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4620       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4621
4622     if (isAbs) {
4623       EVT VT = LHS.getValueType();
4624       SDValue Shift = DAG.getNode(
4625           ISD::SRA, DL, VT, LHS,
4626           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4627       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4628       AddToWorkList(Shift.getNode());
4629       AddToWorkList(Add.getNode());
4630       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4631     }
4632   }
4633
4634   // If the VSELECT result requires splitting and the mask is provided by a
4635   // SETCC, then split both nodes and its operands before legalization. This
4636   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4637   // and enables future optimizations (e.g. min/max pattern matching on X86).
4638   if (N0.getOpcode() == ISD::SETCC) {
4639     EVT VT = N->getValueType(0);
4640
4641     // Check if any splitting is required.
4642     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4643         TargetLowering::TypeSplitVector)
4644       return SDValue();
4645
4646     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4647     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4648     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4649     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4650
4651     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4652     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4653
4654     // Add the new VSELECT nodes to the work list in case they need to be split
4655     // again.
4656     AddToWorkList(Lo.getNode());
4657     AddToWorkList(Hi.getNode());
4658
4659     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4660   }
4661
4662   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4663   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4664     return N1;
4665   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4666   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4667     return N2;
4668
4669   return SDValue();
4670 }
4671
4672 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4673   SDValue N0 = N->getOperand(0);
4674   SDValue N1 = N->getOperand(1);
4675   SDValue N2 = N->getOperand(2);
4676   SDValue N3 = N->getOperand(3);
4677   SDValue N4 = N->getOperand(4);
4678   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4679
4680   // fold select_cc lhs, rhs, x, x, cc -> x
4681   if (N2 == N3)
4682     return N2;
4683
4684   // Determine if the condition we're dealing with is constant
4685   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4686                               N0, N1, CC, SDLoc(N), false);
4687   if (SCC.getNode()) {
4688     AddToWorkList(SCC.getNode());
4689
4690     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4691       if (!SCCC->isNullValue())
4692         return N2;    // cond always true -> true val
4693       else
4694         return N3;    // cond always false -> false val
4695     }
4696
4697     // Fold to a simpler select_cc
4698     if (SCC.getOpcode() == ISD::SETCC)
4699       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4700                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4701                          SCC.getOperand(2));
4702   }
4703
4704   // If we can fold this based on the true/false value, do so.
4705   if (SimplifySelectOps(N, N2, N3))
4706     return SDValue(N, 0);  // Don't revisit N.
4707
4708   // fold select_cc into other things, such as min/max/abs
4709   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4710 }
4711
4712 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4713   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4714                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4715                        SDLoc(N));
4716 }
4717
4718 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4719 // dag node into a ConstantSDNode or a build_vector of constants.
4720 // This function is called by the DAGCombiner when visiting sext/zext/aext
4721 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND). 
4722 // Vector extends are not folded if operations are legal; this is to
4723 // avoid introducing illegal build_vector dag nodes.
4724 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4725                                          SelectionDAG &DAG, bool LegalTypes,
4726                                          bool LegalOperations) {
4727   unsigned Opcode = N->getOpcode();
4728   SDValue N0 = N->getOperand(0);
4729   EVT VT = N->getValueType(0);
4730
4731   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4732          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4733
4734   // fold (sext c1) -> c1
4735   // fold (zext c1) -> c1
4736   // fold (aext c1) -> c1
4737   if (isa<ConstantSDNode>(N0))
4738     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4739
4740   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4741   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4742   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4743   EVT SVT = VT.getScalarType();
4744   if (!(VT.isVector() &&
4745       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4746       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4747     return nullptr;
4748   
4749   // We can fold this node into a build_vector.
4750   unsigned VTBits = SVT.getSizeInBits();
4751   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4752   unsigned ShAmt = VTBits - EVTBits;
4753   SmallVector<SDValue, 8> Elts;
4754   unsigned NumElts = N0->getNumOperands();
4755   SDLoc DL(N);
4756
4757   for (unsigned i=0; i != NumElts; ++i) {
4758     SDValue Op = N0->getOperand(i);
4759     if (Op->getOpcode() == ISD::UNDEF) {
4760       Elts.push_back(DAG.getUNDEF(SVT));
4761       continue;
4762     }
4763
4764     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4765     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4766     if (Opcode == ISD::SIGN_EXTEND)
4767       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4768                                      SVT));
4769     else
4770       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4771                                      SVT));
4772   }
4773
4774   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4775 }
4776
4777 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4778 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4779 // transformation. Returns true if extension are possible and the above
4780 // mentioned transformation is profitable.
4781 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4782                                     unsigned ExtOpc,
4783                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4784                                     const TargetLowering &TLI) {
4785   bool HasCopyToRegUses = false;
4786   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4787   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4788                             UE = N0.getNode()->use_end();
4789        UI != UE; ++UI) {
4790     SDNode *User = *UI;
4791     if (User == N)
4792       continue;
4793     if (UI.getUse().getResNo() != N0.getResNo())
4794       continue;
4795     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4796     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4797       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4798       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4799         // Sign bits will be lost after a zext.
4800         return false;
4801       bool Add = false;
4802       for (unsigned i = 0; i != 2; ++i) {
4803         SDValue UseOp = User->getOperand(i);
4804         if (UseOp == N0)
4805           continue;
4806         if (!isa<ConstantSDNode>(UseOp))
4807           return false;
4808         Add = true;
4809       }
4810       if (Add)
4811         ExtendNodes.push_back(User);
4812       continue;
4813     }
4814     // If truncates aren't free and there are users we can't
4815     // extend, it isn't worthwhile.
4816     if (!isTruncFree)
4817       return false;
4818     // Remember if this value is live-out.
4819     if (User->getOpcode() == ISD::CopyToReg)
4820       HasCopyToRegUses = true;
4821   }
4822
4823   if (HasCopyToRegUses) {
4824     bool BothLiveOut = false;
4825     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4826          UI != UE; ++UI) {
4827       SDUse &Use = UI.getUse();
4828       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4829         BothLiveOut = true;
4830         break;
4831       }
4832     }
4833     if (BothLiveOut)
4834       // Both unextended and extended values are live out. There had better be
4835       // a good reason for the transformation.
4836       return ExtendNodes.size();
4837   }
4838   return true;
4839 }
4840
4841 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4842                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4843                                   ISD::NodeType ExtType) {
4844   // Extend SetCC uses if necessary.
4845   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4846     SDNode *SetCC = SetCCs[i];
4847     SmallVector<SDValue, 4> Ops;
4848
4849     for (unsigned j = 0; j != 2; ++j) {
4850       SDValue SOp = SetCC->getOperand(j);
4851       if (SOp == Trunc)
4852         Ops.push_back(ExtLoad);
4853       else
4854         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4855     }
4856
4857     Ops.push_back(SetCC->getOperand(2));
4858     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4859                                  &Ops[0], Ops.size()));
4860   }
4861 }
4862
4863 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4864   SDValue N0 = N->getOperand(0);
4865   EVT VT = N->getValueType(0);
4866
4867   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4868                                               LegalOperations))
4869     return SDValue(Res, 0);
4870
4871   // fold (sext (sext x)) -> (sext x)
4872   // fold (sext (aext x)) -> (sext x)
4873   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4874     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4875                        N0.getOperand(0));
4876
4877   if (N0.getOpcode() == ISD::TRUNCATE) {
4878     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4879     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4880     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4881     if (NarrowLoad.getNode()) {
4882       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4883       if (NarrowLoad.getNode() != N0.getNode()) {
4884         CombineTo(N0.getNode(), NarrowLoad);
4885         // CombineTo deleted the truncate, if needed, but not what's under it.
4886         AddToWorkList(oye);
4887       }
4888       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4889     }
4890
4891     // See if the value being truncated is already sign extended.  If so, just
4892     // eliminate the trunc/sext pair.
4893     SDValue Op = N0.getOperand(0);
4894     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4895     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4896     unsigned DestBits = VT.getScalarType().getSizeInBits();
4897     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4898
4899     if (OpBits == DestBits) {
4900       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4901       // bits, it is already ready.
4902       if (NumSignBits > DestBits-MidBits)
4903         return Op;
4904     } else if (OpBits < DestBits) {
4905       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4906       // bits, just sext from i32.
4907       if (NumSignBits > OpBits-MidBits)
4908         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4909     } else {
4910       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4911       // bits, just truncate to i32.
4912       if (NumSignBits > OpBits-MidBits)
4913         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4914     }
4915
4916     // fold (sext (truncate x)) -> (sextinreg x).
4917     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4918                                                  N0.getValueType())) {
4919       if (OpBits < DestBits)
4920         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4921       else if (OpBits > DestBits)
4922         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4923       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4924                          DAG.getValueType(N0.getValueType()));
4925     }
4926   }
4927
4928   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4929   // None of the supported targets knows how to perform load and sign extend
4930   // on vectors in one instruction.  We only perform this transformation on
4931   // scalars.
4932   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4933       ISD::isUNINDEXEDLoad(N0.getNode()) &&
4934       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4935        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4936     bool DoXform = true;
4937     SmallVector<SDNode*, 4> SetCCs;
4938     if (!N0.hasOneUse())
4939       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4940     if (DoXform) {
4941       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4942       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4943                                        LN0->getChain(),
4944                                        LN0->getBasePtr(), N0.getValueType(),
4945                                        LN0->getMemOperand());
4946       CombineTo(N, ExtLoad);
4947       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4948                                   N0.getValueType(), ExtLoad);
4949       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4950       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4951                       ISD::SIGN_EXTEND);
4952       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4953     }
4954   }
4955
4956   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4957   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4958   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4959       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4960     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4961     EVT MemVT = LN0->getMemoryVT();
4962     if ((!LegalOperations && !LN0->isVolatile()) ||
4963         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4964       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4965                                        LN0->getChain(),
4966                                        LN0->getBasePtr(), MemVT,
4967                                        LN0->getMemOperand());
4968       CombineTo(N, ExtLoad);
4969       CombineTo(N0.getNode(),
4970                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4971                             N0.getValueType(), ExtLoad),
4972                 ExtLoad.getValue(1));
4973       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4974     }
4975   }
4976
4977   // fold (sext (and/or/xor (load x), cst)) ->
4978   //      (and/or/xor (sextload x), (sext cst))
4979   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4980        N0.getOpcode() == ISD::XOR) &&
4981       isa<LoadSDNode>(N0.getOperand(0)) &&
4982       N0.getOperand(1).getOpcode() == ISD::Constant &&
4983       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4984       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4985     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4986     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
4987       bool DoXform = true;
4988       SmallVector<SDNode*, 4> SetCCs;
4989       if (!N0.hasOneUse())
4990         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4991                                           SetCCs, TLI);
4992       if (DoXform) {
4993         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4994                                          LN0->getChain(), LN0->getBasePtr(),
4995                                          LN0->getMemoryVT(),
4996                                          LN0->getMemOperand());
4997         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4998         Mask = Mask.sext(VT.getSizeInBits());
4999         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5000                                   ExtLoad, DAG.getConstant(Mask, VT));
5001         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5002                                     SDLoc(N0.getOperand(0)),
5003                                     N0.getOperand(0).getValueType(), ExtLoad);
5004         CombineTo(N, And);
5005         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5006         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5007                         ISD::SIGN_EXTEND);
5008         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5009       }
5010     }
5011   }
5012
5013   if (N0.getOpcode() == ISD::SETCC) {
5014     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5015     // Only do this before legalize for now.
5016     if (VT.isVector() && !LegalOperations &&
5017         TLI.getBooleanContents(true) ==
5018           TargetLowering::ZeroOrNegativeOneBooleanContent) {
5019       EVT N0VT = N0.getOperand(0).getValueType();
5020       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5021       // of the same size as the compared operands. Only optimize sext(setcc())
5022       // if this is the case.
5023       EVT SVT = getSetCCResultType(N0VT);
5024
5025       // We know that the # elements of the results is the same as the
5026       // # elements of the compare (and the # elements of the compare result
5027       // for that matter).  Check to see that they are the same size.  If so,
5028       // we know that the element size of the sext'd result matches the
5029       // element size of the compare operands.
5030       if (VT.getSizeInBits() == SVT.getSizeInBits())
5031         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5032                              N0.getOperand(1),
5033                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5034
5035       // If the desired elements are smaller or larger than the source
5036       // elements we can use a matching integer vector type and then
5037       // truncate/sign extend
5038       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5039       if (SVT == MatchingVectorType) {
5040         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5041                                N0.getOperand(0), N0.getOperand(1),
5042                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5043         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5044       }
5045     }
5046
5047     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5048     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5049     SDValue NegOne =
5050       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5051     SDValue SCC =
5052       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5053                        NegOne, DAG.getConstant(0, VT),
5054                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5055     if (SCC.getNode()) return SCC;
5056
5057     if (!VT.isVector()) {
5058       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5059       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5060         SDLoc DL(N);
5061         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5062         SDValue SetCC = DAG.getSetCC(DL,
5063                                      SetCCVT,
5064                                      N0.getOperand(0), N0.getOperand(1), CC);
5065         EVT SelectVT = getSetCCResultType(VT);
5066         return DAG.getSelect(DL, VT,
5067                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5068                              NegOne, DAG.getConstant(0, VT));
5069
5070       }
5071     }
5072   }
5073
5074   // fold (sext x) -> (zext x) if the sign bit is known zero.
5075   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5076       DAG.SignBitIsZero(N0))
5077     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5078
5079   return SDValue();
5080 }
5081
5082 // isTruncateOf - If N is a truncate of some other value, return true, record
5083 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5084 // This function computes KnownZero to avoid a duplicated call to
5085 // ComputeMaskedBits in the caller.
5086 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5087                          APInt &KnownZero) {
5088   APInt KnownOne;
5089   if (N->getOpcode() == ISD::TRUNCATE) {
5090     Op = N->getOperand(0);
5091     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5092     return true;
5093   }
5094
5095   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5096       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5097     return false;
5098
5099   SDValue Op0 = N->getOperand(0);
5100   SDValue Op1 = N->getOperand(1);
5101   assert(Op0.getValueType() == Op1.getValueType());
5102
5103   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5104   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5105   if (COp0 && COp0->isNullValue())
5106     Op = Op1;
5107   else if (COp1 && COp1->isNullValue())
5108     Op = Op0;
5109   else
5110     return false;
5111
5112   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5113
5114   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5115     return false;
5116
5117   return true;
5118 }
5119
5120 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5121   SDValue N0 = N->getOperand(0);
5122   EVT VT = N->getValueType(0);
5123
5124   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5125                                               LegalOperations))
5126     return SDValue(Res, 0);
5127
5128   // fold (zext (zext x)) -> (zext x)
5129   // fold (zext (aext x)) -> (zext x)
5130   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5131     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5132                        N0.getOperand(0));
5133
5134   // fold (zext (truncate x)) -> (zext x) or
5135   //      (zext (truncate x)) -> (truncate x)
5136   // This is valid when the truncated bits of x are already zero.
5137   // FIXME: We should extend this to work for vectors too.
5138   SDValue Op;
5139   APInt KnownZero;
5140   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5141     APInt TruncatedBits =
5142       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5143       APInt(Op.getValueSizeInBits(), 0) :
5144       APInt::getBitsSet(Op.getValueSizeInBits(),
5145                         N0.getValueSizeInBits(),
5146                         std::min(Op.getValueSizeInBits(),
5147                                  VT.getSizeInBits()));
5148     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5149       if (VT.bitsGT(Op.getValueType()))
5150         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5151       if (VT.bitsLT(Op.getValueType()))
5152         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5153
5154       return Op;
5155     }
5156   }
5157
5158   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5159   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5160   if (N0.getOpcode() == ISD::TRUNCATE) {
5161     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5162     if (NarrowLoad.getNode()) {
5163       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5164       if (NarrowLoad.getNode() != N0.getNode()) {
5165         CombineTo(N0.getNode(), NarrowLoad);
5166         // CombineTo deleted the truncate, if needed, but not what's under it.
5167         AddToWorkList(oye);
5168       }
5169       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5170     }
5171   }
5172
5173   // fold (zext (truncate x)) -> (and x, mask)
5174   if (N0.getOpcode() == ISD::TRUNCATE &&
5175       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5176
5177     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5178     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5179     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5180     if (NarrowLoad.getNode()) {
5181       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5182       if (NarrowLoad.getNode() != N0.getNode()) {
5183         CombineTo(N0.getNode(), NarrowLoad);
5184         // CombineTo deleted the truncate, if needed, but not what's under it.
5185         AddToWorkList(oye);
5186       }
5187       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5188     }
5189
5190     SDValue Op = N0.getOperand(0);
5191     if (Op.getValueType().bitsLT(VT)) {
5192       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5193       AddToWorkList(Op.getNode());
5194     } else if (Op.getValueType().bitsGT(VT)) {
5195       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5196       AddToWorkList(Op.getNode());
5197     }
5198     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5199                                   N0.getValueType().getScalarType());
5200   }
5201
5202   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5203   // if either of the casts is not free.
5204   if (N0.getOpcode() == ISD::AND &&
5205       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5206       N0.getOperand(1).getOpcode() == ISD::Constant &&
5207       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5208                            N0.getValueType()) ||
5209        !TLI.isZExtFree(N0.getValueType(), VT))) {
5210     SDValue X = N0.getOperand(0).getOperand(0);
5211     if (X.getValueType().bitsLT(VT)) {
5212       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5213     } else if (X.getValueType().bitsGT(VT)) {
5214       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5215     }
5216     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5217     Mask = Mask.zext(VT.getSizeInBits());
5218     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5219                        X, DAG.getConstant(Mask, VT));
5220   }
5221
5222   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5223   // None of the supported targets knows how to perform load and vector_zext
5224   // on vectors in one instruction.  We only perform this transformation on
5225   // scalars.
5226   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5227       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5228       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5229        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5230     bool DoXform = true;
5231     SmallVector<SDNode*, 4> SetCCs;
5232     if (!N0.hasOneUse())
5233       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5234     if (DoXform) {
5235       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5236       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5237                                        LN0->getChain(),
5238                                        LN0->getBasePtr(), N0.getValueType(),
5239                                        LN0->getMemOperand());
5240       CombineTo(N, ExtLoad);
5241       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5242                                   N0.getValueType(), ExtLoad);
5243       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5244
5245       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5246                       ISD::ZERO_EXTEND);
5247       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5248     }
5249   }
5250
5251   // fold (zext (and/or/xor (load x), cst)) ->
5252   //      (and/or/xor (zextload x), (zext cst))
5253   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5254        N0.getOpcode() == ISD::XOR) &&
5255       isa<LoadSDNode>(N0.getOperand(0)) &&
5256       N0.getOperand(1).getOpcode() == ISD::Constant &&
5257       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5258       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5259     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5260     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5261       bool DoXform = true;
5262       SmallVector<SDNode*, 4> SetCCs;
5263       if (!N0.hasOneUse())
5264         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5265                                           SetCCs, TLI);
5266       if (DoXform) {
5267         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5268                                          LN0->getChain(), LN0->getBasePtr(),
5269                                          LN0->getMemoryVT(),
5270                                          LN0->getMemOperand());
5271         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5272         Mask = Mask.zext(VT.getSizeInBits());
5273         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5274                                   ExtLoad, DAG.getConstant(Mask, VT));
5275         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5276                                     SDLoc(N0.getOperand(0)),
5277                                     N0.getOperand(0).getValueType(), ExtLoad);
5278         CombineTo(N, And);
5279         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5280         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5281                         ISD::ZERO_EXTEND);
5282         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5283       }
5284     }
5285   }
5286
5287   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5288   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5289   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5290       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5291     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5292     EVT MemVT = LN0->getMemoryVT();
5293     if ((!LegalOperations && !LN0->isVolatile()) ||
5294         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5295       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5296                                        LN0->getChain(),
5297                                        LN0->getBasePtr(), MemVT,
5298                                        LN0->getMemOperand());
5299       CombineTo(N, ExtLoad);
5300       CombineTo(N0.getNode(),
5301                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5302                             ExtLoad),
5303                 ExtLoad.getValue(1));
5304       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5305     }
5306   }
5307
5308   if (N0.getOpcode() == ISD::SETCC) {
5309     if (!LegalOperations && VT.isVector() &&
5310         N0.getValueType().getVectorElementType() == MVT::i1) {
5311       EVT N0VT = N0.getOperand(0).getValueType();
5312       if (getSetCCResultType(N0VT) == N0.getValueType())
5313         return SDValue();
5314
5315       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5316       // Only do this before legalize for now.
5317       EVT EltVT = VT.getVectorElementType();
5318       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5319                                     DAG.getConstant(1, EltVT));
5320       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5321         // We know that the # elements of the results is the same as the
5322         // # elements of the compare (and the # elements of the compare result
5323         // for that matter).  Check to see that they are the same size.  If so,
5324         // we know that the element size of the sext'd result matches the
5325         // element size of the compare operands.
5326         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5327                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5328                                          N0.getOperand(1),
5329                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5330                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5331                                        &OneOps[0], OneOps.size()));
5332
5333       // If the desired elements are smaller or larger than the source
5334       // elements we can use a matching integer vector type and then
5335       // truncate/sign extend
5336       EVT MatchingElementType =
5337         EVT::getIntegerVT(*DAG.getContext(),
5338                           N0VT.getScalarType().getSizeInBits());
5339       EVT MatchingVectorType =
5340         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5341                          N0VT.getVectorNumElements());
5342       SDValue VsetCC =
5343         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5344                       N0.getOperand(1),
5345                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5346       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5347                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5348                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5349                                      &OneOps[0], OneOps.size()));
5350     }
5351
5352     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5353     SDValue SCC =
5354       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5355                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5356                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5357     if (SCC.getNode()) return SCC;
5358   }
5359
5360   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5361   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5362       isa<ConstantSDNode>(N0.getOperand(1)) &&
5363       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5364       N0.hasOneUse()) {
5365     SDValue ShAmt = N0.getOperand(1);
5366     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5367     if (N0.getOpcode() == ISD::SHL) {
5368       SDValue InnerZExt = N0.getOperand(0);
5369       // If the original shl may be shifting out bits, do not perform this
5370       // transformation.
5371       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5372         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5373       if (ShAmtVal > KnownZeroBits)
5374         return SDValue();
5375     }
5376
5377     SDLoc DL(N);
5378
5379     // Ensure that the shift amount is wide enough for the shifted value.
5380     if (VT.getSizeInBits() >= 256)
5381       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5382
5383     return DAG.getNode(N0.getOpcode(), DL, VT,
5384                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5385                        ShAmt);
5386   }
5387
5388   return SDValue();
5389 }
5390
5391 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5392   SDValue N0 = N->getOperand(0);
5393   EVT VT = N->getValueType(0);
5394
5395   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5396                                               LegalOperations))
5397     return SDValue(Res, 0);
5398
5399   // fold (aext (aext x)) -> (aext x)
5400   // fold (aext (zext x)) -> (zext x)
5401   // fold (aext (sext x)) -> (sext x)
5402   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5403       N0.getOpcode() == ISD::ZERO_EXTEND ||
5404       N0.getOpcode() == ISD::SIGN_EXTEND)
5405     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5406
5407   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5408   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5409   if (N0.getOpcode() == ISD::TRUNCATE) {
5410     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5411     if (NarrowLoad.getNode()) {
5412       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5413       if (NarrowLoad.getNode() != N0.getNode()) {
5414         CombineTo(N0.getNode(), NarrowLoad);
5415         // CombineTo deleted the truncate, if needed, but not what's under it.
5416         AddToWorkList(oye);
5417       }
5418       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5419     }
5420   }
5421
5422   // fold (aext (truncate x))
5423   if (N0.getOpcode() == ISD::TRUNCATE) {
5424     SDValue TruncOp = N0.getOperand(0);
5425     if (TruncOp.getValueType() == VT)
5426       return TruncOp; // x iff x size == zext size.
5427     if (TruncOp.getValueType().bitsGT(VT))
5428       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5429     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5430   }
5431
5432   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5433   // if the trunc is not free.
5434   if (N0.getOpcode() == ISD::AND &&
5435       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5436       N0.getOperand(1).getOpcode() == ISD::Constant &&
5437       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5438                           N0.getValueType())) {
5439     SDValue X = N0.getOperand(0).getOperand(0);
5440     if (X.getValueType().bitsLT(VT)) {
5441       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5442     } else if (X.getValueType().bitsGT(VT)) {
5443       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5444     }
5445     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5446     Mask = Mask.zext(VT.getSizeInBits());
5447     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5448                        X, DAG.getConstant(Mask, VT));
5449   }
5450
5451   // fold (aext (load x)) -> (aext (truncate (extload x)))
5452   // None of the supported targets knows how to perform load and any_ext
5453   // on vectors in one instruction.  We only perform this transformation on
5454   // scalars.
5455   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5456       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5457       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5458        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5459     bool DoXform = true;
5460     SmallVector<SDNode*, 4> SetCCs;
5461     if (!N0.hasOneUse())
5462       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5463     if (DoXform) {
5464       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5465       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5466                                        LN0->getChain(),
5467                                        LN0->getBasePtr(), N0.getValueType(),
5468                                        LN0->getMemOperand());
5469       CombineTo(N, ExtLoad);
5470       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5471                                   N0.getValueType(), ExtLoad);
5472       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5473       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5474                       ISD::ANY_EXTEND);
5475       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5476     }
5477   }
5478
5479   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5480   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5481   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5482   if (N0.getOpcode() == ISD::LOAD &&
5483       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5484       N0.hasOneUse()) {
5485     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5486     ISD::LoadExtType ExtType = LN0->getExtensionType();
5487     EVT MemVT = LN0->getMemoryVT();
5488     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5489       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5490                                        VT, LN0->getChain(), LN0->getBasePtr(),
5491                                        MemVT, LN0->getMemOperand());
5492       CombineTo(N, ExtLoad);
5493       CombineTo(N0.getNode(),
5494                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5495                             N0.getValueType(), ExtLoad),
5496                 ExtLoad.getValue(1));
5497       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5498     }
5499   }
5500
5501   if (N0.getOpcode() == ISD::SETCC) {
5502     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5503     // Only do this before legalize for now.
5504     if (VT.isVector() && !LegalOperations) {
5505       EVT N0VT = N0.getOperand(0).getValueType();
5506         // We know that the # elements of the results is the same as the
5507         // # elements of the compare (and the # elements of the compare result
5508         // for that matter).  Check to see that they are the same size.  If so,
5509         // we know that the element size of the sext'd result matches the
5510         // element size of the compare operands.
5511       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5512         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5513                              N0.getOperand(1),
5514                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5515       // If the desired elements are smaller or larger than the source
5516       // elements we can use a matching integer vector type and then
5517       // truncate/sign extend
5518       else {
5519         EVT MatchingElementType =
5520           EVT::getIntegerVT(*DAG.getContext(),
5521                             N0VT.getScalarType().getSizeInBits());
5522         EVT MatchingVectorType =
5523           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5524                            N0VT.getVectorNumElements());
5525         SDValue VsetCC =
5526           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5527                         N0.getOperand(1),
5528                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5529         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5530       }
5531     }
5532
5533     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5534     SDValue SCC =
5535       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5536                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5537                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5538     if (SCC.getNode())
5539       return SCC;
5540   }
5541
5542   return SDValue();
5543 }
5544
5545 /// GetDemandedBits - See if the specified operand can be simplified with the
5546 /// knowledge that only the bits specified by Mask are used.  If so, return the
5547 /// simpler operand, otherwise return a null SDValue.
5548 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5549   switch (V.getOpcode()) {
5550   default: break;
5551   case ISD::Constant: {
5552     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5553     assert(CV && "Const value should be ConstSDNode.");
5554     const APInt &CVal = CV->getAPIntValue();
5555     APInt NewVal = CVal & Mask;
5556     if (NewVal != CVal)
5557       return DAG.getConstant(NewVal, V.getValueType());
5558     break;
5559   }
5560   case ISD::OR:
5561   case ISD::XOR:
5562     // If the LHS or RHS don't contribute bits to the or, drop them.
5563     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5564       return V.getOperand(1);
5565     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5566       return V.getOperand(0);
5567     break;
5568   case ISD::SRL:
5569     // Only look at single-use SRLs.
5570     if (!V.getNode()->hasOneUse())
5571       break;
5572     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5573       // See if we can recursively simplify the LHS.
5574       unsigned Amt = RHSC->getZExtValue();
5575
5576       // Watch out for shift count overflow though.
5577       if (Amt >= Mask.getBitWidth()) break;
5578       APInt NewMask = Mask << Amt;
5579       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5580       if (SimplifyLHS.getNode())
5581         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5582                            SimplifyLHS, V.getOperand(1));
5583     }
5584   }
5585   return SDValue();
5586 }
5587
5588 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5589 /// bits and then truncated to a narrower type and where N is a multiple
5590 /// of number of bits of the narrower type, transform it to a narrower load
5591 /// from address + N / num of bits of new type. If the result is to be
5592 /// extended, also fold the extension to form a extending load.
5593 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5594   unsigned Opc = N->getOpcode();
5595
5596   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5597   SDValue N0 = N->getOperand(0);
5598   EVT VT = N->getValueType(0);
5599   EVT ExtVT = VT;
5600
5601   // This transformation isn't valid for vector loads.
5602   if (VT.isVector())
5603     return SDValue();
5604
5605   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5606   // extended to VT.
5607   if (Opc == ISD::SIGN_EXTEND_INREG) {
5608     ExtType = ISD::SEXTLOAD;
5609     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5610   } else if (Opc == ISD::SRL) {
5611     // Another special-case: SRL is basically zero-extending a narrower value.
5612     ExtType = ISD::ZEXTLOAD;
5613     N0 = SDValue(N, 0);
5614     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5615     if (!N01) return SDValue();
5616     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5617                               VT.getSizeInBits() - N01->getZExtValue());
5618   }
5619   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5620     return SDValue();
5621
5622   unsigned EVTBits = ExtVT.getSizeInBits();
5623
5624   // Do not generate loads of non-round integer types since these can
5625   // be expensive (and would be wrong if the type is not byte sized).
5626   if (!ExtVT.isRound())
5627     return SDValue();
5628
5629   unsigned ShAmt = 0;
5630   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5631     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5632       ShAmt = N01->getZExtValue();
5633       // Is the shift amount a multiple of size of VT?
5634       if ((ShAmt & (EVTBits-1)) == 0) {
5635         N0 = N0.getOperand(0);
5636         // Is the load width a multiple of size of VT?
5637         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5638           return SDValue();
5639       }
5640
5641       // At this point, we must have a load or else we can't do the transform.
5642       if (!isa<LoadSDNode>(N0)) return SDValue();
5643
5644       // Because a SRL must be assumed to *need* to zero-extend the high bits
5645       // (as opposed to anyext the high bits), we can't combine the zextload
5646       // lowering of SRL and an sextload.
5647       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5648         return SDValue();
5649
5650       // If the shift amount is larger than the input type then we're not
5651       // accessing any of the loaded bytes.  If the load was a zextload/extload
5652       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5653       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5654         return SDValue();
5655     }
5656   }
5657
5658   // If the load is shifted left (and the result isn't shifted back right),
5659   // we can fold the truncate through the shift.
5660   unsigned ShLeftAmt = 0;
5661   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5662       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5663     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5664       ShLeftAmt = N01->getZExtValue();
5665       N0 = N0.getOperand(0);
5666     }
5667   }
5668
5669   // If we haven't found a load, we can't narrow it.  Don't transform one with
5670   // multiple uses, this would require adding a new load.
5671   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5672     return SDValue();
5673
5674   // Don't change the width of a volatile load.
5675   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5676   if (LN0->isVolatile())
5677     return SDValue();
5678
5679   // Verify that we are actually reducing a load width here.
5680   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5681     return SDValue();
5682
5683   // For the transform to be legal, the load must produce only two values
5684   // (the value loaded and the chain).  Don't transform a pre-increment
5685   // load, for example, which produces an extra value.  Otherwise the
5686   // transformation is not equivalent, and the downstream logic to replace
5687   // uses gets things wrong.
5688   if (LN0->getNumValues() > 2)
5689     return SDValue();
5690
5691   // If the load that we're shrinking is an extload and we're not just
5692   // discarding the extension we can't simply shrink the load. Bail.
5693   // TODO: It would be possible to merge the extensions in some cases.
5694   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5695       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5696     return SDValue();
5697
5698   EVT PtrType = N0.getOperand(1).getValueType();
5699
5700   if (PtrType == MVT::Untyped || PtrType.isExtended())
5701     // It's not possible to generate a constant of extended or untyped type.
5702     return SDValue();
5703
5704   // For big endian targets, we need to adjust the offset to the pointer to
5705   // load the correct bytes.
5706   if (TLI.isBigEndian()) {
5707     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5708     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5709     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5710   }
5711
5712   uint64_t PtrOff = ShAmt / 8;
5713   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5714   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5715                                PtrType, LN0->getBasePtr(),
5716                                DAG.getConstant(PtrOff, PtrType));
5717   AddToWorkList(NewPtr.getNode());
5718
5719   SDValue Load;
5720   if (ExtType == ISD::NON_EXTLOAD)
5721     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5722                         LN0->getPointerInfo().getWithOffset(PtrOff),
5723                         LN0->isVolatile(), LN0->isNonTemporal(),
5724                         LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5725   else
5726     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5727                           LN0->getPointerInfo().getWithOffset(PtrOff),
5728                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5729                           NewAlign, LN0->getTBAAInfo());
5730
5731   // Replace the old load's chain with the new load's chain.
5732   WorkListRemover DeadNodes(*this);
5733   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5734
5735   // Shift the result left, if we've swallowed a left shift.
5736   SDValue Result = Load;
5737   if (ShLeftAmt != 0) {
5738     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5739     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5740       ShImmTy = VT;
5741     // If the shift amount is as large as the result size (but, presumably,
5742     // no larger than the source) then the useful bits of the result are
5743     // zero; we can't simply return the shortened shift, because the result
5744     // of that operation is undefined.
5745     if (ShLeftAmt >= VT.getSizeInBits())
5746       Result = DAG.getConstant(0, VT);
5747     else
5748       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5749                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5750   }
5751
5752   // Return the new loaded value.
5753   return Result;
5754 }
5755
5756 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5757   SDValue N0 = N->getOperand(0);
5758   SDValue N1 = N->getOperand(1);
5759   EVT VT = N->getValueType(0);
5760   EVT EVT = cast<VTSDNode>(N1)->getVT();
5761   unsigned VTBits = VT.getScalarType().getSizeInBits();
5762   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5763
5764   // fold (sext_in_reg c1) -> c1
5765   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5766     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5767
5768   // If the input is already sign extended, just drop the extension.
5769   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5770     return N0;
5771
5772   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5773   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5774       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5775     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5776                        N0.getOperand(0), N1);
5777
5778   // fold (sext_in_reg (sext x)) -> (sext x)
5779   // fold (sext_in_reg (aext x)) -> (sext x)
5780   // if x is small enough.
5781   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5782     SDValue N00 = N0.getOperand(0);
5783     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5784         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5785       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5786   }
5787
5788   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5789   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5790     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5791
5792   // fold operands of sext_in_reg based on knowledge that the top bits are not
5793   // demanded.
5794   if (SimplifyDemandedBits(SDValue(N, 0)))
5795     return SDValue(N, 0);
5796
5797   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5798   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5799   SDValue NarrowLoad = ReduceLoadWidth(N);
5800   if (NarrowLoad.getNode())
5801     return NarrowLoad;
5802
5803   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5804   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5805   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5806   if (N0.getOpcode() == ISD::SRL) {
5807     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5808       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5809         // We can turn this into an SRA iff the input to the SRL is already sign
5810         // extended enough.
5811         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5812         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5813           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5814                              N0.getOperand(0), N0.getOperand(1));
5815       }
5816   }
5817
5818   // fold (sext_inreg (extload x)) -> (sextload x)
5819   if (ISD::isEXTLoad(N0.getNode()) &&
5820       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5821       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5822       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5823        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5824     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5825     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5826                                      LN0->getChain(),
5827                                      LN0->getBasePtr(), EVT,
5828                                      LN0->getMemOperand());
5829     CombineTo(N, ExtLoad);
5830     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5831     AddToWorkList(ExtLoad.getNode());
5832     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5833   }
5834   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5835   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5836       N0.hasOneUse() &&
5837       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5838       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5839        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5840     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5841     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5842                                      LN0->getChain(),
5843                                      LN0->getBasePtr(), EVT,
5844                                      LN0->getMemOperand());
5845     CombineTo(N, ExtLoad);
5846     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5847     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5848   }
5849
5850   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5851   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5852     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5853                                        N0.getOperand(1), false);
5854     if (BSwap.getNode())
5855       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5856                          BSwap, N1);
5857   }
5858
5859   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5860   // into a build_vector.
5861   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5862     SmallVector<SDValue, 8> Elts;
5863     unsigned NumElts = N0->getNumOperands();
5864     unsigned ShAmt = VTBits - EVTBits;
5865
5866     for (unsigned i = 0; i != NumElts; ++i) {
5867       SDValue Op = N0->getOperand(i);
5868       if (Op->getOpcode() == ISD::UNDEF) {
5869         Elts.push_back(Op);
5870         continue;
5871       }
5872
5873       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5874       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5875       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5876                                      Op.getValueType()));
5877     }
5878
5879     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5880   }
5881
5882   return SDValue();
5883 }
5884
5885 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5886   SDValue N0 = N->getOperand(0);
5887   EVT VT = N->getValueType(0);
5888   bool isLE = TLI.isLittleEndian();
5889
5890   // noop truncate
5891   if (N0.getValueType() == N->getValueType(0))
5892     return N0;
5893   // fold (truncate c1) -> c1
5894   if (isa<ConstantSDNode>(N0))
5895     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5896   // fold (truncate (truncate x)) -> (truncate x)
5897   if (N0.getOpcode() == ISD::TRUNCATE)
5898     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5899   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5900   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5901       N0.getOpcode() == ISD::SIGN_EXTEND ||
5902       N0.getOpcode() == ISD::ANY_EXTEND) {
5903     if (N0.getOperand(0).getValueType().bitsLT(VT))
5904       // if the source is smaller than the dest, we still need an extend
5905       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5906                          N0.getOperand(0));
5907     if (N0.getOperand(0).getValueType().bitsGT(VT))
5908       // if the source is larger than the dest, than we just need the truncate
5909       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5910     // if the source and dest are the same type, we can drop both the extend
5911     // and the truncate.
5912     return N0.getOperand(0);
5913   }
5914
5915   // Fold extract-and-trunc into a narrow extract. For example:
5916   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5917   //   i32 y = TRUNCATE(i64 x)
5918   //        -- becomes --
5919   //   v16i8 b = BITCAST (v2i64 val)
5920   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5921   //
5922   // Note: We only run this optimization after type legalization (which often
5923   // creates this pattern) and before operation legalization after which
5924   // we need to be more careful about the vector instructions that we generate.
5925   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5926       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5927
5928     EVT VecTy = N0.getOperand(0).getValueType();
5929     EVT ExTy = N0.getValueType();
5930     EVT TrTy = N->getValueType(0);
5931
5932     unsigned NumElem = VecTy.getVectorNumElements();
5933     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5934
5935     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5936     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5937
5938     SDValue EltNo = N0->getOperand(1);
5939     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5940       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5941       EVT IndexTy = TLI.getVectorIdxTy();
5942       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5943
5944       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5945                               NVT, N0.getOperand(0));
5946
5947       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5948                          SDLoc(N), TrTy, V,
5949                          DAG.getConstant(Index, IndexTy));
5950     }
5951   }
5952
5953   // Fold a series of buildvector, bitcast, and truncate if possible.
5954   // For example fold
5955   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5956   //   (2xi32 (buildvector x, y)).
5957   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5958       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5959       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5960       N0.getOperand(0).hasOneUse()) {
5961
5962     SDValue BuildVect = N0.getOperand(0);
5963     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5964     EVT TruncVecEltTy = VT.getVectorElementType();
5965
5966     // Check that the element types match.
5967     if (BuildVectEltTy == TruncVecEltTy) {
5968       // Now we only need to compute the offset of the truncated elements.
5969       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5970       unsigned TruncVecNumElts = VT.getVectorNumElements();
5971       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5972
5973       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5974              "Invalid number of elements");
5975
5976       SmallVector<SDValue, 8> Opnds;
5977       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5978         Opnds.push_back(BuildVect.getOperand(i));
5979
5980       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5981                          Opnds.size());
5982     }
5983   }
5984
5985   // See if we can simplify the input to this truncate through knowledge that
5986   // only the low bits are being used.
5987   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5988   // Currently we only perform this optimization on scalars because vectors
5989   // may have different active low bits.
5990   if (!VT.isVector()) {
5991     SDValue Shorter =
5992       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5993                                                VT.getSizeInBits()));
5994     if (Shorter.getNode())
5995       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5996   }
5997   // fold (truncate (load x)) -> (smaller load x)
5998   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5999   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6000     SDValue Reduced = ReduceLoadWidth(N);
6001     if (Reduced.getNode())
6002       return Reduced;
6003     // Handle the case where the load remains an extending load even
6004     // after truncation.
6005     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6006       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6007       if (!LN0->isVolatile() &&
6008           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6009         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6010                                          VT, LN0->getChain(), LN0->getBasePtr(),
6011                                          LN0->getMemoryVT(),
6012                                          LN0->getMemOperand());
6013         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6014         return NewLoad;
6015       }
6016     }
6017   }
6018   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6019   // where ... are all 'undef'.
6020   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6021     SmallVector<EVT, 8> VTs;
6022     SDValue V;
6023     unsigned Idx = 0;
6024     unsigned NumDefs = 0;
6025
6026     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6027       SDValue X = N0.getOperand(i);
6028       if (X.getOpcode() != ISD::UNDEF) {
6029         V = X;
6030         Idx = i;
6031         NumDefs++;
6032       }
6033       // Stop if more than one members are non-undef.
6034       if (NumDefs > 1)
6035         break;
6036       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6037                                      VT.getVectorElementType(),
6038                                      X.getValueType().getVectorNumElements()));
6039     }
6040
6041     if (NumDefs == 0)
6042       return DAG.getUNDEF(VT);
6043
6044     if (NumDefs == 1) {
6045       assert(V.getNode() && "The single defined operand is empty!");
6046       SmallVector<SDValue, 8> Opnds;
6047       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6048         if (i != Idx) {
6049           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6050           continue;
6051         }
6052         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6053         AddToWorkList(NV.getNode());
6054         Opnds.push_back(NV);
6055       }
6056       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
6057                          &Opnds[0], Opnds.size());
6058     }
6059   }
6060
6061   // Simplify the operands using demanded-bits information.
6062   if (!VT.isVector() &&
6063       SimplifyDemandedBits(SDValue(N, 0)))
6064     return SDValue(N, 0);
6065
6066   return SDValue();
6067 }
6068
6069 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6070   SDValue Elt = N->getOperand(i);
6071   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6072     return Elt.getNode();
6073   return Elt.getOperand(Elt.getResNo()).getNode();
6074 }
6075
6076 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6077 /// if load locations are consecutive.
6078 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6079   assert(N->getOpcode() == ISD::BUILD_PAIR);
6080
6081   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6082   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6083   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6084       LD1->getAddressSpace() != LD2->getAddressSpace())
6085     return SDValue();
6086   EVT LD1VT = LD1->getValueType(0);
6087
6088   if (ISD::isNON_EXTLoad(LD2) &&
6089       LD2->hasOneUse() &&
6090       // If both are volatile this would reduce the number of volatile loads.
6091       // If one is volatile it might be ok, but play conservative and bail out.
6092       !LD1->isVolatile() &&
6093       !LD2->isVolatile() &&
6094       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6095     unsigned Align = LD1->getAlignment();
6096     unsigned NewAlign = TLI.getDataLayout()->
6097       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6098
6099     if (NewAlign <= Align &&
6100         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6101       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6102                          LD1->getBasePtr(), LD1->getPointerInfo(),
6103                          false, false, false, Align);
6104   }
6105
6106   return SDValue();
6107 }
6108
6109 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6110   SDValue N0 = N->getOperand(0);
6111   EVT VT = N->getValueType(0);
6112
6113   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6114   // Only do this before legalize, since afterward the target may be depending
6115   // on the bitconvert.
6116   // First check to see if this is all constant.
6117   if (!LegalTypes &&
6118       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6119       VT.isVector()) {
6120     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6121
6122     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6123     assert(!DestEltVT.isVector() &&
6124            "Element type of vector ValueType must not be vector!");
6125     if (isSimple)
6126       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6127   }
6128
6129   // If the input is a constant, let getNode fold it.
6130   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6131     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6132     if (Res.getNode() != N) {
6133       if (!LegalOperations ||
6134           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6135         return Res;
6136
6137       // Folding it resulted in an illegal node, and it's too late to
6138       // do that. Clean up the old node and forego the transformation.
6139       // Ideally this won't happen very often, because instcombine
6140       // and the earlier dagcombine runs (where illegal nodes are
6141       // permitted) should have folded most of them already.
6142       DAG.DeleteNode(Res.getNode());
6143     }
6144   }
6145
6146   // (conv (conv x, t1), t2) -> (conv x, t2)
6147   if (N0.getOpcode() == ISD::BITCAST)
6148     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6149                        N0.getOperand(0));
6150
6151   // fold (conv (load x)) -> (load (conv*)x)
6152   // If the resultant load doesn't need a higher alignment than the original!
6153   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6154       // Do not change the width of a volatile load.
6155       !cast<LoadSDNode>(N0)->isVolatile() &&
6156       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6157       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6158     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6159     unsigned Align = TLI.getDataLayout()->
6160       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6161     unsigned OrigAlign = LN0->getAlignment();
6162
6163     if (Align <= OrigAlign) {
6164       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6165                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6166                                  LN0->isVolatile(), LN0->isNonTemporal(),
6167                                  LN0->isInvariant(), OrigAlign,
6168                                  LN0->getTBAAInfo());
6169       AddToWorkList(N);
6170       CombineTo(N0.getNode(),
6171                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6172                             N0.getValueType(), Load),
6173                 Load.getValue(1));
6174       return Load;
6175     }
6176   }
6177
6178   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6179   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6180   // This often reduces constant pool loads.
6181   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6182        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6183       N0.getNode()->hasOneUse() && VT.isInteger() &&
6184       !VT.isVector() && !N0.getValueType().isVector()) {
6185     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6186                                   N0.getOperand(0));
6187     AddToWorkList(NewConv.getNode());
6188
6189     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6190     if (N0.getOpcode() == ISD::FNEG)
6191       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6192                          NewConv, DAG.getConstant(SignBit, VT));
6193     assert(N0.getOpcode() == ISD::FABS);
6194     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6195                        NewConv, DAG.getConstant(~SignBit, VT));
6196   }
6197
6198   // fold (bitconvert (fcopysign cst, x)) ->
6199   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6200   // Note that we don't handle (copysign x, cst) because this can always be
6201   // folded to an fneg or fabs.
6202   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6203       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6204       VT.isInteger() && !VT.isVector()) {
6205     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6206     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6207     if (isTypeLegal(IntXVT)) {
6208       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6209                               IntXVT, N0.getOperand(1));
6210       AddToWorkList(X.getNode());
6211
6212       // If X has a different width than the result/lhs, sext it or truncate it.
6213       unsigned VTWidth = VT.getSizeInBits();
6214       if (OrigXWidth < VTWidth) {
6215         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6216         AddToWorkList(X.getNode());
6217       } else if (OrigXWidth > VTWidth) {
6218         // To get the sign bit in the right place, we have to shift it right
6219         // before truncating.
6220         X = DAG.getNode(ISD::SRL, SDLoc(X),
6221                         X.getValueType(), X,
6222                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6223         AddToWorkList(X.getNode());
6224         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6225         AddToWorkList(X.getNode());
6226       }
6227
6228       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6229       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6230                       X, DAG.getConstant(SignBit, VT));
6231       AddToWorkList(X.getNode());
6232
6233       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6234                                 VT, N0.getOperand(0));
6235       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6236                         Cst, DAG.getConstant(~SignBit, VT));
6237       AddToWorkList(Cst.getNode());
6238
6239       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6240     }
6241   }
6242
6243   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6244   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6245     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6246     if (CombineLD.getNode())
6247       return CombineLD;
6248   }
6249
6250   return SDValue();
6251 }
6252
6253 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6254   EVT VT = N->getValueType(0);
6255   return CombineConsecutiveLoads(N, VT);
6256 }
6257
6258 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6259 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6260 /// destination element value type.
6261 SDValue DAGCombiner::
6262 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6263   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6264
6265   // If this is already the right type, we're done.
6266   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6267
6268   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6269   unsigned DstBitSize = DstEltVT.getSizeInBits();
6270
6271   // If this is a conversion of N elements of one type to N elements of another
6272   // type, convert each element.  This handles FP<->INT cases.
6273   if (SrcBitSize == DstBitSize) {
6274     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6275                               BV->getValueType(0).getVectorNumElements());
6276
6277     // Due to the FP element handling below calling this routine recursively,
6278     // we can end up with a scalar-to-vector node here.
6279     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6280       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6281                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6282                                      DstEltVT, BV->getOperand(0)));
6283
6284     SmallVector<SDValue, 8> Ops;
6285     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6286       SDValue Op = BV->getOperand(i);
6287       // If the vector element type is not legal, the BUILD_VECTOR operands
6288       // are promoted and implicitly truncated.  Make that explicit here.
6289       if (Op.getValueType() != SrcEltVT)
6290         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6291       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6292                                 DstEltVT, Op));
6293       AddToWorkList(Ops.back().getNode());
6294     }
6295     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6296                        &Ops[0], Ops.size());
6297   }
6298
6299   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6300   // handle annoying details of growing/shrinking FP values, we convert them to
6301   // int first.
6302   if (SrcEltVT.isFloatingPoint()) {
6303     // Convert the input float vector to a int vector where the elements are the
6304     // same sizes.
6305     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6306     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6307     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6308     SrcEltVT = IntVT;
6309   }
6310
6311   // Now we know the input is an integer vector.  If the output is a FP type,
6312   // convert to integer first, then to FP of the right size.
6313   if (DstEltVT.isFloatingPoint()) {
6314     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6315     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6316     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6317
6318     // Next, convert to FP elements of the same size.
6319     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6320   }
6321
6322   // Okay, we know the src/dst types are both integers of differing types.
6323   // Handling growing first.
6324   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6325   if (SrcBitSize < DstBitSize) {
6326     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6327
6328     SmallVector<SDValue, 8> Ops;
6329     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6330          i += NumInputsPerOutput) {
6331       bool isLE = TLI.isLittleEndian();
6332       APInt NewBits = APInt(DstBitSize, 0);
6333       bool EltIsUndef = true;
6334       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6335         // Shift the previously computed bits over.
6336         NewBits <<= SrcBitSize;
6337         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6338         if (Op.getOpcode() == ISD::UNDEF) continue;
6339         EltIsUndef = false;
6340
6341         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6342                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6343       }
6344
6345       if (EltIsUndef)
6346         Ops.push_back(DAG.getUNDEF(DstEltVT));
6347       else
6348         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6349     }
6350
6351     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6352     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6353                        &Ops[0], Ops.size());
6354   }
6355
6356   // Finally, this must be the case where we are shrinking elements: each input
6357   // turns into multiple outputs.
6358   bool isS2V = ISD::isScalarToVector(BV);
6359   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6360   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6361                             NumOutputsPerInput*BV->getNumOperands());
6362   SmallVector<SDValue, 8> Ops;
6363
6364   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6365     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6366       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6367         Ops.push_back(DAG.getUNDEF(DstEltVT));
6368       continue;
6369     }
6370
6371     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6372                   getAPIntValue().zextOrTrunc(SrcBitSize);
6373
6374     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6375       APInt ThisVal = OpVal.trunc(DstBitSize);
6376       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6377       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6378         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6379         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6380                            Ops[0]);
6381       OpVal = OpVal.lshr(DstBitSize);
6382     }
6383
6384     // For big endian targets, swap the order of the pieces of each element.
6385     if (TLI.isBigEndian())
6386       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6387   }
6388
6389   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6390                      &Ops[0], Ops.size());
6391 }
6392
6393 SDValue DAGCombiner::visitFADD(SDNode *N) {
6394   SDValue N0 = N->getOperand(0);
6395   SDValue N1 = N->getOperand(1);
6396   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6397   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6398   EVT VT = N->getValueType(0);
6399
6400   // fold vector ops
6401   if (VT.isVector()) {
6402     SDValue FoldedVOp = SimplifyVBinOp(N);
6403     if (FoldedVOp.getNode()) return FoldedVOp;
6404   }
6405
6406   // fold (fadd c1, c2) -> c1 + c2
6407   if (N0CFP && N1CFP)
6408     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6409   // canonicalize constant to RHS
6410   if (N0CFP && !N1CFP)
6411     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6412   // fold (fadd A, 0) -> A
6413   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6414       N1CFP->getValueAPF().isZero())
6415     return N0;
6416   // fold (fadd A, (fneg B)) -> (fsub A, B)
6417   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6418     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6419     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6420                        GetNegatedExpression(N1, DAG, LegalOperations));
6421   // fold (fadd (fneg A), B) -> (fsub B, A)
6422   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6423     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6424     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6425                        GetNegatedExpression(N0, DAG, LegalOperations));
6426
6427   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6428   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6429       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6430       isa<ConstantFPSDNode>(N0.getOperand(1)))
6431     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6432                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6433                                    N0.getOperand(1), N1));
6434
6435   // No FP constant should be created after legalization as Instruction
6436   // Selection pass has hard time in dealing with FP constant.
6437   //
6438   // We don't need test this condition for transformation like following, as
6439   // the DAG being transformed implies it is legal to take FP constant as
6440   // operand.
6441   //
6442   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6443   //
6444   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6445
6446   // If allow, fold (fadd (fneg x), x) -> 0.0
6447   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6448       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6449     return DAG.getConstantFP(0.0, VT);
6450
6451     // If allow, fold (fadd x, (fneg x)) -> 0.0
6452   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6453       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6454     return DAG.getConstantFP(0.0, VT);
6455
6456   // In unsafe math mode, we can fold chains of FADD's of the same value
6457   // into multiplications.  This transform is not safe in general because
6458   // we are reducing the number of rounding steps.
6459   if (DAG.getTarget().Options.UnsafeFPMath &&
6460       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6461       !N0CFP && !N1CFP) {
6462     if (N0.getOpcode() == ISD::FMUL) {
6463       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6464       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6465
6466       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6467       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6468         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6469                                      SDValue(CFP00, 0),
6470                                      DAG.getConstantFP(1.0, VT));
6471         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6472                            N1, NewCFP);
6473       }
6474
6475       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6476       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6477         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6478                                      SDValue(CFP01, 0),
6479                                      DAG.getConstantFP(1.0, VT));
6480         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6481                            N1, NewCFP);
6482       }
6483
6484       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6485       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6486           N1.getOperand(0) == N1.getOperand(1) &&
6487           N0.getOperand(1) == N1.getOperand(0)) {
6488         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6489                                      SDValue(CFP00, 0),
6490                                      DAG.getConstantFP(2.0, VT));
6491         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6492                            N0.getOperand(1), NewCFP);
6493       }
6494
6495       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6496       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6497           N1.getOperand(0) == N1.getOperand(1) &&
6498           N0.getOperand(0) == N1.getOperand(0)) {
6499         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6500                                      SDValue(CFP01, 0),
6501                                      DAG.getConstantFP(2.0, VT));
6502         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6503                            N0.getOperand(0), NewCFP);
6504       }
6505     }
6506
6507     if (N1.getOpcode() == ISD::FMUL) {
6508       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6509       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6510
6511       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6512       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6513         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6514                                      SDValue(CFP10, 0),
6515                                      DAG.getConstantFP(1.0, VT));
6516         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6517                            N0, NewCFP);
6518       }
6519
6520       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6521       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6522         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6523                                      SDValue(CFP11, 0),
6524                                      DAG.getConstantFP(1.0, VT));
6525         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6526                            N0, NewCFP);
6527       }
6528
6529
6530       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6531       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6532           N0.getOperand(0) == N0.getOperand(1) &&
6533           N1.getOperand(1) == N0.getOperand(0)) {
6534         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6535                                      SDValue(CFP10, 0),
6536                                      DAG.getConstantFP(2.0, VT));
6537         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6538                            N1.getOperand(1), NewCFP);
6539       }
6540
6541       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6542       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6543           N0.getOperand(0) == N0.getOperand(1) &&
6544           N1.getOperand(0) == N0.getOperand(0)) {
6545         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6546                                      SDValue(CFP11, 0),
6547                                      DAG.getConstantFP(2.0, VT));
6548         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6549                            N1.getOperand(0), NewCFP);
6550       }
6551     }
6552
6553     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6554       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6555       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6556       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6557           (N0.getOperand(0) == N1))
6558         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6559                            N1, DAG.getConstantFP(3.0, VT));
6560     }
6561
6562     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6563       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6564       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6565       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6566           N1.getOperand(0) == N0)
6567         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6568                            N0, DAG.getConstantFP(3.0, VT));
6569     }
6570
6571     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6572     if (AllowNewFpConst &&
6573         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6574         N0.getOperand(0) == N0.getOperand(1) &&
6575         N1.getOperand(0) == N1.getOperand(1) &&
6576         N0.getOperand(0) == N1.getOperand(0))
6577       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6578                          N0.getOperand(0),
6579                          DAG.getConstantFP(4.0, VT));
6580   }
6581
6582   // FADD -> FMA combines:
6583   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6584        DAG.getTarget().Options.UnsafeFPMath) &&
6585       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6586       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6587
6588     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6589     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6590       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6591                          N0.getOperand(0), N0.getOperand(1), N1);
6592
6593     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6594     // Note: Commutes FADD operands.
6595     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6596       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6597                          N1.getOperand(0), N1.getOperand(1), N0);
6598   }
6599
6600   return SDValue();
6601 }
6602
6603 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6604   SDValue N0 = N->getOperand(0);
6605   SDValue N1 = N->getOperand(1);
6606   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6607   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6608   EVT VT = N->getValueType(0);
6609   SDLoc dl(N);
6610
6611   // fold vector ops
6612   if (VT.isVector()) {
6613     SDValue FoldedVOp = SimplifyVBinOp(N);
6614     if (FoldedVOp.getNode()) return FoldedVOp;
6615   }
6616
6617   // fold (fsub c1, c2) -> c1-c2
6618   if (N0CFP && N1CFP)
6619     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6620   // fold (fsub A, 0) -> A
6621   if (DAG.getTarget().Options.UnsafeFPMath &&
6622       N1CFP && N1CFP->getValueAPF().isZero())
6623     return N0;
6624   // fold (fsub 0, B) -> -B
6625   if (DAG.getTarget().Options.UnsafeFPMath &&
6626       N0CFP && N0CFP->getValueAPF().isZero()) {
6627     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6628       return GetNegatedExpression(N1, DAG, LegalOperations);
6629     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6630       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6631   }
6632   // fold (fsub A, (fneg B)) -> (fadd A, B)
6633   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6634     return DAG.getNode(ISD::FADD, dl, VT, N0,
6635                        GetNegatedExpression(N1, DAG, LegalOperations));
6636
6637   // If 'unsafe math' is enabled, fold
6638   //    (fsub x, x) -> 0.0 &
6639   //    (fsub x, (fadd x, y)) -> (fneg y) &
6640   //    (fsub x, (fadd y, x)) -> (fneg y)
6641   if (DAG.getTarget().Options.UnsafeFPMath) {
6642     if (N0 == N1)
6643       return DAG.getConstantFP(0.0f, VT);
6644
6645     if (N1.getOpcode() == ISD::FADD) {
6646       SDValue N10 = N1->getOperand(0);
6647       SDValue N11 = N1->getOperand(1);
6648
6649       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6650                                           &DAG.getTarget().Options))
6651         return GetNegatedExpression(N11, DAG, LegalOperations);
6652
6653       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6654                                           &DAG.getTarget().Options))
6655         return GetNegatedExpression(N10, DAG, LegalOperations);
6656     }
6657   }
6658
6659   // FSUB -> FMA combines:
6660   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6661        DAG.getTarget().Options.UnsafeFPMath) &&
6662       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6663       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6664
6665     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6666     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6667       return DAG.getNode(ISD::FMA, dl, VT,
6668                          N0.getOperand(0), N0.getOperand(1),
6669                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6670
6671     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6672     // Note: Commutes FSUB operands.
6673     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6674       return DAG.getNode(ISD::FMA, dl, VT,
6675                          DAG.getNode(ISD::FNEG, dl, VT,
6676                          N1.getOperand(0)),
6677                          N1.getOperand(1), N0);
6678
6679     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6680     if (N0.getOpcode() == ISD::FNEG &&
6681         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6682         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6683       SDValue N00 = N0.getOperand(0).getOperand(0);
6684       SDValue N01 = N0.getOperand(0).getOperand(1);
6685       return DAG.getNode(ISD::FMA, dl, VT,
6686                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6687                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6688     }
6689   }
6690
6691   return SDValue();
6692 }
6693
6694 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6695   SDValue N0 = N->getOperand(0);
6696   SDValue N1 = N->getOperand(1);
6697   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6698   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6699   EVT VT = N->getValueType(0);
6700   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6701
6702   // fold vector ops
6703   if (VT.isVector()) {
6704     SDValue FoldedVOp = SimplifyVBinOp(N);
6705     if (FoldedVOp.getNode()) return FoldedVOp;
6706   }
6707
6708   // fold (fmul c1, c2) -> c1*c2
6709   if (N0CFP && N1CFP)
6710     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6711   // canonicalize constant to RHS
6712   if (N0CFP && !N1CFP)
6713     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6714   // fold (fmul A, 0) -> 0
6715   if (DAG.getTarget().Options.UnsafeFPMath &&
6716       N1CFP && N1CFP->getValueAPF().isZero())
6717     return N1;
6718   // fold (fmul A, 0) -> 0, vector edition.
6719   if (DAG.getTarget().Options.UnsafeFPMath &&
6720       ISD::isBuildVectorAllZeros(N1.getNode()))
6721     return N1;
6722   // fold (fmul A, 1.0) -> A
6723   if (N1CFP && N1CFP->isExactlyValue(1.0))
6724     return N0;
6725   // fold (fmul X, 2.0) -> (fadd X, X)
6726   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6727     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6728   // fold (fmul X, -1.0) -> (fneg X)
6729   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6730     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6731       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6732
6733   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6734   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6735                                        &DAG.getTarget().Options)) {
6736     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6737                                          &DAG.getTarget().Options)) {
6738       // Both can be negated for free, check to see if at least one is cheaper
6739       // negated.
6740       if (LHSNeg == 2 || RHSNeg == 2)
6741         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6742                            GetNegatedExpression(N0, DAG, LegalOperations),
6743                            GetNegatedExpression(N1, DAG, LegalOperations));
6744     }
6745   }
6746
6747   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6748   if (DAG.getTarget().Options.UnsafeFPMath &&
6749       N1CFP && N0.getOpcode() == ISD::FMUL &&
6750       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6751     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6752                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6753                                    N0.getOperand(1), N1));
6754
6755   return SDValue();
6756 }
6757
6758 SDValue DAGCombiner::visitFMA(SDNode *N) {
6759   SDValue N0 = N->getOperand(0);
6760   SDValue N1 = N->getOperand(1);
6761   SDValue N2 = N->getOperand(2);
6762   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6763   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6764   EVT VT = N->getValueType(0);
6765   SDLoc dl(N);
6766
6767   if (DAG.getTarget().Options.UnsafeFPMath) {
6768     if (N0CFP && N0CFP->isZero())
6769       return N2;
6770     if (N1CFP && N1CFP->isZero())
6771       return N2;
6772   }
6773   if (N0CFP && N0CFP->isExactlyValue(1.0))
6774     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6775   if (N1CFP && N1CFP->isExactlyValue(1.0))
6776     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6777
6778   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6779   if (N0CFP && !N1CFP)
6780     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6781
6782   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6783   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6784       N2.getOpcode() == ISD::FMUL &&
6785       N0 == N2.getOperand(0) &&
6786       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6787     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6788                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6789   }
6790
6791
6792   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6793   if (DAG.getTarget().Options.UnsafeFPMath &&
6794       N0.getOpcode() == ISD::FMUL && N1CFP &&
6795       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6796     return DAG.getNode(ISD::FMA, dl, VT,
6797                        N0.getOperand(0),
6798                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6799                        N2);
6800   }
6801
6802   // (fma x, 1, y) -> (fadd x, y)
6803   // (fma x, -1, y) -> (fadd (fneg x), y)
6804   if (N1CFP) {
6805     if (N1CFP->isExactlyValue(1.0))
6806       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6807
6808     if (N1CFP->isExactlyValue(-1.0) &&
6809         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6810       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6811       AddToWorkList(RHSNeg.getNode());
6812       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6813     }
6814   }
6815
6816   // (fma x, c, x) -> (fmul x, (c+1))
6817   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6818     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6819                        DAG.getNode(ISD::FADD, dl, VT,
6820                                    N1, DAG.getConstantFP(1.0, VT)));
6821
6822   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6823   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6824       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6825     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6826                        DAG.getNode(ISD::FADD, dl, VT,
6827                                    N1, DAG.getConstantFP(-1.0, VT)));
6828
6829
6830   return SDValue();
6831 }
6832
6833 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6834   SDValue N0 = N->getOperand(0);
6835   SDValue N1 = N->getOperand(1);
6836   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6837   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6838   EVT VT = N->getValueType(0);
6839   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6840
6841   // fold vector ops
6842   if (VT.isVector()) {
6843     SDValue FoldedVOp = SimplifyVBinOp(N);
6844     if (FoldedVOp.getNode()) return FoldedVOp;
6845   }
6846
6847   // fold (fdiv c1, c2) -> c1/c2
6848   if (N0CFP && N1CFP)
6849     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6850
6851   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6852   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6853     // Compute the reciprocal 1.0 / c2.
6854     APFloat N1APF = N1CFP->getValueAPF();
6855     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6856     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6857     // Only do the transform if the reciprocal is a legal fp immediate that
6858     // isn't too nasty (eg NaN, denormal, ...).
6859     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6860         (!LegalOperations ||
6861          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6862          // backend)... we should handle this gracefully after Legalize.
6863          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6864          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6865          TLI.isFPImmLegal(Recip, VT)))
6866       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6867                          DAG.getConstantFP(Recip, VT));
6868   }
6869
6870   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6871   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6872                                        &DAG.getTarget().Options)) {
6873     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6874                                          &DAG.getTarget().Options)) {
6875       // Both can be negated for free, check to see if at least one is cheaper
6876       // negated.
6877       if (LHSNeg == 2 || RHSNeg == 2)
6878         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6879                            GetNegatedExpression(N0, DAG, LegalOperations),
6880                            GetNegatedExpression(N1, DAG, LegalOperations));
6881     }
6882   }
6883
6884   return SDValue();
6885 }
6886
6887 SDValue DAGCombiner::visitFREM(SDNode *N) {
6888   SDValue N0 = N->getOperand(0);
6889   SDValue N1 = N->getOperand(1);
6890   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6891   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6892   EVT VT = N->getValueType(0);
6893
6894   // fold (frem c1, c2) -> fmod(c1,c2)
6895   if (N0CFP && N1CFP)
6896     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6897
6898   return SDValue();
6899 }
6900
6901 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6902   SDValue N0 = N->getOperand(0);
6903   SDValue N1 = N->getOperand(1);
6904   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6905   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6906   EVT VT = N->getValueType(0);
6907
6908   if (N0CFP && N1CFP)  // Constant fold
6909     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6910
6911   if (N1CFP) {
6912     const APFloat& V = N1CFP->getValueAPF();
6913     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6914     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6915     if (!V.isNegative()) {
6916       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6917         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6918     } else {
6919       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6920         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6921                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6922     }
6923   }
6924
6925   // copysign(fabs(x), y) -> copysign(x, y)
6926   // copysign(fneg(x), y) -> copysign(x, y)
6927   // copysign(copysign(x,z), y) -> copysign(x, y)
6928   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6929       N0.getOpcode() == ISD::FCOPYSIGN)
6930     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6931                        N0.getOperand(0), N1);
6932
6933   // copysign(x, abs(y)) -> abs(x)
6934   if (N1.getOpcode() == ISD::FABS)
6935     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6936
6937   // copysign(x, copysign(y,z)) -> copysign(x, z)
6938   if (N1.getOpcode() == ISD::FCOPYSIGN)
6939     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6940                        N0, N1.getOperand(1));
6941
6942   // copysign(x, fp_extend(y)) -> copysign(x, y)
6943   // copysign(x, fp_round(y)) -> copysign(x, y)
6944   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6945     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6946                        N0, N1.getOperand(0));
6947
6948   return SDValue();
6949 }
6950
6951 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6952   SDValue N0 = N->getOperand(0);
6953   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6954   EVT VT = N->getValueType(0);
6955   EVT OpVT = N0.getValueType();
6956
6957   // fold (sint_to_fp c1) -> c1fp
6958   if (N0C &&
6959       // ...but only if the target supports immediate floating-point values
6960       (!LegalOperations ||
6961        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6962     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6963
6964   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6965   // but UINT_TO_FP is legal on this target, try to convert.
6966   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6967       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6968     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6969     if (DAG.SignBitIsZero(N0))
6970       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6971   }
6972
6973   // The next optimizations are desirable only if SELECT_CC can be lowered.
6974   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6975   // having to say they don't support SELECT_CC on every type the DAG knows
6976   // about, since there is no way to mark an opcode illegal at all value types
6977   // (See also visitSELECT)
6978   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6979     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6980     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6981         !VT.isVector() &&
6982         (!LegalOperations ||
6983          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6984       SDValue Ops[] =
6985         { N0.getOperand(0), N0.getOperand(1),
6986           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6987           N0.getOperand(2) };
6988       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6989     }
6990
6991     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6992     //      (select_cc x, y, 1.0, 0.0,, cc)
6993     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6994         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6995         (!LegalOperations ||
6996          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6997       SDValue Ops[] =
6998         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6999           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7000           N0.getOperand(0).getOperand(2) };
7001       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7002     }
7003   }
7004
7005   return SDValue();
7006 }
7007
7008 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7009   SDValue N0 = N->getOperand(0);
7010   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7011   EVT VT = N->getValueType(0);
7012   EVT OpVT = N0.getValueType();
7013
7014   // fold (uint_to_fp c1) -> c1fp
7015   if (N0C &&
7016       // ...but only if the target supports immediate floating-point values
7017       (!LegalOperations ||
7018        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7019     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7020
7021   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7022   // but SINT_TO_FP is legal on this target, try to convert.
7023   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7024       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7025     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7026     if (DAG.SignBitIsZero(N0))
7027       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7028   }
7029
7030   // The next optimizations are desirable only if SELECT_CC can be lowered.
7031   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
7032   // having to say they don't support SELECT_CC on every type the DAG knows
7033   // about, since there is no way to mark an opcode illegal at all value types
7034   // (See also visitSELECT)
7035   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
7036     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7037
7038     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7039         (!LegalOperations ||
7040          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7041       SDValue Ops[] =
7042         { N0.getOperand(0), N0.getOperand(1),
7043           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7044           N0.getOperand(2) };
7045       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
7046     }
7047   }
7048
7049   return SDValue();
7050 }
7051
7052 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7053   SDValue N0 = N->getOperand(0);
7054   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7055   EVT VT = N->getValueType(0);
7056
7057   // fold (fp_to_sint c1fp) -> c1
7058   if (N0CFP)
7059     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7060
7061   return SDValue();
7062 }
7063
7064 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7065   SDValue N0 = N->getOperand(0);
7066   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7067   EVT VT = N->getValueType(0);
7068
7069   // fold (fp_to_uint c1fp) -> c1
7070   if (N0CFP)
7071     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7072
7073   return SDValue();
7074 }
7075
7076 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7077   SDValue N0 = N->getOperand(0);
7078   SDValue N1 = N->getOperand(1);
7079   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7080   EVT VT = N->getValueType(0);
7081
7082   // fold (fp_round c1fp) -> c1fp
7083   if (N0CFP)
7084     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7085
7086   // fold (fp_round (fp_extend x)) -> x
7087   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7088     return N0.getOperand(0);
7089
7090   // fold (fp_round (fp_round x)) -> (fp_round x)
7091   if (N0.getOpcode() == ISD::FP_ROUND) {
7092     // This is a value preserving truncation if both round's are.
7093     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7094                    N0.getNode()->getConstantOperandVal(1) == 1;
7095     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7096                        DAG.getIntPtrConstant(IsTrunc));
7097   }
7098
7099   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7100   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7101     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7102                               N0.getOperand(0), N1);
7103     AddToWorkList(Tmp.getNode());
7104     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7105                        Tmp, N0.getOperand(1));
7106   }
7107
7108   return SDValue();
7109 }
7110
7111 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7112   SDValue N0 = N->getOperand(0);
7113   EVT VT = N->getValueType(0);
7114   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7115   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7116
7117   // fold (fp_round_inreg c1fp) -> c1fp
7118   if (N0CFP && isTypeLegal(EVT)) {
7119     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7120     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7121   }
7122
7123   return SDValue();
7124 }
7125
7126 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7127   SDValue N0 = N->getOperand(0);
7128   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7129   EVT VT = N->getValueType(0);
7130
7131   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7132   if (N->hasOneUse() &&
7133       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7134     return SDValue();
7135
7136   // fold (fp_extend c1fp) -> c1fp
7137   if (N0CFP)
7138     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7139
7140   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7141   // value of X.
7142   if (N0.getOpcode() == ISD::FP_ROUND
7143       && N0.getNode()->getConstantOperandVal(1) == 1) {
7144     SDValue In = N0.getOperand(0);
7145     if (In.getValueType() == VT) return In;
7146     if (VT.bitsLT(In.getValueType()))
7147       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7148                          In, N0.getOperand(1));
7149     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7150   }
7151
7152   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7153   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7154       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7155        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7156     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7157     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7158                                      LN0->getChain(),
7159                                      LN0->getBasePtr(), N0.getValueType(),
7160                                      LN0->getMemOperand());
7161     CombineTo(N, ExtLoad);
7162     CombineTo(N0.getNode(),
7163               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7164                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7165               ExtLoad.getValue(1));
7166     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7167   }
7168
7169   return SDValue();
7170 }
7171
7172 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7173   SDValue N0 = N->getOperand(0);
7174   EVT VT = N->getValueType(0);
7175
7176   if (VT.isVector()) {
7177     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7178     if (FoldedVOp.getNode()) return FoldedVOp;
7179   }
7180
7181   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7182                          &DAG.getTarget().Options))
7183     return GetNegatedExpression(N0, DAG, LegalOperations);
7184
7185   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7186   // constant pool values.
7187   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7188       !VT.isVector() &&
7189       N0.getNode()->hasOneUse() &&
7190       N0.getOperand(0).getValueType().isInteger()) {
7191     SDValue Int = N0.getOperand(0);
7192     EVT IntVT = Int.getValueType();
7193     if (IntVT.isInteger() && !IntVT.isVector()) {
7194       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7195               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7196       AddToWorkList(Int.getNode());
7197       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7198                          VT, Int);
7199     }
7200   }
7201
7202   // (fneg (fmul c, x)) -> (fmul -c, x)
7203   if (N0.getOpcode() == ISD::FMUL) {
7204     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7205     if (CFP1)
7206       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7207                          N0.getOperand(0),
7208                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7209                                      N0.getOperand(1)));
7210   }
7211
7212   return SDValue();
7213 }
7214
7215 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7216   SDValue N0 = N->getOperand(0);
7217   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7218   EVT VT = N->getValueType(0);
7219
7220   // fold (fceil c1) -> fceil(c1)
7221   if (N0CFP)
7222     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7223
7224   return SDValue();
7225 }
7226
7227 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7228   SDValue N0 = N->getOperand(0);
7229   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7230   EVT VT = N->getValueType(0);
7231
7232   // fold (ftrunc c1) -> ftrunc(c1)
7233   if (N0CFP)
7234     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7235
7236   return SDValue();
7237 }
7238
7239 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7240   SDValue N0 = N->getOperand(0);
7241   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7242   EVT VT = N->getValueType(0);
7243
7244   // fold (ffloor c1) -> ffloor(c1)
7245   if (N0CFP)
7246     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7247
7248   return SDValue();
7249 }
7250
7251 SDValue DAGCombiner::visitFABS(SDNode *N) {
7252   SDValue N0 = N->getOperand(0);
7253   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7254   EVT VT = N->getValueType(0);
7255
7256   if (VT.isVector()) {
7257     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7258     if (FoldedVOp.getNode()) return FoldedVOp;
7259   }
7260
7261   // fold (fabs c1) -> fabs(c1)
7262   if (N0CFP)
7263     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7264   // fold (fabs (fabs x)) -> (fabs x)
7265   if (N0.getOpcode() == ISD::FABS)
7266     return N->getOperand(0);
7267   // fold (fabs (fneg x)) -> (fabs x)
7268   // fold (fabs (fcopysign x, y)) -> (fabs x)
7269   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7270     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7271
7272   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7273   // constant pool values.
7274   if (!TLI.isFAbsFree(VT) &&
7275       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7276       N0.getOperand(0).getValueType().isInteger() &&
7277       !N0.getOperand(0).getValueType().isVector()) {
7278     SDValue Int = N0.getOperand(0);
7279     EVT IntVT = Int.getValueType();
7280     if (IntVT.isInteger() && !IntVT.isVector()) {
7281       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7282              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7283       AddToWorkList(Int.getNode());
7284       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7285                          N->getValueType(0), Int);
7286     }
7287   }
7288
7289   return SDValue();
7290 }
7291
7292 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7293   SDValue Chain = N->getOperand(0);
7294   SDValue N1 = N->getOperand(1);
7295   SDValue N2 = N->getOperand(2);
7296
7297   // If N is a constant we could fold this into a fallthrough or unconditional
7298   // branch. However that doesn't happen very often in normal code, because
7299   // Instcombine/SimplifyCFG should have handled the available opportunities.
7300   // If we did this folding here, it would be necessary to update the
7301   // MachineBasicBlock CFG, which is awkward.
7302
7303   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7304   // on the target.
7305   if (N1.getOpcode() == ISD::SETCC &&
7306       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7307                                    N1.getOperand(0).getValueType())) {
7308     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7309                        Chain, N1.getOperand(2),
7310                        N1.getOperand(0), N1.getOperand(1), N2);
7311   }
7312
7313   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7314       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7315        (N1.getOperand(0).hasOneUse() &&
7316         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7317     SDNode *Trunc = nullptr;
7318     if (N1.getOpcode() == ISD::TRUNCATE) {
7319       // Look pass the truncate.
7320       Trunc = N1.getNode();
7321       N1 = N1.getOperand(0);
7322     }
7323
7324     // Match this pattern so that we can generate simpler code:
7325     //
7326     //   %a = ...
7327     //   %b = and i32 %a, 2
7328     //   %c = srl i32 %b, 1
7329     //   brcond i32 %c ...
7330     //
7331     // into
7332     //
7333     //   %a = ...
7334     //   %b = and i32 %a, 2
7335     //   %c = setcc eq %b, 0
7336     //   brcond %c ...
7337     //
7338     // This applies only when the AND constant value has one bit set and the
7339     // SRL constant is equal to the log2 of the AND constant. The back-end is
7340     // smart enough to convert the result into a TEST/JMP sequence.
7341     SDValue Op0 = N1.getOperand(0);
7342     SDValue Op1 = N1.getOperand(1);
7343
7344     if (Op0.getOpcode() == ISD::AND &&
7345         Op1.getOpcode() == ISD::Constant) {
7346       SDValue AndOp1 = Op0.getOperand(1);
7347
7348       if (AndOp1.getOpcode() == ISD::Constant) {
7349         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7350
7351         if (AndConst.isPowerOf2() &&
7352             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7353           SDValue SetCC =
7354             DAG.getSetCC(SDLoc(N),
7355                          getSetCCResultType(Op0.getValueType()),
7356                          Op0, DAG.getConstant(0, Op0.getValueType()),
7357                          ISD::SETNE);
7358
7359           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7360                                           MVT::Other, Chain, SetCC, N2);
7361           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7362           // will convert it back to (X & C1) >> C2.
7363           CombineTo(N, NewBRCond, false);
7364           // Truncate is dead.
7365           if (Trunc) {
7366             removeFromWorkList(Trunc);
7367             DAG.DeleteNode(Trunc);
7368           }
7369           // Replace the uses of SRL with SETCC
7370           WorkListRemover DeadNodes(*this);
7371           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7372           removeFromWorkList(N1.getNode());
7373           DAG.DeleteNode(N1.getNode());
7374           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7375         }
7376       }
7377     }
7378
7379     if (Trunc)
7380       // Restore N1 if the above transformation doesn't match.
7381       N1 = N->getOperand(1);
7382   }
7383
7384   // Transform br(xor(x, y)) -> br(x != y)
7385   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7386   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7387     SDNode *TheXor = N1.getNode();
7388     SDValue Op0 = TheXor->getOperand(0);
7389     SDValue Op1 = TheXor->getOperand(1);
7390     if (Op0.getOpcode() == Op1.getOpcode()) {
7391       // Avoid missing important xor optimizations.
7392       SDValue Tmp = visitXOR(TheXor);
7393       if (Tmp.getNode()) {
7394         if (Tmp.getNode() != TheXor) {
7395           DEBUG(dbgs() << "\nReplacing.8 ";
7396                 TheXor->dump(&DAG);
7397                 dbgs() << "\nWith: ";
7398                 Tmp.getNode()->dump(&DAG);
7399                 dbgs() << '\n');
7400           WorkListRemover DeadNodes(*this);
7401           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7402           removeFromWorkList(TheXor);
7403           DAG.DeleteNode(TheXor);
7404           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7405                              MVT::Other, Chain, Tmp, N2);
7406         }
7407
7408         // visitXOR has changed XOR's operands or replaced the XOR completely,
7409         // bail out.
7410         return SDValue(N, 0);
7411       }
7412     }
7413
7414     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7415       bool Equal = false;
7416       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7417         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7418             Op0.getOpcode() == ISD::XOR) {
7419           TheXor = Op0.getNode();
7420           Equal = true;
7421         }
7422
7423       EVT SetCCVT = N1.getValueType();
7424       if (LegalTypes)
7425         SetCCVT = getSetCCResultType(SetCCVT);
7426       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7427                                    SetCCVT,
7428                                    Op0, Op1,
7429                                    Equal ? ISD::SETEQ : ISD::SETNE);
7430       // Replace the uses of XOR with SETCC
7431       WorkListRemover DeadNodes(*this);
7432       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7433       removeFromWorkList(N1.getNode());
7434       DAG.DeleteNode(N1.getNode());
7435       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7436                          MVT::Other, Chain, SetCC, N2);
7437     }
7438   }
7439
7440   return SDValue();
7441 }
7442
7443 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7444 //
7445 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7446   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7447   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7448
7449   // If N is a constant we could fold this into a fallthrough or unconditional
7450   // branch. However that doesn't happen very often in normal code, because
7451   // Instcombine/SimplifyCFG should have handled the available opportunities.
7452   // If we did this folding here, it would be necessary to update the
7453   // MachineBasicBlock CFG, which is awkward.
7454
7455   // Use SimplifySetCC to simplify SETCC's.
7456   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7457                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7458                                false);
7459   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7460
7461   // fold to a simpler setcc
7462   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7463     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7464                        N->getOperand(0), Simp.getOperand(2),
7465                        Simp.getOperand(0), Simp.getOperand(1),
7466                        N->getOperand(4));
7467
7468   return SDValue();
7469 }
7470
7471 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7472 /// uses N as its base pointer and that N may be folded in the load / store
7473 /// addressing mode.
7474 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7475                                     SelectionDAG &DAG,
7476                                     const TargetLowering &TLI) {
7477   EVT VT;
7478   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7479     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7480       return false;
7481     VT = Use->getValueType(0);
7482   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7483     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7484       return false;
7485     VT = ST->getValue().getValueType();
7486   } else
7487     return false;
7488
7489   TargetLowering::AddrMode AM;
7490   if (N->getOpcode() == ISD::ADD) {
7491     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7492     if (Offset)
7493       // [reg +/- imm]
7494       AM.BaseOffs = Offset->getSExtValue();
7495     else
7496       // [reg +/- reg]
7497       AM.Scale = 1;
7498   } else if (N->getOpcode() == ISD::SUB) {
7499     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7500     if (Offset)
7501       // [reg +/- imm]
7502       AM.BaseOffs = -Offset->getSExtValue();
7503     else
7504       // [reg +/- reg]
7505       AM.Scale = 1;
7506   } else
7507     return false;
7508
7509   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7510 }
7511
7512 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7513 /// pre-indexed load / store when the base pointer is an add or subtract
7514 /// and it has other uses besides the load / store. After the
7515 /// transformation, the new indexed load / store has effectively folded
7516 /// the add / subtract in and all of its other uses are redirected to the
7517 /// new load / store.
7518 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7519   if (Level < AfterLegalizeDAG)
7520     return false;
7521
7522   bool isLoad = true;
7523   SDValue Ptr;
7524   EVT VT;
7525   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7526     if (LD->isIndexed())
7527       return false;
7528     VT = LD->getMemoryVT();
7529     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7530         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7531       return false;
7532     Ptr = LD->getBasePtr();
7533   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7534     if (ST->isIndexed())
7535       return false;
7536     VT = ST->getMemoryVT();
7537     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7538         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7539       return false;
7540     Ptr = ST->getBasePtr();
7541     isLoad = false;
7542   } else {
7543     return false;
7544   }
7545
7546   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7547   // out.  There is no reason to make this a preinc/predec.
7548   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7549       Ptr.getNode()->hasOneUse())
7550     return false;
7551
7552   // Ask the target to do addressing mode selection.
7553   SDValue BasePtr;
7554   SDValue Offset;
7555   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7556   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7557     return false;
7558
7559   // Backends without true r+i pre-indexed forms may need to pass a
7560   // constant base with a variable offset so that constant coercion
7561   // will work with the patterns in canonical form.
7562   bool Swapped = false;
7563   if (isa<ConstantSDNode>(BasePtr)) {
7564     std::swap(BasePtr, Offset);
7565     Swapped = true;
7566   }
7567
7568   // Don't create a indexed load / store with zero offset.
7569   if (isa<ConstantSDNode>(Offset) &&
7570       cast<ConstantSDNode>(Offset)->isNullValue())
7571     return false;
7572
7573   // Try turning it into a pre-indexed load / store except when:
7574   // 1) The new base ptr is a frame index.
7575   // 2) If N is a store and the new base ptr is either the same as or is a
7576   //    predecessor of the value being stored.
7577   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7578   //    that would create a cycle.
7579   // 4) All uses are load / store ops that use it as old base ptr.
7580
7581   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7582   // (plus the implicit offset) to a register to preinc anyway.
7583   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7584     return false;
7585
7586   // Check #2.
7587   if (!isLoad) {
7588     SDValue Val = cast<StoreSDNode>(N)->getValue();
7589     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7590       return false;
7591   }
7592
7593   // If the offset is a constant, there may be other adds of constants that
7594   // can be folded with this one. We should do this to avoid having to keep
7595   // a copy of the original base pointer.
7596   SmallVector<SDNode *, 16> OtherUses;
7597   if (isa<ConstantSDNode>(Offset))
7598     for (SDNode *Use : BasePtr.getNode()->uses()) {
7599       if (Use == Ptr.getNode())
7600         continue;
7601
7602       if (Use->isPredecessorOf(N))
7603         continue;
7604
7605       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7606         OtherUses.clear();
7607         break;
7608       }
7609
7610       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7611       if (Op1.getNode() == BasePtr.getNode())
7612         std::swap(Op0, Op1);
7613       assert(Op0.getNode() == BasePtr.getNode() &&
7614              "Use of ADD/SUB but not an operand");
7615
7616       if (!isa<ConstantSDNode>(Op1)) {
7617         OtherUses.clear();
7618         break;
7619       }
7620
7621       // FIXME: In some cases, we can be smarter about this.
7622       if (Op1.getValueType() != Offset.getValueType()) {
7623         OtherUses.clear();
7624         break;
7625       }
7626
7627       OtherUses.push_back(Use);
7628     }
7629
7630   if (Swapped)
7631     std::swap(BasePtr, Offset);
7632
7633   // Now check for #3 and #4.
7634   bool RealUse = false;
7635
7636   // Caches for hasPredecessorHelper
7637   SmallPtrSet<const SDNode *, 32> Visited;
7638   SmallVector<const SDNode *, 16> Worklist;
7639
7640   for (SDNode *Use : Ptr.getNode()->uses()) {
7641     if (Use == N)
7642       continue;
7643     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7644       return false;
7645
7646     // If Ptr may be folded in addressing mode of other use, then it's
7647     // not profitable to do this transformation.
7648     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7649       RealUse = true;
7650   }
7651
7652   if (!RealUse)
7653     return false;
7654
7655   SDValue Result;
7656   if (isLoad)
7657     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7658                                 BasePtr, Offset, AM);
7659   else
7660     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7661                                  BasePtr, Offset, AM);
7662   ++PreIndexedNodes;
7663   ++NodesCombined;
7664   DEBUG(dbgs() << "\nReplacing.4 ";
7665         N->dump(&DAG);
7666         dbgs() << "\nWith: ";
7667         Result.getNode()->dump(&DAG);
7668         dbgs() << '\n');
7669   WorkListRemover DeadNodes(*this);
7670   if (isLoad) {
7671     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7672     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7673   } else {
7674     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7675   }
7676
7677   // Finally, since the node is now dead, remove it from the graph.
7678   DAG.DeleteNode(N);
7679
7680   if (Swapped)
7681     std::swap(BasePtr, Offset);
7682
7683   // Replace other uses of BasePtr that can be updated to use Ptr
7684   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7685     unsigned OffsetIdx = 1;
7686     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7687       OffsetIdx = 0;
7688     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7689            BasePtr.getNode() && "Expected BasePtr operand");
7690
7691     // We need to replace ptr0 in the following expression:
7692     //   x0 * offset0 + y0 * ptr0 = t0
7693     // knowing that
7694     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7695     //
7696     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7697     // indexed load/store and the expresion that needs to be re-written.
7698     //
7699     // Therefore, we have:
7700     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7701
7702     ConstantSDNode *CN =
7703       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7704     int X0, X1, Y0, Y1;
7705     APInt Offset0 = CN->getAPIntValue();
7706     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7707
7708     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7709     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7710     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7711     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7712
7713     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7714
7715     APInt CNV = Offset0;
7716     if (X0 < 0) CNV = -CNV;
7717     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7718     else CNV = CNV - Offset1;
7719
7720     // We can now generate the new expression.
7721     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7722     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7723
7724     SDValue NewUse = DAG.getNode(Opcode,
7725                                  SDLoc(OtherUses[i]),
7726                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7727     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7728     removeFromWorkList(OtherUses[i]);
7729     DAG.DeleteNode(OtherUses[i]);
7730   }
7731
7732   // Replace the uses of Ptr with uses of the updated base value.
7733   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7734   removeFromWorkList(Ptr.getNode());
7735   DAG.DeleteNode(Ptr.getNode());
7736
7737   return true;
7738 }
7739
7740 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7741 /// add / sub of the base pointer node into a post-indexed load / store.
7742 /// The transformation folded the add / subtract into the new indexed
7743 /// load / store effectively and all of its uses are redirected to the
7744 /// new load / store.
7745 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7746   if (Level < AfterLegalizeDAG)
7747     return false;
7748
7749   bool isLoad = true;
7750   SDValue Ptr;
7751   EVT VT;
7752   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7753     if (LD->isIndexed())
7754       return false;
7755     VT = LD->getMemoryVT();
7756     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7757         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7758       return false;
7759     Ptr = LD->getBasePtr();
7760   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7761     if (ST->isIndexed())
7762       return false;
7763     VT = ST->getMemoryVT();
7764     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7765         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7766       return false;
7767     Ptr = ST->getBasePtr();
7768     isLoad = false;
7769   } else {
7770     return false;
7771   }
7772
7773   if (Ptr.getNode()->hasOneUse())
7774     return false;
7775
7776   for (SDNode *Op : Ptr.getNode()->uses()) {
7777     if (Op == N ||
7778         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7779       continue;
7780
7781     SDValue BasePtr;
7782     SDValue Offset;
7783     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7784     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7785       // Don't create a indexed load / store with zero offset.
7786       if (isa<ConstantSDNode>(Offset) &&
7787           cast<ConstantSDNode>(Offset)->isNullValue())
7788         continue;
7789
7790       // Try turning it into a post-indexed load / store except when
7791       // 1) All uses are load / store ops that use it as base ptr (and
7792       //    it may be folded as addressing mmode).
7793       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7794       //    nor a successor of N. Otherwise, if Op is folded that would
7795       //    create a cycle.
7796
7797       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7798         continue;
7799
7800       // Check for #1.
7801       bool TryNext = false;
7802       for (SDNode *Use : BasePtr.getNode()->uses()) {
7803         if (Use == Ptr.getNode())
7804           continue;
7805
7806         // If all the uses are load / store addresses, then don't do the
7807         // transformation.
7808         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7809           bool RealUse = false;
7810           for (SDNode *UseUse : Use->uses()) {
7811             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7812               RealUse = true;
7813           }
7814
7815           if (!RealUse) {
7816             TryNext = true;
7817             break;
7818           }
7819         }
7820       }
7821
7822       if (TryNext)
7823         continue;
7824
7825       // Check for #2
7826       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7827         SDValue Result = isLoad
7828           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7829                                BasePtr, Offset, AM)
7830           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7831                                 BasePtr, Offset, AM);
7832         ++PostIndexedNodes;
7833         ++NodesCombined;
7834         DEBUG(dbgs() << "\nReplacing.5 ";
7835               N->dump(&DAG);
7836               dbgs() << "\nWith: ";
7837               Result.getNode()->dump(&DAG);
7838               dbgs() << '\n');
7839         WorkListRemover DeadNodes(*this);
7840         if (isLoad) {
7841           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7842           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7843         } else {
7844           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7845         }
7846
7847         // Finally, since the node is now dead, remove it from the graph.
7848         DAG.DeleteNode(N);
7849
7850         // Replace the uses of Use with uses of the updated base value.
7851         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7852                                       Result.getValue(isLoad ? 1 : 0));
7853         removeFromWorkList(Op);
7854         DAG.DeleteNode(Op);
7855         return true;
7856       }
7857     }
7858   }
7859
7860   return false;
7861 }
7862
7863 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7864   LoadSDNode *LD  = cast<LoadSDNode>(N);
7865   SDValue Chain = LD->getChain();
7866   SDValue Ptr   = LD->getBasePtr();
7867
7868   // If load is not volatile and there are no uses of the loaded value (and
7869   // the updated indexed value in case of indexed loads), change uses of the
7870   // chain value into uses of the chain input (i.e. delete the dead load).
7871   if (!LD->isVolatile()) {
7872     if (N->getValueType(1) == MVT::Other) {
7873       // Unindexed loads.
7874       if (!N->hasAnyUseOfValue(0)) {
7875         // It's not safe to use the two value CombineTo variant here. e.g.
7876         // v1, chain2 = load chain1, loc
7877         // v2, chain3 = load chain2, loc
7878         // v3         = add v2, c
7879         // Now we replace use of chain2 with chain1.  This makes the second load
7880         // isomorphic to the one we are deleting, and thus makes this load live.
7881         DEBUG(dbgs() << "\nReplacing.6 ";
7882               N->dump(&DAG);
7883               dbgs() << "\nWith chain: ";
7884               Chain.getNode()->dump(&DAG);
7885               dbgs() << "\n");
7886         WorkListRemover DeadNodes(*this);
7887         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7888
7889         if (N->use_empty()) {
7890           removeFromWorkList(N);
7891           DAG.DeleteNode(N);
7892         }
7893
7894         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7895       }
7896     } else {
7897       // Indexed loads.
7898       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7899       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7900         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7901         DEBUG(dbgs() << "\nReplacing.7 ";
7902               N->dump(&DAG);
7903               dbgs() << "\nWith: ";
7904               Undef.getNode()->dump(&DAG);
7905               dbgs() << " and 2 other values\n");
7906         WorkListRemover DeadNodes(*this);
7907         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7908         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7909                                       DAG.getUNDEF(N->getValueType(1)));
7910         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7911         removeFromWorkList(N);
7912         DAG.DeleteNode(N);
7913         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7914       }
7915     }
7916   }
7917
7918   // If this load is directly stored, replace the load value with the stored
7919   // value.
7920   // TODO: Handle store large -> read small portion.
7921   // TODO: Handle TRUNCSTORE/LOADEXT
7922   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7923     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7924       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7925       if (PrevST->getBasePtr() == Ptr &&
7926           PrevST->getValue().getValueType() == N->getValueType(0))
7927       return CombineTo(N, Chain.getOperand(1), Chain);
7928     }
7929   }
7930
7931   // Try to infer better alignment information than the load already has.
7932   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7933     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7934       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7935         SDValue NewLoad =
7936                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7937                               LD->getValueType(0),
7938                               Chain, Ptr, LD->getPointerInfo(),
7939                               LD->getMemoryVT(),
7940                               LD->isVolatile(), LD->isNonTemporal(), Align,
7941                               LD->getTBAAInfo());
7942         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7943       }
7944     }
7945   }
7946
7947   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7948     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7949 #ifndef NDEBUG
7950   if (CombinerAAOnlyFunc.getNumOccurrences() &&
7951       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7952     UseAA = false;
7953 #endif
7954   if (UseAA && LD->isUnindexed()) {
7955     // Walk up chain skipping non-aliasing memory nodes.
7956     SDValue BetterChain = FindBetterChain(N, Chain);
7957
7958     // If there is a better chain.
7959     if (Chain != BetterChain) {
7960       SDValue ReplLoad;
7961
7962       // Replace the chain to void dependency.
7963       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7964         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7965                                BetterChain, Ptr, LD->getMemOperand());
7966       } else {
7967         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7968                                   LD->getValueType(0),
7969                                   BetterChain, Ptr, LD->getMemoryVT(),
7970                                   LD->getMemOperand());
7971       }
7972
7973       // Create token factor to keep old chain connected.
7974       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7975                                   MVT::Other, Chain, ReplLoad.getValue(1));
7976
7977       // Make sure the new and old chains are cleaned up.
7978       AddToWorkList(Token.getNode());
7979
7980       // Replace uses with load result and token factor. Don't add users
7981       // to work list.
7982       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7983     }
7984   }
7985
7986   // Try transforming N to an indexed load.
7987   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7988     return SDValue(N, 0);
7989
7990   // Try to slice up N to more direct loads if the slices are mapped to
7991   // different register banks or pairing can take place.
7992   if (SliceUpLoad(N))
7993     return SDValue(N, 0);
7994
7995   return SDValue();
7996 }
7997
7998 namespace {
7999 /// \brief Helper structure used to slice a load in smaller loads.
8000 /// Basically a slice is obtained from the following sequence:
8001 /// Origin = load Ty1, Base
8002 /// Shift = srl Ty1 Origin, CstTy Amount
8003 /// Inst = trunc Shift to Ty2
8004 ///
8005 /// Then, it will be rewriten into:
8006 /// Slice = load SliceTy, Base + SliceOffset
8007 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8008 ///
8009 /// SliceTy is deduced from the number of bits that are actually used to
8010 /// build Inst.
8011 struct LoadedSlice {
8012   /// \brief Helper structure used to compute the cost of a slice.
8013   struct Cost {
8014     /// Are we optimizing for code size.
8015     bool ForCodeSize;
8016     /// Various cost.
8017     unsigned Loads;
8018     unsigned Truncates;
8019     unsigned CrossRegisterBanksCopies;
8020     unsigned ZExts;
8021     unsigned Shift;
8022
8023     Cost(bool ForCodeSize = false)
8024         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8025           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8026
8027     /// \brief Get the cost of one isolated slice.
8028     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8029         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8030           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8031       EVT TruncType = LS.Inst->getValueType(0);
8032       EVT LoadedType = LS.getLoadedType();
8033       if (TruncType != LoadedType &&
8034           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8035         ZExts = 1;
8036     }
8037
8038     /// \brief Account for slicing gain in the current cost.
8039     /// Slicing provide a few gains like removing a shift or a
8040     /// truncate. This method allows to grow the cost of the original
8041     /// load with the gain from this slice.
8042     void addSliceGain(const LoadedSlice &LS) {
8043       // Each slice saves a truncate.
8044       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8045       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8046                               LS.Inst->getOperand(0).getValueType()))
8047         ++Truncates;
8048       // If there is a shift amount, this slice gets rid of it.
8049       if (LS.Shift)
8050         ++Shift;
8051       // If this slice can merge a cross register bank copy, account for it.
8052       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8053         ++CrossRegisterBanksCopies;
8054     }
8055
8056     Cost &operator+=(const Cost &RHS) {
8057       Loads += RHS.Loads;
8058       Truncates += RHS.Truncates;
8059       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8060       ZExts += RHS.ZExts;
8061       Shift += RHS.Shift;
8062       return *this;
8063     }
8064
8065     bool operator==(const Cost &RHS) const {
8066       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8067              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8068              ZExts == RHS.ZExts && Shift == RHS.Shift;
8069     }
8070
8071     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8072
8073     bool operator<(const Cost &RHS) const {
8074       // Assume cross register banks copies are as expensive as loads.
8075       // FIXME: Do we want some more target hooks?
8076       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8077       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8078       // Unless we are optimizing for code size, consider the
8079       // expensive operation first.
8080       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8081         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8082       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8083              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8084     }
8085
8086     bool operator>(const Cost &RHS) const { return RHS < *this; }
8087
8088     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8089
8090     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8091   };
8092   // The last instruction that represent the slice. This should be a
8093   // truncate instruction.
8094   SDNode *Inst;
8095   // The original load instruction.
8096   LoadSDNode *Origin;
8097   // The right shift amount in bits from the original load.
8098   unsigned Shift;
8099   // The DAG from which Origin came from.
8100   // This is used to get some contextual information about legal types, etc.
8101   SelectionDAG *DAG;
8102
8103   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8104               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8105       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8106
8107   LoadedSlice(const LoadedSlice &LS)
8108       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8109
8110   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8111   /// \return Result is \p BitWidth and has used bits set to 1 and
8112   ///         not used bits set to 0.
8113   APInt getUsedBits() const {
8114     // Reproduce the trunc(lshr) sequence:
8115     // - Start from the truncated value.
8116     // - Zero extend to the desired bit width.
8117     // - Shift left.
8118     assert(Origin && "No original load to compare against.");
8119     unsigned BitWidth = Origin->getValueSizeInBits(0);
8120     assert(Inst && "This slice is not bound to an instruction");
8121     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8122            "Extracted slice is bigger than the whole type!");
8123     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8124     UsedBits.setAllBits();
8125     UsedBits = UsedBits.zext(BitWidth);
8126     UsedBits <<= Shift;
8127     return UsedBits;
8128   }
8129
8130   /// \brief Get the size of the slice to be loaded in bytes.
8131   unsigned getLoadedSize() const {
8132     unsigned SliceSize = getUsedBits().countPopulation();
8133     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8134     return SliceSize / 8;
8135   }
8136
8137   /// \brief Get the type that will be loaded for this slice.
8138   /// Note: This may not be the final type for the slice.
8139   EVT getLoadedType() const {
8140     assert(DAG && "Missing context");
8141     LLVMContext &Ctxt = *DAG->getContext();
8142     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8143   }
8144
8145   /// \brief Get the alignment of the load used for this slice.
8146   unsigned getAlignment() const {
8147     unsigned Alignment = Origin->getAlignment();
8148     unsigned Offset = getOffsetFromBase();
8149     if (Offset != 0)
8150       Alignment = MinAlign(Alignment, Alignment + Offset);
8151     return Alignment;
8152   }
8153
8154   /// \brief Check if this slice can be rewritten with legal operations.
8155   bool isLegal() const {
8156     // An invalid slice is not legal.
8157     if (!Origin || !Inst || !DAG)
8158       return false;
8159
8160     // Offsets are for indexed load only, we do not handle that.
8161     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8162       return false;
8163
8164     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8165
8166     // Check that the type is legal.
8167     EVT SliceType = getLoadedType();
8168     if (!TLI.isTypeLegal(SliceType))
8169       return false;
8170
8171     // Check that the load is legal for this type.
8172     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8173       return false;
8174
8175     // Check that the offset can be computed.
8176     // 1. Check its type.
8177     EVT PtrType = Origin->getBasePtr().getValueType();
8178     if (PtrType == MVT::Untyped || PtrType.isExtended())
8179       return false;
8180
8181     // 2. Check that it fits in the immediate.
8182     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8183       return false;
8184
8185     // 3. Check that the computation is legal.
8186     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8187       return false;
8188
8189     // Check that the zext is legal if it needs one.
8190     EVT TruncateType = Inst->getValueType(0);
8191     if (TruncateType != SliceType &&
8192         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8193       return false;
8194
8195     return true;
8196   }
8197
8198   /// \brief Get the offset in bytes of this slice in the original chunk of
8199   /// bits.
8200   /// \pre DAG != nullptr.
8201   uint64_t getOffsetFromBase() const {
8202     assert(DAG && "Missing context.");
8203     bool IsBigEndian =
8204         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8205     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8206     uint64_t Offset = Shift / 8;
8207     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8208     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8209            "The size of the original loaded type is not a multiple of a"
8210            " byte.");
8211     // If Offset is bigger than TySizeInBytes, it means we are loading all
8212     // zeros. This should have been optimized before in the process.
8213     assert(TySizeInBytes > Offset &&
8214            "Invalid shift amount for given loaded size");
8215     if (IsBigEndian)
8216       Offset = TySizeInBytes - Offset - getLoadedSize();
8217     return Offset;
8218   }
8219
8220   /// \brief Generate the sequence of instructions to load the slice
8221   /// represented by this object and redirect the uses of this slice to
8222   /// this new sequence of instructions.
8223   /// \pre this->Inst && this->Origin are valid Instructions and this
8224   /// object passed the legal check: LoadedSlice::isLegal returned true.
8225   /// \return The last instruction of the sequence used to load the slice.
8226   SDValue loadSlice() const {
8227     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8228     const SDValue &OldBaseAddr = Origin->getBasePtr();
8229     SDValue BaseAddr = OldBaseAddr;
8230     // Get the offset in that chunk of bytes w.r.t. the endianess.
8231     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8232     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8233     if (Offset) {
8234       // BaseAddr = BaseAddr + Offset.
8235       EVT ArithType = BaseAddr.getValueType();
8236       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8237                               DAG->getConstant(Offset, ArithType));
8238     }
8239
8240     // Create the type of the loaded slice according to its size.
8241     EVT SliceType = getLoadedType();
8242
8243     // Create the load for the slice.
8244     SDValue LastInst = DAG->getLoad(
8245         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8246         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8247         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8248     // If the final type is not the same as the loaded type, this means that
8249     // we have to pad with zero. Create a zero extend for that.
8250     EVT FinalType = Inst->getValueType(0);
8251     if (SliceType != FinalType)
8252       LastInst =
8253           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8254     return LastInst;
8255   }
8256
8257   /// \brief Check if this slice can be merged with an expensive cross register
8258   /// bank copy. E.g.,
8259   /// i = load i32
8260   /// f = bitcast i32 i to float
8261   bool canMergeExpensiveCrossRegisterBankCopy() const {
8262     if (!Inst || !Inst->hasOneUse())
8263       return false;
8264     SDNode *Use = *Inst->use_begin();
8265     if (Use->getOpcode() != ISD::BITCAST)
8266       return false;
8267     assert(DAG && "Missing context");
8268     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8269     EVT ResVT = Use->getValueType(0);
8270     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8271     const TargetRegisterClass *ArgRC =
8272         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8273     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8274       return false;
8275
8276     // At this point, we know that we perform a cross-register-bank copy.
8277     // Check if it is expensive.
8278     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8279     // Assume bitcasts are cheap, unless both register classes do not
8280     // explicitly share a common sub class.
8281     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8282       return false;
8283
8284     // Check if it will be merged with the load.
8285     // 1. Check the alignment constraint.
8286     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8287         ResVT.getTypeForEVT(*DAG->getContext()));
8288
8289     if (RequiredAlignment > getAlignment())
8290       return false;
8291
8292     // 2. Check that the load is a legal operation for that type.
8293     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8294       return false;
8295
8296     // 3. Check that we do not have a zext in the way.
8297     if (Inst->getValueType(0) != getLoadedType())
8298       return false;
8299
8300     return true;
8301   }
8302 };
8303 }
8304
8305 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8306 /// \p UsedBits looks like 0..0 1..1 0..0.
8307 static bool areUsedBitsDense(const APInt &UsedBits) {
8308   // If all the bits are one, this is dense!
8309   if (UsedBits.isAllOnesValue())
8310     return true;
8311
8312   // Get rid of the unused bits on the right.
8313   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8314   // Get rid of the unused bits on the left.
8315   if (NarrowedUsedBits.countLeadingZeros())
8316     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8317   // Check that the chunk of bits is completely used.
8318   return NarrowedUsedBits.isAllOnesValue();
8319 }
8320
8321 /// \brief Check whether or not \p First and \p Second are next to each other
8322 /// in memory. This means that there is no hole between the bits loaded
8323 /// by \p First and the bits loaded by \p Second.
8324 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8325                                      const LoadedSlice &Second) {
8326   assert(First.Origin == Second.Origin && First.Origin &&
8327          "Unable to match different memory origins.");
8328   APInt UsedBits = First.getUsedBits();
8329   assert((UsedBits & Second.getUsedBits()) == 0 &&
8330          "Slices are not supposed to overlap.");
8331   UsedBits |= Second.getUsedBits();
8332   return areUsedBitsDense(UsedBits);
8333 }
8334
8335 /// \brief Adjust the \p GlobalLSCost according to the target
8336 /// paring capabilities and the layout of the slices.
8337 /// \pre \p GlobalLSCost should account for at least as many loads as
8338 /// there is in the slices in \p LoadedSlices.
8339 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8340                                  LoadedSlice::Cost &GlobalLSCost) {
8341   unsigned NumberOfSlices = LoadedSlices.size();
8342   // If there is less than 2 elements, no pairing is possible.
8343   if (NumberOfSlices < 2)
8344     return;
8345
8346   // Sort the slices so that elements that are likely to be next to each
8347   // other in memory are next to each other in the list.
8348   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8349             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8350     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8351     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8352   });
8353   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8354   // First (resp. Second) is the first (resp. Second) potentially candidate
8355   // to be placed in a paired load.
8356   const LoadedSlice *First = nullptr;
8357   const LoadedSlice *Second = nullptr;
8358   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8359                 // Set the beginning of the pair.
8360                                                            First = Second) {
8361
8362     Second = &LoadedSlices[CurrSlice];
8363
8364     // If First is NULL, it means we start a new pair.
8365     // Get to the next slice.
8366     if (!First)
8367       continue;
8368
8369     EVT LoadedType = First->getLoadedType();
8370
8371     // If the types of the slices are different, we cannot pair them.
8372     if (LoadedType != Second->getLoadedType())
8373       continue;
8374
8375     // Check if the target supplies paired loads for this type.
8376     unsigned RequiredAlignment = 0;
8377     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8378       // move to the next pair, this type is hopeless.
8379       Second = nullptr;
8380       continue;
8381     }
8382     // Check if we meet the alignment requirement.
8383     if (RequiredAlignment > First->getAlignment())
8384       continue;
8385
8386     // Check that both loads are next to each other in memory.
8387     if (!areSlicesNextToEachOther(*First, *Second))
8388       continue;
8389
8390     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8391     --GlobalLSCost.Loads;
8392     // Move to the next pair.
8393     Second = nullptr;
8394   }
8395 }
8396
8397 /// \brief Check the profitability of all involved LoadedSlice.
8398 /// Currently, it is considered profitable if there is exactly two
8399 /// involved slices (1) which are (2) next to each other in memory, and
8400 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8401 ///
8402 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8403 /// the elements themselves.
8404 ///
8405 /// FIXME: When the cost model will be mature enough, we can relax
8406 /// constraints (1) and (2).
8407 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8408                                 const APInt &UsedBits, bool ForCodeSize) {
8409   unsigned NumberOfSlices = LoadedSlices.size();
8410   if (StressLoadSlicing)
8411     return NumberOfSlices > 1;
8412
8413   // Check (1).
8414   if (NumberOfSlices != 2)
8415     return false;
8416
8417   // Check (2).
8418   if (!areUsedBitsDense(UsedBits))
8419     return false;
8420
8421   // Check (3).
8422   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8423   // The original code has one big load.
8424   OrigCost.Loads = 1;
8425   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8426     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8427     // Accumulate the cost of all the slices.
8428     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8429     GlobalSlicingCost += SliceCost;
8430
8431     // Account as cost in the original configuration the gain obtained
8432     // with the current slices.
8433     OrigCost.addSliceGain(LS);
8434   }
8435
8436   // If the target supports paired load, adjust the cost accordingly.
8437   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8438   return OrigCost > GlobalSlicingCost;
8439 }
8440
8441 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8442 /// operations, split it in the various pieces being extracted.
8443 ///
8444 /// This sort of thing is introduced by SROA.
8445 /// This slicing takes care not to insert overlapping loads.
8446 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8447 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8448   if (Level < AfterLegalizeDAG)
8449     return false;
8450
8451   LoadSDNode *LD = cast<LoadSDNode>(N);
8452   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8453       !LD->getValueType(0).isInteger())
8454     return false;
8455
8456   // Keep track of already used bits to detect overlapping values.
8457   // In that case, we will just abort the transformation.
8458   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8459
8460   SmallVector<LoadedSlice, 4> LoadedSlices;
8461
8462   // Check if this load is used as several smaller chunks of bits.
8463   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8464   // of computation for each trunc.
8465   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8466        UI != UIEnd; ++UI) {
8467     // Skip the uses of the chain.
8468     if (UI.getUse().getResNo() != 0)
8469       continue;
8470
8471     SDNode *User = *UI;
8472     unsigned Shift = 0;
8473
8474     // Check if this is a trunc(lshr).
8475     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8476         isa<ConstantSDNode>(User->getOperand(1))) {
8477       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8478       User = *User->use_begin();
8479     }
8480
8481     // At this point, User is a Truncate, iff we encountered, trunc or
8482     // trunc(lshr).
8483     if (User->getOpcode() != ISD::TRUNCATE)
8484       return false;
8485
8486     // The width of the type must be a power of 2 and greater than 8-bits.
8487     // Otherwise the load cannot be represented in LLVM IR.
8488     // Moreover, if we shifted with a non-8-bits multiple, the slice
8489     // will be across several bytes. We do not support that.
8490     unsigned Width = User->getValueSizeInBits(0);
8491     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8492       return 0;
8493
8494     // Build the slice for this chain of computations.
8495     LoadedSlice LS(User, LD, Shift, &DAG);
8496     APInt CurrentUsedBits = LS.getUsedBits();
8497
8498     // Check if this slice overlaps with another.
8499     if ((CurrentUsedBits & UsedBits) != 0)
8500       return false;
8501     // Update the bits used globally.
8502     UsedBits |= CurrentUsedBits;
8503
8504     // Check if the new slice would be legal.
8505     if (!LS.isLegal())
8506       return false;
8507
8508     // Record the slice.
8509     LoadedSlices.push_back(LS);
8510   }
8511
8512   // Abort slicing if it does not seem to be profitable.
8513   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8514     return false;
8515
8516   ++SlicedLoads;
8517
8518   // Rewrite each chain to use an independent load.
8519   // By construction, each chain can be represented by a unique load.
8520
8521   // Prepare the argument for the new token factor for all the slices.
8522   SmallVector<SDValue, 8> ArgChains;
8523   for (SmallVectorImpl<LoadedSlice>::const_iterator
8524            LSIt = LoadedSlices.begin(),
8525            LSItEnd = LoadedSlices.end();
8526        LSIt != LSItEnd; ++LSIt) {
8527     SDValue SliceInst = LSIt->loadSlice();
8528     CombineTo(LSIt->Inst, SliceInst, true);
8529     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8530       SliceInst = SliceInst.getOperand(0);
8531     assert(SliceInst->getOpcode() == ISD::LOAD &&
8532            "It takes more than a zext to get to the loaded slice!!");
8533     ArgChains.push_back(SliceInst.getValue(1));
8534   }
8535
8536   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8537                               &ArgChains[0], ArgChains.size());
8538   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8539   return true;
8540 }
8541
8542 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8543 /// load is having specific bytes cleared out.  If so, return the byte size
8544 /// being masked out and the shift amount.
8545 static std::pair<unsigned, unsigned>
8546 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8547   std::pair<unsigned, unsigned> Result(0, 0);
8548
8549   // Check for the structure we're looking for.
8550   if (V->getOpcode() != ISD::AND ||
8551       !isa<ConstantSDNode>(V->getOperand(1)) ||
8552       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8553     return Result;
8554
8555   // Check the chain and pointer.
8556   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8557   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8558
8559   // The store should be chained directly to the load or be an operand of a
8560   // tokenfactor.
8561   if (LD == Chain.getNode())
8562     ; // ok.
8563   else if (Chain->getOpcode() != ISD::TokenFactor)
8564     return Result; // Fail.
8565   else {
8566     bool isOk = false;
8567     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8568       if (Chain->getOperand(i).getNode() == LD) {
8569         isOk = true;
8570         break;
8571       }
8572     if (!isOk) return Result;
8573   }
8574
8575   // This only handles simple types.
8576   if (V.getValueType() != MVT::i16 &&
8577       V.getValueType() != MVT::i32 &&
8578       V.getValueType() != MVT::i64)
8579     return Result;
8580
8581   // Check the constant mask.  Invert it so that the bits being masked out are
8582   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8583   // follow the sign bit for uniformity.
8584   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8585   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8586   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8587   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8588   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8589   if (NotMaskLZ == 64) return Result;  // All zero mask.
8590
8591   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8592   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8593     return Result;
8594
8595   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8596   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8597     NotMaskLZ -= 64-V.getValueSizeInBits();
8598
8599   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8600   switch (MaskedBytes) {
8601   case 1:
8602   case 2:
8603   case 4: break;
8604   default: return Result; // All one mask, or 5-byte mask.
8605   }
8606
8607   // Verify that the first bit starts at a multiple of mask so that the access
8608   // is aligned the same as the access width.
8609   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8610
8611   Result.first = MaskedBytes;
8612   Result.second = NotMaskTZ/8;
8613   return Result;
8614 }
8615
8616
8617 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8618 /// provides a value as specified by MaskInfo.  If so, replace the specified
8619 /// store with a narrower store of truncated IVal.
8620 static SDNode *
8621 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8622                                 SDValue IVal, StoreSDNode *St,
8623                                 DAGCombiner *DC) {
8624   unsigned NumBytes = MaskInfo.first;
8625   unsigned ByteShift = MaskInfo.second;
8626   SelectionDAG &DAG = DC->getDAG();
8627
8628   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8629   // that uses this.  If not, this is not a replacement.
8630   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8631                                   ByteShift*8, (ByteShift+NumBytes)*8);
8632   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8633
8634   // Check that it is legal on the target to do this.  It is legal if the new
8635   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8636   // legalization.
8637   MVT VT = MVT::getIntegerVT(NumBytes*8);
8638   if (!DC->isTypeLegal(VT))
8639     return nullptr;
8640
8641   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8642   // shifted by ByteShift and truncated down to NumBytes.
8643   if (ByteShift)
8644     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8645                        DAG.getConstant(ByteShift*8,
8646                                     DC->getShiftAmountTy(IVal.getValueType())));
8647
8648   // Figure out the offset for the store and the alignment of the access.
8649   unsigned StOffset;
8650   unsigned NewAlign = St->getAlignment();
8651
8652   if (DAG.getTargetLoweringInfo().isLittleEndian())
8653     StOffset = ByteShift;
8654   else
8655     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8656
8657   SDValue Ptr = St->getBasePtr();
8658   if (StOffset) {
8659     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8660                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8661     NewAlign = MinAlign(NewAlign, StOffset);
8662   }
8663
8664   // Truncate down to the new size.
8665   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8666
8667   ++OpsNarrowed;
8668   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8669                       St->getPointerInfo().getWithOffset(StOffset),
8670                       false, false, NewAlign).getNode();
8671 }
8672
8673
8674 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8675 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8676 /// of the loaded bits, try narrowing the load and store if it would end up
8677 /// being a win for performance or code size.
8678 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8679   StoreSDNode *ST  = cast<StoreSDNode>(N);
8680   if (ST->isVolatile())
8681     return SDValue();
8682
8683   SDValue Chain = ST->getChain();
8684   SDValue Value = ST->getValue();
8685   SDValue Ptr   = ST->getBasePtr();
8686   EVT VT = Value.getValueType();
8687
8688   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8689     return SDValue();
8690
8691   unsigned Opc = Value.getOpcode();
8692
8693   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8694   // is a byte mask indicating a consecutive number of bytes, check to see if
8695   // Y is known to provide just those bytes.  If so, we try to replace the
8696   // load + replace + store sequence with a single (narrower) store, which makes
8697   // the load dead.
8698   if (Opc == ISD::OR) {
8699     std::pair<unsigned, unsigned> MaskedLoad;
8700     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8701     if (MaskedLoad.first)
8702       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8703                                                   Value.getOperand(1), ST,this))
8704         return SDValue(NewST, 0);
8705
8706     // Or is commutative, so try swapping X and Y.
8707     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8708     if (MaskedLoad.first)
8709       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8710                                                   Value.getOperand(0), ST,this))
8711         return SDValue(NewST, 0);
8712   }
8713
8714   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8715       Value.getOperand(1).getOpcode() != ISD::Constant)
8716     return SDValue();
8717
8718   SDValue N0 = Value.getOperand(0);
8719   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8720       Chain == SDValue(N0.getNode(), 1)) {
8721     LoadSDNode *LD = cast<LoadSDNode>(N0);
8722     if (LD->getBasePtr() != Ptr ||
8723         LD->getPointerInfo().getAddrSpace() !=
8724         ST->getPointerInfo().getAddrSpace())
8725       return SDValue();
8726
8727     // Find the type to narrow it the load / op / store to.
8728     SDValue N1 = Value.getOperand(1);
8729     unsigned BitWidth = N1.getValueSizeInBits();
8730     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8731     if (Opc == ISD::AND)
8732       Imm ^= APInt::getAllOnesValue(BitWidth);
8733     if (Imm == 0 || Imm.isAllOnesValue())
8734       return SDValue();
8735     unsigned ShAmt = Imm.countTrailingZeros();
8736     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8737     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8738     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8739     while (NewBW < BitWidth &&
8740            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8741              TLI.isNarrowingProfitable(VT, NewVT))) {
8742       NewBW = NextPowerOf2(NewBW);
8743       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8744     }
8745     if (NewBW >= BitWidth)
8746       return SDValue();
8747
8748     // If the lsb changed does not start at the type bitwidth boundary,
8749     // start at the previous one.
8750     if (ShAmt % NewBW)
8751       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8752     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8753                                    std::min(BitWidth, ShAmt + NewBW));
8754     if ((Imm & Mask) == Imm) {
8755       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8756       if (Opc == ISD::AND)
8757         NewImm ^= APInt::getAllOnesValue(NewBW);
8758       uint64_t PtrOff = ShAmt / 8;
8759       // For big endian targets, we need to adjust the offset to the pointer to
8760       // load the correct bytes.
8761       if (TLI.isBigEndian())
8762         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8763
8764       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8765       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8766       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8767         return SDValue();
8768
8769       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8770                                    Ptr.getValueType(), Ptr,
8771                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8772       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8773                                   LD->getChain(), NewPtr,
8774                                   LD->getPointerInfo().getWithOffset(PtrOff),
8775                                   LD->isVolatile(), LD->isNonTemporal(),
8776                                   LD->isInvariant(), NewAlign,
8777                                   LD->getTBAAInfo());
8778       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8779                                    DAG.getConstant(NewImm, NewVT));
8780       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8781                                    NewVal, NewPtr,
8782                                    ST->getPointerInfo().getWithOffset(PtrOff),
8783                                    false, false, NewAlign);
8784
8785       AddToWorkList(NewPtr.getNode());
8786       AddToWorkList(NewLD.getNode());
8787       AddToWorkList(NewVal.getNode());
8788       WorkListRemover DeadNodes(*this);
8789       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8790       ++OpsNarrowed;
8791       return NewST;
8792     }
8793   }
8794
8795   return SDValue();
8796 }
8797
8798 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8799 /// if the load value isn't used by any other operations, then consider
8800 /// transforming the pair to integer load / store operations if the target
8801 /// deems the transformation profitable.
8802 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8803   StoreSDNode *ST  = cast<StoreSDNode>(N);
8804   SDValue Chain = ST->getChain();
8805   SDValue Value = ST->getValue();
8806   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8807       Value.hasOneUse() &&
8808       Chain == SDValue(Value.getNode(), 1)) {
8809     LoadSDNode *LD = cast<LoadSDNode>(Value);
8810     EVT VT = LD->getMemoryVT();
8811     if (!VT.isFloatingPoint() ||
8812         VT != ST->getMemoryVT() ||
8813         LD->isNonTemporal() ||
8814         ST->isNonTemporal() ||
8815         LD->getPointerInfo().getAddrSpace() != 0 ||
8816         ST->getPointerInfo().getAddrSpace() != 0)
8817       return SDValue();
8818
8819     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8820     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8821         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8822         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8823         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8824       return SDValue();
8825
8826     unsigned LDAlign = LD->getAlignment();
8827     unsigned STAlign = ST->getAlignment();
8828     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8829     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8830     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8831       return SDValue();
8832
8833     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8834                                 LD->getChain(), LD->getBasePtr(),
8835                                 LD->getPointerInfo(),
8836                                 false, false, false, LDAlign);
8837
8838     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8839                                  NewLD, ST->getBasePtr(),
8840                                  ST->getPointerInfo(),
8841                                  false, false, STAlign);
8842
8843     AddToWorkList(NewLD.getNode());
8844     AddToWorkList(NewST.getNode());
8845     WorkListRemover DeadNodes(*this);
8846     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8847     ++LdStFP2Int;
8848     return NewST;
8849   }
8850
8851   return SDValue();
8852 }
8853
8854 /// Helper struct to parse and store a memory address as base + index + offset.
8855 /// We ignore sign extensions when it is safe to do so.
8856 /// The following two expressions are not equivalent. To differentiate we need
8857 /// to store whether there was a sign extension involved in the index
8858 /// computation.
8859 ///  (load (i64 add (i64 copyfromreg %c)
8860 ///                 (i64 signextend (add (i8 load %index)
8861 ///                                      (i8 1))))
8862 /// vs
8863 ///
8864 /// (load (i64 add (i64 copyfromreg %c)
8865 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8866 ///                                         (i32 1)))))
8867 struct BaseIndexOffset {
8868   SDValue Base;
8869   SDValue Index;
8870   int64_t Offset;
8871   bool IsIndexSignExt;
8872
8873   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8874
8875   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8876                   bool IsIndexSignExt) :
8877     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8878
8879   bool equalBaseIndex(const BaseIndexOffset &Other) {
8880     return Other.Base == Base && Other.Index == Index &&
8881       Other.IsIndexSignExt == IsIndexSignExt;
8882   }
8883
8884   /// Parses tree in Ptr for base, index, offset addresses.
8885   static BaseIndexOffset match(SDValue Ptr) {
8886     bool IsIndexSignExt = false;
8887
8888     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8889     // instruction, then it could be just the BASE or everything else we don't
8890     // know how to handle. Just use Ptr as BASE and give up.
8891     if (Ptr->getOpcode() != ISD::ADD)
8892       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8893
8894     // We know that we have at least an ADD instruction. Try to pattern match
8895     // the simple case of BASE + OFFSET.
8896     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8897       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8898       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8899                               IsIndexSignExt);
8900     }
8901
8902     // Inside a loop the current BASE pointer is calculated using an ADD and a
8903     // MUL instruction. In this case Ptr is the actual BASE pointer.
8904     // (i64 add (i64 %array_ptr)
8905     //          (i64 mul (i64 %induction_var)
8906     //                   (i64 %element_size)))
8907     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8908       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8909
8910     // Look at Base + Index + Offset cases.
8911     SDValue Base = Ptr->getOperand(0);
8912     SDValue IndexOffset = Ptr->getOperand(1);
8913
8914     // Skip signextends.
8915     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8916       IndexOffset = IndexOffset->getOperand(0);
8917       IsIndexSignExt = true;
8918     }
8919
8920     // Either the case of Base + Index (no offset) or something else.
8921     if (IndexOffset->getOpcode() != ISD::ADD)
8922       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8923
8924     // Now we have the case of Base + Index + offset.
8925     SDValue Index = IndexOffset->getOperand(0);
8926     SDValue Offset = IndexOffset->getOperand(1);
8927
8928     if (!isa<ConstantSDNode>(Offset))
8929       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8930
8931     // Ignore signextends.
8932     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8933       Index = Index->getOperand(0);
8934       IsIndexSignExt = true;
8935     } else IsIndexSignExt = false;
8936
8937     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8938     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8939   }
8940 };
8941
8942 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8943 /// is located in a sequence of memory operations connected by a chain.
8944 struct MemOpLink {
8945   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8946     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8947   // Ptr to the mem node.
8948   LSBaseSDNode *MemNode;
8949   // Offset from the base ptr.
8950   int64_t OffsetFromBase;
8951   // What is the sequence number of this mem node.
8952   // Lowest mem operand in the DAG starts at zero.
8953   unsigned SequenceNum;
8954 };
8955
8956 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8957   EVT MemVT = St->getMemoryVT();
8958   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8959   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8960     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8961
8962   // Don't merge vectors into wider inputs.
8963   if (MemVT.isVector() || !MemVT.isSimple())
8964     return false;
8965
8966   // Perform an early exit check. Do not bother looking at stored values that
8967   // are not constants or loads.
8968   SDValue StoredVal = St->getValue();
8969   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8970   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8971       !IsLoadSrc)
8972     return false;
8973
8974   // Only look at ends of store sequences.
8975   SDValue Chain = SDValue(St, 1);
8976   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8977     return false;
8978
8979   // This holds the base pointer, index, and the offset in bytes from the base
8980   // pointer.
8981   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8982
8983   // We must have a base and an offset.
8984   if (!BasePtr.Base.getNode())
8985     return false;
8986
8987   // Do not handle stores to undef base pointers.
8988   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8989     return false;
8990
8991   // Save the LoadSDNodes that we find in the chain.
8992   // We need to make sure that these nodes do not interfere with
8993   // any of the store nodes.
8994   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8995
8996   // Save the StoreSDNodes that we find in the chain.
8997   SmallVector<MemOpLink, 8> StoreNodes;
8998
8999   // Walk up the chain and look for nodes with offsets from the same
9000   // base pointer. Stop when reaching an instruction with a different kind
9001   // or instruction which has a different base pointer.
9002   unsigned Seq = 0;
9003   StoreSDNode *Index = St;
9004   while (Index) {
9005     // If the chain has more than one use, then we can't reorder the mem ops.
9006     if (Index != St && !SDValue(Index, 1)->hasOneUse())
9007       break;
9008
9009     // Find the base pointer and offset for this memory node.
9010     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9011
9012     // Check that the base pointer is the same as the original one.
9013     if (!Ptr.equalBaseIndex(BasePtr))
9014       break;
9015
9016     // Check that the alignment is the same.
9017     if (Index->getAlignment() != St->getAlignment())
9018       break;
9019
9020     // The memory operands must not be volatile.
9021     if (Index->isVolatile() || Index->isIndexed())
9022       break;
9023
9024     // No truncation.
9025     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9026       if (St->isTruncatingStore())
9027         break;
9028
9029     // The stored memory type must be the same.
9030     if (Index->getMemoryVT() != MemVT)
9031       break;
9032
9033     // We do not allow unaligned stores because we want to prevent overriding
9034     // stores.
9035     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9036       break;
9037
9038     // We found a potential memory operand to merge.
9039     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9040
9041     // Find the next memory operand in the chain. If the next operand in the
9042     // chain is a store then move up and continue the scan with the next
9043     // memory operand. If the next operand is a load save it and use alias
9044     // information to check if it interferes with anything.
9045     SDNode *NextInChain = Index->getChain().getNode();
9046     while (1) {
9047       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9048         // We found a store node. Use it for the next iteration.
9049         Index = STn;
9050         break;
9051       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9052         if (Ldn->isVolatile()) {
9053           Index = nullptr;
9054           break;
9055         }
9056
9057         // Save the load node for later. Continue the scan.
9058         AliasLoadNodes.push_back(Ldn);
9059         NextInChain = Ldn->getChain().getNode();
9060         continue;
9061       } else {
9062         Index = nullptr;
9063         break;
9064       }
9065     }
9066   }
9067
9068   // Check if there is anything to merge.
9069   if (StoreNodes.size() < 2)
9070     return false;
9071
9072   // Sort the memory operands according to their distance from the base pointer.
9073   std::sort(StoreNodes.begin(), StoreNodes.end(),
9074             [](MemOpLink LHS, MemOpLink RHS) {
9075     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9076            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9077             LHS.SequenceNum > RHS.SequenceNum);
9078   });
9079
9080   // Scan the memory operations on the chain and find the first non-consecutive
9081   // store memory address.
9082   unsigned LastConsecutiveStore = 0;
9083   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9084   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9085
9086     // Check that the addresses are consecutive starting from the second
9087     // element in the list of stores.
9088     if (i > 0) {
9089       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9090       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9091         break;
9092     }
9093
9094     bool Alias = false;
9095     // Check if this store interferes with any of the loads that we found.
9096     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9097       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9098         Alias = true;
9099         break;
9100       }
9101     // We found a load that alias with this store. Stop the sequence.
9102     if (Alias)
9103       break;
9104
9105     // Mark this node as useful.
9106     LastConsecutiveStore = i;
9107   }
9108
9109   // The node with the lowest store address.
9110   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9111
9112   // Store the constants into memory as one consecutive store.
9113   if (!IsLoadSrc) {
9114     unsigned LastLegalType = 0;
9115     unsigned LastLegalVectorType = 0;
9116     bool NonZero = false;
9117     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9118       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9119       SDValue StoredVal = St->getValue();
9120
9121       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9122         NonZero |= !C->isNullValue();
9123       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9124         NonZero |= !C->getConstantFPValue()->isNullValue();
9125       } else {
9126         // Non-constant.
9127         break;
9128       }
9129
9130       // Find a legal type for the constant store.
9131       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9132       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9133       if (TLI.isTypeLegal(StoreTy))
9134         LastLegalType = i+1;
9135       // Or check whether a truncstore is legal.
9136       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9137                TargetLowering::TypePromoteInteger) {
9138         EVT LegalizedStoredValueTy =
9139           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9140         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9141           LastLegalType = i+1;
9142       }
9143
9144       // Find a legal type for the vector store.
9145       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9146       if (TLI.isTypeLegal(Ty))
9147         LastLegalVectorType = i + 1;
9148     }
9149
9150     // We only use vectors if the constant is known to be zero and the
9151     // function is not marked with the noimplicitfloat attribute.
9152     if (NonZero || NoVectors)
9153       LastLegalVectorType = 0;
9154
9155     // Check if we found a legal integer type to store.
9156     if (LastLegalType == 0 && LastLegalVectorType == 0)
9157       return false;
9158
9159     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9160     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9161
9162     // Make sure we have something to merge.
9163     if (NumElem < 2)
9164       return false;
9165
9166     unsigned EarliestNodeUsed = 0;
9167     for (unsigned i=0; i < NumElem; ++i) {
9168       // Find a chain for the new wide-store operand. Notice that some
9169       // of the store nodes that we found may not be selected for inclusion
9170       // in the wide store. The chain we use needs to be the chain of the
9171       // earliest store node which is *used* and replaced by the wide store.
9172       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9173         EarliestNodeUsed = i;
9174     }
9175
9176     // The earliest Node in the DAG.
9177     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9178     SDLoc DL(StoreNodes[0].MemNode);
9179
9180     SDValue StoredVal;
9181     if (UseVector) {
9182       // Find a legal type for the vector store.
9183       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9184       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9185       StoredVal = DAG.getConstant(0, Ty);
9186     } else {
9187       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9188       APInt StoreInt(StoreBW, 0);
9189
9190       // Construct a single integer constant which is made of the smaller
9191       // constant inputs.
9192       bool IsLE = TLI.isLittleEndian();
9193       for (unsigned i = 0; i < NumElem ; ++i) {
9194         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9195         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9196         SDValue Val = St->getValue();
9197         StoreInt<<=ElementSizeBytes*8;
9198         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9199           StoreInt|=C->getAPIntValue().zext(StoreBW);
9200         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9201           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9202         } else {
9203           assert(false && "Invalid constant element type");
9204         }
9205       }
9206
9207       // Create the new Load and Store operations.
9208       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9209       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9210     }
9211
9212     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9213                                     FirstInChain->getBasePtr(),
9214                                     FirstInChain->getPointerInfo(),
9215                                     false, false,
9216                                     FirstInChain->getAlignment());
9217
9218     // Replace the first store with the new store
9219     CombineTo(EarliestOp, NewStore);
9220     // Erase all other stores.
9221     for (unsigned i = 0; i < NumElem ; ++i) {
9222       if (StoreNodes[i].MemNode == EarliestOp)
9223         continue;
9224       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9225       // ReplaceAllUsesWith will replace all uses that existed when it was
9226       // called, but graph optimizations may cause new ones to appear. For
9227       // example, the case in pr14333 looks like
9228       //
9229       //  St's chain -> St -> another store -> X
9230       //
9231       // And the only difference from St to the other store is the chain.
9232       // When we change it's chain to be St's chain they become identical,
9233       // get CSEed and the net result is that X is now a use of St.
9234       // Since we know that St is redundant, just iterate.
9235       while (!St->use_empty())
9236         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9237       removeFromWorkList(St);
9238       DAG.DeleteNode(St);
9239     }
9240
9241     return true;
9242   }
9243
9244   // Below we handle the case of multiple consecutive stores that
9245   // come from multiple consecutive loads. We merge them into a single
9246   // wide load and a single wide store.
9247
9248   // Look for load nodes which are used by the stored values.
9249   SmallVector<MemOpLink, 8> LoadNodes;
9250
9251   // Find acceptable loads. Loads need to have the same chain (token factor),
9252   // must not be zext, volatile, indexed, and they must be consecutive.
9253   BaseIndexOffset LdBasePtr;
9254   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9255     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9256     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9257     if (!Ld) break;
9258
9259     // Loads must only have one use.
9260     if (!Ld->hasNUsesOfValue(1, 0))
9261       break;
9262
9263     // Check that the alignment is the same as the stores.
9264     if (Ld->getAlignment() != St->getAlignment())
9265       break;
9266
9267     // The memory operands must not be volatile.
9268     if (Ld->isVolatile() || Ld->isIndexed())
9269       break;
9270
9271     // We do not accept ext loads.
9272     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9273       break;
9274
9275     // The stored memory type must be the same.
9276     if (Ld->getMemoryVT() != MemVT)
9277       break;
9278
9279     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9280     // If this is not the first ptr that we check.
9281     if (LdBasePtr.Base.getNode()) {
9282       // The base ptr must be the same.
9283       if (!LdPtr.equalBaseIndex(LdBasePtr))
9284         break;
9285     } else {
9286       // Check that all other base pointers are the same as this one.
9287       LdBasePtr = LdPtr;
9288     }
9289
9290     // We found a potential memory operand to merge.
9291     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9292   }
9293
9294   if (LoadNodes.size() < 2)
9295     return false;
9296
9297   // Scan the memory operations on the chain and find the first non-consecutive
9298   // load memory address. These variables hold the index in the store node
9299   // array.
9300   unsigned LastConsecutiveLoad = 0;
9301   // This variable refers to the size and not index in the array.
9302   unsigned LastLegalVectorType = 0;
9303   unsigned LastLegalIntegerType = 0;
9304   StartAddress = LoadNodes[0].OffsetFromBase;
9305   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9306   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9307     // All loads much share the same chain.
9308     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9309       break;
9310
9311     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9312     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9313       break;
9314     LastConsecutiveLoad = i;
9315
9316     // Find a legal type for the vector store.
9317     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9318     if (TLI.isTypeLegal(StoreTy))
9319       LastLegalVectorType = i + 1;
9320
9321     // Find a legal type for the integer store.
9322     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9323     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9324     if (TLI.isTypeLegal(StoreTy))
9325       LastLegalIntegerType = i + 1;
9326     // Or check whether a truncstore and extload is legal.
9327     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9328              TargetLowering::TypePromoteInteger) {
9329       EVT LegalizedStoredValueTy =
9330         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9331       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9332           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9333           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9334           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9335         LastLegalIntegerType = i+1;
9336     }
9337   }
9338
9339   // Only use vector types if the vector type is larger than the integer type.
9340   // If they are the same, use integers.
9341   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9342   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9343
9344   // We add +1 here because the LastXXX variables refer to location while
9345   // the NumElem refers to array/index size.
9346   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9347   NumElem = std::min(LastLegalType, NumElem);
9348
9349   if (NumElem < 2)
9350     return false;
9351
9352   // The earliest Node in the DAG.
9353   unsigned EarliestNodeUsed = 0;
9354   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9355   for (unsigned i=1; i<NumElem; ++i) {
9356     // Find a chain for the new wide-store operand. Notice that some
9357     // of the store nodes that we found may not be selected for inclusion
9358     // in the wide store. The chain we use needs to be the chain of the
9359     // earliest store node which is *used* and replaced by the wide store.
9360     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9361       EarliestNodeUsed = i;
9362   }
9363
9364   // Find if it is better to use vectors or integers to load and store
9365   // to memory.
9366   EVT JointMemOpVT;
9367   if (UseVectorTy) {
9368     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9369   } else {
9370     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9371     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9372   }
9373
9374   SDLoc LoadDL(LoadNodes[0].MemNode);
9375   SDLoc StoreDL(StoreNodes[0].MemNode);
9376
9377   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9378   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9379                                 FirstLoad->getChain(),
9380                                 FirstLoad->getBasePtr(),
9381                                 FirstLoad->getPointerInfo(),
9382                                 false, false, false,
9383                                 FirstLoad->getAlignment());
9384
9385   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9386                                   FirstInChain->getBasePtr(),
9387                                   FirstInChain->getPointerInfo(), false, false,
9388                                   FirstInChain->getAlignment());
9389
9390   // Replace one of the loads with the new load.
9391   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9392   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9393                                 SDValue(NewLoad.getNode(), 1));
9394
9395   // Remove the rest of the load chains.
9396   for (unsigned i = 1; i < NumElem ; ++i) {
9397     // Replace all chain users of the old load nodes with the chain of the new
9398     // load node.
9399     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9400     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9401   }
9402
9403   // Replace the first store with the new store.
9404   CombineTo(EarliestOp, NewStore);
9405   // Erase all other stores.
9406   for (unsigned i = 0; i < NumElem ; ++i) {
9407     // Remove all Store nodes.
9408     if (StoreNodes[i].MemNode == EarliestOp)
9409       continue;
9410     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9411     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9412     removeFromWorkList(St);
9413     DAG.DeleteNode(St);
9414   }
9415
9416   return true;
9417 }
9418
9419 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9420   StoreSDNode *ST  = cast<StoreSDNode>(N);
9421   SDValue Chain = ST->getChain();
9422   SDValue Value = ST->getValue();
9423   SDValue Ptr   = ST->getBasePtr();
9424
9425   // If this is a store of a bit convert, store the input value if the
9426   // resultant store does not need a higher alignment than the original.
9427   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9428       ST->isUnindexed()) {
9429     unsigned OrigAlign = ST->getAlignment();
9430     EVT SVT = Value.getOperand(0).getValueType();
9431     unsigned Align = TLI.getDataLayout()->
9432       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9433     if (Align <= OrigAlign &&
9434         ((!LegalOperations && !ST->isVolatile()) ||
9435          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9436       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9437                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9438                           ST->isNonTemporal(), OrigAlign,
9439                           ST->getTBAAInfo());
9440   }
9441
9442   // Turn 'store undef, Ptr' -> nothing.
9443   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9444     return Chain;
9445
9446   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9447   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9448     // NOTE: If the original store is volatile, this transform must not increase
9449     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9450     // processor operation but an i64 (which is not legal) requires two.  So the
9451     // transform should not be done in this case.
9452     if (Value.getOpcode() != ISD::TargetConstantFP) {
9453       SDValue Tmp;
9454       switch (CFP->getSimpleValueType(0).SimpleTy) {
9455       default: llvm_unreachable("Unknown FP type");
9456       case MVT::f16:    // We don't do this for these yet.
9457       case MVT::f80:
9458       case MVT::f128:
9459       case MVT::ppcf128:
9460         break;
9461       case MVT::f32:
9462         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9463             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9464           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9465                               bitcastToAPInt().getZExtValue(), MVT::i32);
9466           return DAG.getStore(Chain, SDLoc(N), Tmp,
9467                               Ptr, ST->getMemOperand());
9468         }
9469         break;
9470       case MVT::f64:
9471         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9472              !ST->isVolatile()) ||
9473             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9474           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9475                                 getZExtValue(), MVT::i64);
9476           return DAG.getStore(Chain, SDLoc(N), Tmp,
9477                               Ptr, ST->getMemOperand());
9478         }
9479
9480         if (!ST->isVolatile() &&
9481             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9482           // Many FP stores are not made apparent until after legalize, e.g. for
9483           // argument passing.  Since this is so common, custom legalize the
9484           // 64-bit integer store into two 32-bit stores.
9485           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9486           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9487           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9488           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9489
9490           unsigned Alignment = ST->getAlignment();
9491           bool isVolatile = ST->isVolatile();
9492           bool isNonTemporal = ST->isNonTemporal();
9493           const MDNode *TBAAInfo = ST->getTBAAInfo();
9494
9495           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9496                                      Ptr, ST->getPointerInfo(),
9497                                      isVolatile, isNonTemporal,
9498                                      ST->getAlignment(), TBAAInfo);
9499           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9500                             DAG.getConstant(4, Ptr.getValueType()));
9501           Alignment = MinAlign(Alignment, 4U);
9502           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9503                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9504                                      isVolatile, isNonTemporal,
9505                                      Alignment, TBAAInfo);
9506           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9507                              St0, St1);
9508         }
9509
9510         break;
9511       }
9512     }
9513   }
9514
9515   // Try to infer better alignment information than the store already has.
9516   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9517     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9518       if (Align > ST->getAlignment())
9519         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9520                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9521                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9522                                  ST->getTBAAInfo());
9523     }
9524   }
9525
9526   // Try transforming a pair floating point load / store ops to integer
9527   // load / store ops.
9528   SDValue NewST = TransformFPLoadStorePair(N);
9529   if (NewST.getNode())
9530     return NewST;
9531
9532   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9533     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9534 #ifndef NDEBUG
9535   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9536       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9537     UseAA = false;
9538 #endif
9539   if (UseAA && ST->isUnindexed()) {
9540     // Walk up chain skipping non-aliasing memory nodes.
9541     SDValue BetterChain = FindBetterChain(N, Chain);
9542
9543     // If there is a better chain.
9544     if (Chain != BetterChain) {
9545       SDValue ReplStore;
9546
9547       // Replace the chain to avoid dependency.
9548       if (ST->isTruncatingStore()) {
9549         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9550                                       ST->getMemoryVT(), ST->getMemOperand());
9551       } else {
9552         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9553                                  ST->getMemOperand());
9554       }
9555
9556       // Create token to keep both nodes around.
9557       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9558                                   MVT::Other, Chain, ReplStore);
9559
9560       // Make sure the new and old chains are cleaned up.
9561       AddToWorkList(Token.getNode());
9562
9563       // Don't add users to work list.
9564       return CombineTo(N, Token, false);
9565     }
9566   }
9567
9568   // Try transforming N to an indexed store.
9569   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9570     return SDValue(N, 0);
9571
9572   // FIXME: is there such a thing as a truncating indexed store?
9573   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9574       Value.getValueType().isInteger()) {
9575     // See if we can simplify the input to this truncstore with knowledge that
9576     // only the low bits are being used.  For example:
9577     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9578     SDValue Shorter =
9579       GetDemandedBits(Value,
9580                       APInt::getLowBitsSet(
9581                         Value.getValueType().getScalarType().getSizeInBits(),
9582                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9583     AddToWorkList(Value.getNode());
9584     if (Shorter.getNode())
9585       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9586                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9587
9588     // Otherwise, see if we can simplify the operation with
9589     // SimplifyDemandedBits, which only works if the value has a single use.
9590     if (SimplifyDemandedBits(Value,
9591                         APInt::getLowBitsSet(
9592                           Value.getValueType().getScalarType().getSizeInBits(),
9593                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9594       return SDValue(N, 0);
9595   }
9596
9597   // If this is a load followed by a store to the same location, then the store
9598   // is dead/noop.
9599   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9600     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9601         ST->isUnindexed() && !ST->isVolatile() &&
9602         // There can't be any side effects between the load and store, such as
9603         // a call or store.
9604         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9605       // The store is dead, remove it.
9606       return Chain;
9607     }
9608   }
9609
9610   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9611   // truncating store.  We can do this even if this is already a truncstore.
9612   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9613       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9614       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9615                             ST->getMemoryVT())) {
9616     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9617                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9618   }
9619
9620   // Only perform this optimization before the types are legal, because we
9621   // don't want to perform this optimization on every DAGCombine invocation.
9622   if (!LegalTypes) {
9623     bool EverChanged = false;
9624
9625     do {
9626       // There can be multiple store sequences on the same chain.
9627       // Keep trying to merge store sequences until we are unable to do so
9628       // or until we merge the last store on the chain.
9629       bool Changed = MergeConsecutiveStores(ST);
9630       EverChanged |= Changed;
9631       if (!Changed) break;
9632     } while (ST->getOpcode() != ISD::DELETED_NODE);
9633
9634     if (EverChanged)
9635       return SDValue(N, 0);
9636   }
9637
9638   return ReduceLoadOpStoreWidth(N);
9639 }
9640
9641 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9642   SDValue InVec = N->getOperand(0);
9643   SDValue InVal = N->getOperand(1);
9644   SDValue EltNo = N->getOperand(2);
9645   SDLoc dl(N);
9646
9647   // If the inserted element is an UNDEF, just use the input vector.
9648   if (InVal.getOpcode() == ISD::UNDEF)
9649     return InVec;
9650
9651   EVT VT = InVec.getValueType();
9652
9653   // If we can't generate a legal BUILD_VECTOR, exit
9654   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9655     return SDValue();
9656
9657   // Check that we know which element is being inserted
9658   if (!isa<ConstantSDNode>(EltNo))
9659     return SDValue();
9660   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9661
9662   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9663   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9664   // vector elements.
9665   SmallVector<SDValue, 8> Ops;
9666   // Do not combine these two vectors if the output vector will not replace
9667   // the input vector.
9668   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9669     Ops.append(InVec.getNode()->op_begin(),
9670                InVec.getNode()->op_end());
9671   } else if (InVec.getOpcode() == ISD::UNDEF) {
9672     unsigned NElts = VT.getVectorNumElements();
9673     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9674   } else {
9675     return SDValue();
9676   }
9677
9678   // Insert the element
9679   if (Elt < Ops.size()) {
9680     // All the operands of BUILD_VECTOR must have the same type;
9681     // we enforce that here.
9682     EVT OpVT = Ops[0].getValueType();
9683     if (InVal.getValueType() != OpVT)
9684       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9685                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9686                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9687     Ops[Elt] = InVal;
9688   }
9689
9690   // Return the new vector
9691   return DAG.getNode(ISD::BUILD_VECTOR, dl,
9692                      VT, &Ops[0], Ops.size());
9693 }
9694
9695 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9696   // (vextract (scalar_to_vector val, 0) -> val
9697   SDValue InVec = N->getOperand(0);
9698   EVT VT = InVec.getValueType();
9699   EVT NVT = N->getValueType(0);
9700
9701   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9702     // Check if the result type doesn't match the inserted element type. A
9703     // SCALAR_TO_VECTOR may truncate the inserted element and the
9704     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9705     SDValue InOp = InVec.getOperand(0);
9706     if (InOp.getValueType() != NVT) {
9707       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9708       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9709     }
9710     return InOp;
9711   }
9712
9713   SDValue EltNo = N->getOperand(1);
9714   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9715
9716   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9717   // We only perform this optimization before the op legalization phase because
9718   // we may introduce new vector instructions which are not backed by TD
9719   // patterns. For example on AVX, extracting elements from a wide vector
9720   // without using extract_subvector. However, if we can find an underlying
9721   // scalar value, then we can always use that.
9722   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9723       && ConstEltNo) {
9724     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9725     int NumElem = VT.getVectorNumElements();
9726     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9727     // Find the new index to extract from.
9728     int OrigElt = SVOp->getMaskElt(Elt);
9729
9730     // Extracting an undef index is undef.
9731     if (OrigElt == -1)
9732       return DAG.getUNDEF(NVT);
9733
9734     // Select the right vector half to extract from.
9735     SDValue SVInVec;
9736     if (OrigElt < NumElem) {
9737       SVInVec = InVec->getOperand(0);
9738     } else {
9739       SVInVec = InVec->getOperand(1);
9740       OrigElt -= NumElem;
9741     }
9742
9743     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9744       SDValue InOp = SVInVec.getOperand(OrigElt);
9745       if (InOp.getValueType() != NVT) {
9746         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9747         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9748       }
9749
9750       return InOp;
9751     }
9752
9753     // FIXME: We should handle recursing on other vector shuffles and
9754     // scalar_to_vector here as well.
9755
9756     if (!LegalOperations) {
9757       EVT IndexTy = TLI.getVectorIdxTy();
9758       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9759                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9760     }
9761   }
9762
9763   // Perform only after legalization to ensure build_vector / vector_shuffle
9764   // optimizations have already been done.
9765   if (!LegalOperations) return SDValue();
9766
9767   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9768   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9769   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9770
9771   if (ConstEltNo) {
9772     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9773     bool NewLoad = false;
9774     bool BCNumEltsChanged = false;
9775     EVT ExtVT = VT.getVectorElementType();
9776     EVT LVT = ExtVT;
9777
9778     // If the result of load has to be truncated, then it's not necessarily
9779     // profitable.
9780     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9781       return SDValue();
9782
9783     if (InVec.getOpcode() == ISD::BITCAST) {
9784       // Don't duplicate a load with other uses.
9785       if (!InVec.hasOneUse())
9786         return SDValue();
9787
9788       EVT BCVT = InVec.getOperand(0).getValueType();
9789       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9790         return SDValue();
9791       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9792         BCNumEltsChanged = true;
9793       InVec = InVec.getOperand(0);
9794       ExtVT = BCVT.getVectorElementType();
9795       NewLoad = true;
9796     }
9797
9798     LoadSDNode *LN0 = nullptr;
9799     const ShuffleVectorSDNode *SVN = nullptr;
9800     if (ISD::isNormalLoad(InVec.getNode())) {
9801       LN0 = cast<LoadSDNode>(InVec);
9802     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9803                InVec.getOperand(0).getValueType() == ExtVT &&
9804                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9805       // Don't duplicate a load with other uses.
9806       if (!InVec.hasOneUse())
9807         return SDValue();
9808
9809       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9810     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9811       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9812       // =>
9813       // (load $addr+1*size)
9814
9815       // Don't duplicate a load with other uses.
9816       if (!InVec.hasOneUse())
9817         return SDValue();
9818
9819       // If the bit convert changed the number of elements, it is unsafe
9820       // to examine the mask.
9821       if (BCNumEltsChanged)
9822         return SDValue();
9823
9824       // Select the input vector, guarding against out of range extract vector.
9825       unsigned NumElems = VT.getVectorNumElements();
9826       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9827       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9828
9829       if (InVec.getOpcode() == ISD::BITCAST) {
9830         // Don't duplicate a load with other uses.
9831         if (!InVec.hasOneUse())
9832           return SDValue();
9833
9834         InVec = InVec.getOperand(0);
9835       }
9836       if (ISD::isNormalLoad(InVec.getNode())) {
9837         LN0 = cast<LoadSDNode>(InVec);
9838         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9839       }
9840     }
9841
9842     // Make sure we found a non-volatile load and the extractelement is
9843     // the only use.
9844     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9845       return SDValue();
9846
9847     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9848     if (Elt == -1)
9849       return DAG.getUNDEF(LVT);
9850
9851     unsigned Align = LN0->getAlignment();
9852     if (NewLoad) {
9853       // Check the resultant load doesn't need a higher alignment than the
9854       // original load.
9855       unsigned NewAlign =
9856         TLI.getDataLayout()
9857             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9858
9859       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9860         return SDValue();
9861
9862       Align = NewAlign;
9863     }
9864
9865     SDValue NewPtr = LN0->getBasePtr();
9866     unsigned PtrOff = 0;
9867
9868     if (Elt) {
9869       PtrOff = LVT.getSizeInBits() * Elt / 8;
9870       EVT PtrType = NewPtr.getValueType();
9871       if (TLI.isBigEndian())
9872         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9873       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9874                            DAG.getConstant(PtrOff, PtrType));
9875     }
9876
9877     // The replacement we need to do here is a little tricky: we need to
9878     // replace an extractelement of a load with a load.
9879     // Use ReplaceAllUsesOfValuesWith to do the replacement.
9880     // Note that this replacement assumes that the extractvalue is the only
9881     // use of the load; that's okay because we don't want to perform this
9882     // transformation in other cases anyway.
9883     SDValue Load;
9884     SDValue Chain;
9885     if (NVT.bitsGT(LVT)) {
9886       // If the result type of vextract is wider than the load, then issue an
9887       // extending load instead.
9888       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9889         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9890       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9891                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9892                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9893                             Align, LN0->getTBAAInfo());
9894       Chain = Load.getValue(1);
9895     } else {
9896       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9897                          LN0->getPointerInfo().getWithOffset(PtrOff),
9898                          LN0->isVolatile(), LN0->isNonTemporal(),
9899                          LN0->isInvariant(), Align, LN0->getTBAAInfo());
9900       Chain = Load.getValue(1);
9901       if (NVT.bitsLT(LVT))
9902         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9903       else
9904         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9905     }
9906     WorkListRemover DeadNodes(*this);
9907     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9908     SDValue To[] = { Load, Chain };
9909     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9910     // Since we're explcitly calling ReplaceAllUses, add the new node to the
9911     // worklist explicitly as well.
9912     AddToWorkList(Load.getNode());
9913     AddUsersToWorkList(Load.getNode()); // Add users too
9914     // Make sure to revisit this node to clean it up; it will usually be dead.
9915     AddToWorkList(N);
9916     return SDValue(N, 0);
9917   }
9918
9919   return SDValue();
9920 }
9921
9922 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9923 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9924   // We perform this optimization post type-legalization because
9925   // the type-legalizer often scalarizes integer-promoted vectors.
9926   // Performing this optimization before may create bit-casts which
9927   // will be type-legalized to complex code sequences.
9928   // We perform this optimization only before the operation legalizer because we
9929   // may introduce illegal operations.
9930   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9931     return SDValue();
9932
9933   unsigned NumInScalars = N->getNumOperands();
9934   SDLoc dl(N);
9935   EVT VT = N->getValueType(0);
9936
9937   // Check to see if this is a BUILD_VECTOR of a bunch of values
9938   // which come from any_extend or zero_extend nodes. If so, we can create
9939   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9940   // optimizations. We do not handle sign-extend because we can't fill the sign
9941   // using shuffles.
9942   EVT SourceType = MVT::Other;
9943   bool AllAnyExt = true;
9944
9945   for (unsigned i = 0; i != NumInScalars; ++i) {
9946     SDValue In = N->getOperand(i);
9947     // Ignore undef inputs.
9948     if (In.getOpcode() == ISD::UNDEF) continue;
9949
9950     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
9951     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9952
9953     // Abort if the element is not an extension.
9954     if (!ZeroExt && !AnyExt) {
9955       SourceType = MVT::Other;
9956       break;
9957     }
9958
9959     // The input is a ZeroExt or AnyExt. Check the original type.
9960     EVT InTy = In.getOperand(0).getValueType();
9961
9962     // Check that all of the widened source types are the same.
9963     if (SourceType == MVT::Other)
9964       // First time.
9965       SourceType = InTy;
9966     else if (InTy != SourceType) {
9967       // Multiple income types. Abort.
9968       SourceType = MVT::Other;
9969       break;
9970     }
9971
9972     // Check if all of the extends are ANY_EXTENDs.
9973     AllAnyExt &= AnyExt;
9974   }
9975
9976   // In order to have valid types, all of the inputs must be extended from the
9977   // same source type and all of the inputs must be any or zero extend.
9978   // Scalar sizes must be a power of two.
9979   EVT OutScalarTy = VT.getScalarType();
9980   bool ValidTypes = SourceType != MVT::Other &&
9981                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9982                  isPowerOf2_32(SourceType.getSizeInBits());
9983
9984   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9985   // turn into a single shuffle instruction.
9986   if (!ValidTypes)
9987     return SDValue();
9988
9989   bool isLE = TLI.isLittleEndian();
9990   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9991   assert(ElemRatio > 1 && "Invalid element size ratio");
9992   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9993                                DAG.getConstant(0, SourceType);
9994
9995   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9996   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9997
9998   // Populate the new build_vector
9999   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10000     SDValue Cast = N->getOperand(i);
10001     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10002             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10003             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10004     SDValue In;
10005     if (Cast.getOpcode() == ISD::UNDEF)
10006       In = DAG.getUNDEF(SourceType);
10007     else
10008       In = Cast->getOperand(0);
10009     unsigned Index = isLE ? (i * ElemRatio) :
10010                             (i * ElemRatio + (ElemRatio - 1));
10011
10012     assert(Index < Ops.size() && "Invalid index");
10013     Ops[Index] = In;
10014   }
10015
10016   // The type of the new BUILD_VECTOR node.
10017   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10018   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10019          "Invalid vector size");
10020   // Check if the new vector type is legal.
10021   if (!isTypeLegal(VecVT)) return SDValue();
10022
10023   // Make the new BUILD_VECTOR.
10024   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
10025
10026   // The new BUILD_VECTOR node has the potential to be further optimized.
10027   AddToWorkList(BV.getNode());
10028   // Bitcast to the desired type.
10029   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10030 }
10031
10032 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10033   EVT VT = N->getValueType(0);
10034
10035   unsigned NumInScalars = N->getNumOperands();
10036   SDLoc dl(N);
10037
10038   EVT SrcVT = MVT::Other;
10039   unsigned Opcode = ISD::DELETED_NODE;
10040   unsigned NumDefs = 0;
10041
10042   for (unsigned i = 0; i != NumInScalars; ++i) {
10043     SDValue In = N->getOperand(i);
10044     unsigned Opc = In.getOpcode();
10045
10046     if (Opc == ISD::UNDEF)
10047       continue;
10048
10049     // If all scalar values are floats and converted from integers.
10050     if (Opcode == ISD::DELETED_NODE &&
10051         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10052       Opcode = Opc;
10053     }
10054
10055     if (Opc != Opcode)
10056       return SDValue();
10057
10058     EVT InVT = In.getOperand(0).getValueType();
10059
10060     // If all scalar values are typed differently, bail out. It's chosen to
10061     // simplify BUILD_VECTOR of integer types.
10062     if (SrcVT == MVT::Other)
10063       SrcVT = InVT;
10064     if (SrcVT != InVT)
10065       return SDValue();
10066     NumDefs++;
10067   }
10068
10069   // If the vector has just one element defined, it's not worth to fold it into
10070   // a vectorized one.
10071   if (NumDefs < 2)
10072     return SDValue();
10073
10074   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10075          && "Should only handle conversion from integer to float.");
10076   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10077
10078   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10079
10080   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10081     return SDValue();
10082
10083   SmallVector<SDValue, 8> Opnds;
10084   for (unsigned i = 0; i != NumInScalars; ++i) {
10085     SDValue In = N->getOperand(i);
10086
10087     if (In.getOpcode() == ISD::UNDEF)
10088       Opnds.push_back(DAG.getUNDEF(SrcVT));
10089     else
10090       Opnds.push_back(In.getOperand(0));
10091   }
10092   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10093                            &Opnds[0], Opnds.size());
10094   AddToWorkList(BV.getNode());
10095
10096   return DAG.getNode(Opcode, dl, VT, BV);
10097 }
10098
10099 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10100   unsigned NumInScalars = N->getNumOperands();
10101   SDLoc dl(N);
10102   EVT VT = N->getValueType(0);
10103
10104   // A vector built entirely of undefs is undef.
10105   if (ISD::allOperandsUndef(N))
10106     return DAG.getUNDEF(VT);
10107
10108   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10109   if (V.getNode())
10110     return V;
10111
10112   V = reduceBuildVecConvertToConvertBuildVec(N);
10113   if (V.getNode())
10114     return V;
10115
10116   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10117   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10118   // at most two distinct vectors, turn this into a shuffle node.
10119
10120   // May only combine to shuffle after legalize if shuffle is legal.
10121   if (LegalOperations &&
10122       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10123     return SDValue();
10124
10125   SDValue VecIn1, VecIn2;
10126   for (unsigned i = 0; i != NumInScalars; ++i) {
10127     // Ignore undef inputs.
10128     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10129
10130     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10131     // constant index, bail out.
10132     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10133         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10134       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10135       break;
10136     }
10137
10138     // We allow up to two distinct input vectors.
10139     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10140     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10141       continue;
10142
10143     if (!VecIn1.getNode()) {
10144       VecIn1 = ExtractedFromVec;
10145     } else if (!VecIn2.getNode()) {
10146       VecIn2 = ExtractedFromVec;
10147     } else {
10148       // Too many inputs.
10149       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10150       break;
10151     }
10152   }
10153
10154     // If everything is good, we can make a shuffle operation.
10155   if (VecIn1.getNode()) {
10156     SmallVector<int, 8> Mask;
10157     for (unsigned i = 0; i != NumInScalars; ++i) {
10158       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10159         Mask.push_back(-1);
10160         continue;
10161       }
10162
10163       // If extracting from the first vector, just use the index directly.
10164       SDValue Extract = N->getOperand(i);
10165       SDValue ExtVal = Extract.getOperand(1);
10166       if (Extract.getOperand(0) == VecIn1) {
10167         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10168         if (ExtIndex > VT.getVectorNumElements())
10169           return SDValue();
10170
10171         Mask.push_back(ExtIndex);
10172         continue;
10173       }
10174
10175       // Otherwise, use InIdx + VecSize
10176       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10177       Mask.push_back(Idx+NumInScalars);
10178     }
10179
10180     // We can't generate a shuffle node with mismatched input and output types.
10181     // Attempt to transform a single input vector to the correct type.
10182     if ((VT != VecIn1.getValueType())) {
10183       // We don't support shuffeling between TWO values of different types.
10184       if (VecIn2.getNode())
10185         return SDValue();
10186
10187       // We only support widening of vectors which are half the size of the
10188       // output registers. For example XMM->YMM widening on X86 with AVX.
10189       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10190         return SDValue();
10191
10192       // If the input vector type has a different base type to the output
10193       // vector type, bail out.
10194       if (VecIn1.getValueType().getVectorElementType() !=
10195           VT.getVectorElementType())
10196         return SDValue();
10197
10198       // Widen the input vector by adding undef values.
10199       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10200                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10201     }
10202
10203     // If VecIn2 is unused then change it to undef.
10204     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10205
10206     // Check that we were able to transform all incoming values to the same
10207     // type.
10208     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10209         VecIn1.getValueType() != VT)
10210           return SDValue();
10211
10212     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10213     if (!isTypeLegal(VT))
10214       return SDValue();
10215
10216     // Return the new VECTOR_SHUFFLE node.
10217     SDValue Ops[2];
10218     Ops[0] = VecIn1;
10219     Ops[1] = VecIn2;
10220     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10221   }
10222
10223   return SDValue();
10224 }
10225
10226 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10227   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10228   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10229   // inputs come from at most two distinct vectors, turn this into a shuffle
10230   // node.
10231
10232   // If we only have one input vector, we don't need to do any concatenation.
10233   if (N->getNumOperands() == 1)
10234     return N->getOperand(0);
10235
10236   // Check if all of the operands are undefs.
10237   EVT VT = N->getValueType(0);
10238   if (ISD::allOperandsUndef(N))
10239     return DAG.getUNDEF(VT);
10240
10241   // Optimize concat_vectors where one of the vectors is undef.
10242   if (N->getNumOperands() == 2 &&
10243       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10244     SDValue In = N->getOperand(0);
10245     assert(In.getValueType().isVector() && "Must concat vectors");
10246
10247     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10248     if (In->getOpcode() == ISD::BITCAST &&
10249         !In->getOperand(0)->getValueType(0).isVector()) {
10250       SDValue Scalar = In->getOperand(0);
10251       EVT SclTy = Scalar->getValueType(0);
10252
10253       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10254         return SDValue();
10255
10256       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10257                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10258       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10259         return SDValue();
10260
10261       SDLoc dl = SDLoc(N);
10262       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10263       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10264     }
10265   }
10266
10267   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10268   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10269   if (N->getNumOperands() == 2 &&
10270       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10271       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10272     EVT VT = N->getValueType(0);
10273     SDValue N0 = N->getOperand(0);
10274     SDValue N1 = N->getOperand(1);
10275     SmallVector<SDValue, 8> Opnds;
10276     unsigned BuildVecNumElts =  N0.getNumOperands();
10277
10278     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10279       Opnds.push_back(N0.getOperand(i));
10280     for (unsigned i = 0; i != BuildVecNumElts; ++i)
10281       Opnds.push_back(N1.getOperand(i));
10282
10283     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10284                        Opnds.size());
10285   }
10286
10287   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10288   // nodes often generate nop CONCAT_VECTOR nodes.
10289   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10290   // place the incoming vectors at the exact same location.
10291   SDValue SingleSource = SDValue();
10292   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10293
10294   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10295     SDValue Op = N->getOperand(i);
10296
10297     if (Op.getOpcode() == ISD::UNDEF)
10298       continue;
10299
10300     // Check if this is the identity extract:
10301     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10302       return SDValue();
10303
10304     // Find the single incoming vector for the extract_subvector.
10305     if (SingleSource.getNode()) {
10306       if (Op.getOperand(0) != SingleSource)
10307         return SDValue();
10308     } else {
10309       SingleSource = Op.getOperand(0);
10310
10311       // Check the source type is the same as the type of the result.
10312       // If not, this concat may extend the vector, so we can not
10313       // optimize it away.
10314       if (SingleSource.getValueType() != N->getValueType(0))
10315         return SDValue();
10316     }
10317
10318     unsigned IdentityIndex = i * PartNumElem;
10319     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10320     // The extract index must be constant.
10321     if (!CS)
10322       return SDValue();
10323
10324     // Check that we are reading from the identity index.
10325     if (CS->getZExtValue() != IdentityIndex)
10326       return SDValue();
10327   }
10328
10329   if (SingleSource.getNode())
10330     return SingleSource;
10331
10332   return SDValue();
10333 }
10334
10335 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10336   EVT NVT = N->getValueType(0);
10337   SDValue V = N->getOperand(0);
10338
10339   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10340     // Combine:
10341     //    (extract_subvec (concat V1, V2, ...), i)
10342     // Into:
10343     //    Vi if possible
10344     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10345     // type.
10346     if (V->getOperand(0).getValueType() != NVT)
10347       return SDValue();
10348     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10349     unsigned NumElems = NVT.getVectorNumElements();
10350     assert((Idx % NumElems) == 0 &&
10351            "IDX in concat is not a multiple of the result vector length.");
10352     return V->getOperand(Idx / NumElems);
10353   }
10354
10355   // Skip bitcasting
10356   if (V->getOpcode() == ISD::BITCAST)
10357     V = V.getOperand(0);
10358
10359   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10360     SDLoc dl(N);
10361     // Handle only simple case where vector being inserted and vector
10362     // being extracted are of same type, and are half size of larger vectors.
10363     EVT BigVT = V->getOperand(0).getValueType();
10364     EVT SmallVT = V->getOperand(1).getValueType();
10365     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10366       return SDValue();
10367
10368     // Only handle cases where both indexes are constants with the same type.
10369     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10370     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10371
10372     if (InsIdx && ExtIdx &&
10373         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10374         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10375       // Combine:
10376       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10377       // Into:
10378       //    indices are equal or bit offsets are equal => V1
10379       //    otherwise => (extract_subvec V1, ExtIdx)
10380       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10381           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10382         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10383       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10384                          DAG.getNode(ISD::BITCAST, dl,
10385                                      N->getOperand(0).getValueType(),
10386                                      V->getOperand(0)), N->getOperand(1));
10387     }
10388   }
10389
10390   return SDValue();
10391 }
10392
10393 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10394 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10395   EVT VT = N->getValueType(0);
10396   unsigned NumElts = VT.getVectorNumElements();
10397
10398   SDValue N0 = N->getOperand(0);
10399   SDValue N1 = N->getOperand(1);
10400   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10401
10402   SmallVector<SDValue, 4> Ops;
10403   EVT ConcatVT = N0.getOperand(0).getValueType();
10404   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10405   unsigned NumConcats = NumElts / NumElemsPerConcat;
10406
10407   // Look at every vector that's inserted. We're looking for exact
10408   // subvector-sized copies from a concatenated vector
10409   for (unsigned I = 0; I != NumConcats; ++I) {
10410     // Make sure we're dealing with a copy.
10411     unsigned Begin = I * NumElemsPerConcat;
10412     bool AllUndef = true, NoUndef = true;
10413     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10414       if (SVN->getMaskElt(J) >= 0)
10415         AllUndef = false;
10416       else
10417         NoUndef = false;
10418     }
10419
10420     if (NoUndef) {
10421       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10422         return SDValue();
10423
10424       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10425         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10426           return SDValue();
10427
10428       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10429       if (FirstElt < N0.getNumOperands())
10430         Ops.push_back(N0.getOperand(FirstElt));
10431       else
10432         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10433
10434     } else if (AllUndef) {
10435       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10436     } else { // Mixed with general masks and undefs, can't do optimization.
10437       return SDValue();
10438     }
10439   }
10440
10441   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10442                      Ops.size());
10443 }
10444
10445 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10446   EVT VT = N->getValueType(0);
10447   unsigned NumElts = VT.getVectorNumElements();
10448
10449   SDValue N0 = N->getOperand(0);
10450   SDValue N1 = N->getOperand(1);
10451
10452   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10453
10454   // Canonicalize shuffle undef, undef -> undef
10455   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10456     return DAG.getUNDEF(VT);
10457
10458   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10459
10460   // Canonicalize shuffle v, v -> v, undef
10461   if (N0 == N1) {
10462     SmallVector<int, 8> NewMask;
10463     for (unsigned i = 0; i != NumElts; ++i) {
10464       int Idx = SVN->getMaskElt(i);
10465       if (Idx >= (int)NumElts) Idx -= NumElts;
10466       NewMask.push_back(Idx);
10467     }
10468     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10469                                 &NewMask[0]);
10470   }
10471
10472   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10473   if (N0.getOpcode() == ISD::UNDEF) {
10474     SmallVector<int, 8> NewMask;
10475     for (unsigned i = 0; i != NumElts; ++i) {
10476       int Idx = SVN->getMaskElt(i);
10477       if (Idx >= 0) {
10478         if (Idx >= (int)NumElts)
10479           Idx -= NumElts;
10480         else
10481           Idx = -1; // remove reference to lhs
10482       }
10483       NewMask.push_back(Idx);
10484     }
10485     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10486                                 &NewMask[0]);
10487   }
10488
10489   // Remove references to rhs if it is undef
10490   if (N1.getOpcode() == ISD::UNDEF) {
10491     bool Changed = false;
10492     SmallVector<int, 8> NewMask;
10493     for (unsigned i = 0; i != NumElts; ++i) {
10494       int Idx = SVN->getMaskElt(i);
10495       if (Idx >= (int)NumElts) {
10496         Idx = -1;
10497         Changed = true;
10498       }
10499       NewMask.push_back(Idx);
10500     }
10501     if (Changed)
10502       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10503   }
10504
10505   // If it is a splat, check if the argument vector is another splat or a
10506   // build_vector with all scalar elements the same.
10507   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10508     SDNode *V = N0.getNode();
10509
10510     // If this is a bit convert that changes the element type of the vector but
10511     // not the number of vector elements, look through it.  Be careful not to
10512     // look though conversions that change things like v4f32 to v2f64.
10513     if (V->getOpcode() == ISD::BITCAST) {
10514       SDValue ConvInput = V->getOperand(0);
10515       if (ConvInput.getValueType().isVector() &&
10516           ConvInput.getValueType().getVectorNumElements() == NumElts)
10517         V = ConvInput.getNode();
10518     }
10519
10520     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10521       assert(V->getNumOperands() == NumElts &&
10522              "BUILD_VECTOR has wrong number of operands");
10523       SDValue Base;
10524       bool AllSame = true;
10525       for (unsigned i = 0; i != NumElts; ++i) {
10526         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10527           Base = V->getOperand(i);
10528           break;
10529         }
10530       }
10531       // Splat of <u, u, u, u>, return <u, u, u, u>
10532       if (!Base.getNode())
10533         return N0;
10534       for (unsigned i = 0; i != NumElts; ++i) {
10535         if (V->getOperand(i) != Base) {
10536           AllSame = false;
10537           break;
10538         }
10539       }
10540       // Splat of <x, x, x, x>, return <x, x, x, x>
10541       if (AllSame)
10542         return N0;
10543     }
10544   }
10545
10546   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10547       Level < AfterLegalizeVectorOps &&
10548       (N1.getOpcode() == ISD::UNDEF ||
10549       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10550        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10551     SDValue V = partitionShuffleOfConcats(N, DAG);
10552
10553     if (V.getNode())
10554       return V;
10555   }
10556
10557   // If this shuffle node is simply a swizzle of another shuffle node,
10558   // and it reverses the swizzle of the previous shuffle then we can
10559   // optimize shuffle(shuffle(x, undef), undef) -> x.
10560   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10561       N1.getOpcode() == ISD::UNDEF) {
10562
10563     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10564
10565     // Shuffle nodes can only reverse shuffles with a single non-undef value.
10566     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10567       return SDValue();
10568
10569     // The incoming shuffle must be of the same type as the result of the
10570     // current shuffle.
10571     assert(OtherSV->getOperand(0).getValueType() == VT &&
10572            "Shuffle types don't match");
10573
10574     for (unsigned i = 0; i != NumElts; ++i) {
10575       int Idx = SVN->getMaskElt(i);
10576       assert(Idx < (int)NumElts && "Index references undef operand");
10577       // Next, this index comes from the first value, which is the incoming
10578       // shuffle. Adopt the incoming index.
10579       if (Idx >= 0)
10580         Idx = OtherSV->getMaskElt(Idx);
10581
10582       // The combined shuffle must map each index to itself.
10583       if (Idx >= 0 && (unsigned)Idx != i)
10584         return SDValue();
10585     }
10586
10587     return OtherSV->getOperand(0);
10588   }
10589
10590   return SDValue();
10591 }
10592
10593 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10594   SDValue N0 = N->getOperand(0);
10595   SDValue N2 = N->getOperand(2);
10596
10597   // If the input vector is a concatenation, and the insert replaces
10598   // one of the halves, we can optimize into a single concat_vectors.
10599   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10600       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10601     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10602     EVT VT = N->getValueType(0);
10603
10604     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10605     // (concat_vectors Z, Y)
10606     if (InsIdx == 0)
10607       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10608                          N->getOperand(1), N0.getOperand(1));
10609
10610     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10611     // (concat_vectors X, Z)
10612     if (InsIdx == VT.getVectorNumElements()/2)
10613       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10614                          N0.getOperand(0), N->getOperand(1));
10615   }
10616
10617   return SDValue();
10618 }
10619
10620 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10621 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10622 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10623 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10624 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10625   EVT VT = N->getValueType(0);
10626   SDLoc dl(N);
10627   SDValue LHS = N->getOperand(0);
10628   SDValue RHS = N->getOperand(1);
10629   if (N->getOpcode() == ISD::AND) {
10630     if (RHS.getOpcode() == ISD::BITCAST)
10631       RHS = RHS.getOperand(0);
10632     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10633       SmallVector<int, 8> Indices;
10634       unsigned NumElts = RHS.getNumOperands();
10635       for (unsigned i = 0; i != NumElts; ++i) {
10636         SDValue Elt = RHS.getOperand(i);
10637         if (!isa<ConstantSDNode>(Elt))
10638           return SDValue();
10639
10640         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10641           Indices.push_back(i);
10642         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10643           Indices.push_back(NumElts);
10644         else
10645           return SDValue();
10646       }
10647
10648       // Let's see if the target supports this vector_shuffle.
10649       EVT RVT = RHS.getValueType();
10650       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10651         return SDValue();
10652
10653       // Return the new VECTOR_SHUFFLE node.
10654       EVT EltVT = RVT.getVectorElementType();
10655       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10656                                      DAG.getConstant(0, EltVT));
10657       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10658                                  RVT, &ZeroOps[0], ZeroOps.size());
10659       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10660       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10661       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10662     }
10663   }
10664
10665   return SDValue();
10666 }
10667
10668 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10669 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10670   assert(N->getValueType(0).isVector() &&
10671          "SimplifyVBinOp only works on vectors!");
10672
10673   SDValue LHS = N->getOperand(0);
10674   SDValue RHS = N->getOperand(1);
10675   SDValue Shuffle = XformToShuffleWithZero(N);
10676   if (Shuffle.getNode()) return Shuffle;
10677
10678   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10679   // this operation.
10680   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10681       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10682     // Check if both vectors are constants. If not bail out.
10683     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10684           cast<BuildVectorSDNode>(RHS)->isConstant()))
10685       return SDValue();
10686
10687     SmallVector<SDValue, 8> Ops;
10688     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10689       SDValue LHSOp = LHS.getOperand(i);
10690       SDValue RHSOp = RHS.getOperand(i);
10691
10692       // Can't fold divide by zero.
10693       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10694           N->getOpcode() == ISD::FDIV) {
10695         if ((RHSOp.getOpcode() == ISD::Constant &&
10696              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10697             (RHSOp.getOpcode() == ISD::ConstantFP &&
10698              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10699           break;
10700       }
10701
10702       EVT VT = LHSOp.getValueType();
10703       EVT RVT = RHSOp.getValueType();
10704       if (RVT != VT) {
10705         // Integer BUILD_VECTOR operands may have types larger than the element
10706         // size (e.g., when the element type is not legal).  Prior to type
10707         // legalization, the types may not match between the two BUILD_VECTORS.
10708         // Truncate one of the operands to make them match.
10709         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10710           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10711         } else {
10712           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10713           VT = RVT;
10714         }
10715       }
10716       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10717                                    LHSOp, RHSOp);
10718       if (FoldOp.getOpcode() != ISD::UNDEF &&
10719           FoldOp.getOpcode() != ISD::Constant &&
10720           FoldOp.getOpcode() != ISD::ConstantFP)
10721         break;
10722       Ops.push_back(FoldOp);
10723       AddToWorkList(FoldOp.getNode());
10724     }
10725
10726     if (Ops.size() == LHS.getNumOperands())
10727       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10728                          LHS.getValueType(), &Ops[0], Ops.size());
10729   }
10730
10731   return SDValue();
10732 }
10733
10734 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10735 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10736   assert(N->getValueType(0).isVector() &&
10737          "SimplifyVUnaryOp only works on vectors!");
10738
10739   SDValue N0 = N->getOperand(0);
10740
10741   if (N0.getOpcode() != ISD::BUILD_VECTOR)
10742     return SDValue();
10743
10744   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10745   SmallVector<SDValue, 8> Ops;
10746   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10747     SDValue Op = N0.getOperand(i);
10748     if (Op.getOpcode() != ISD::UNDEF &&
10749         Op.getOpcode() != ISD::ConstantFP)
10750       break;
10751     EVT EltVT = Op.getValueType();
10752     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10753     if (FoldOp.getOpcode() != ISD::UNDEF &&
10754         FoldOp.getOpcode() != ISD::ConstantFP)
10755       break;
10756     Ops.push_back(FoldOp);
10757     AddToWorkList(FoldOp.getNode());
10758   }
10759
10760   if (Ops.size() != N0.getNumOperands())
10761     return SDValue();
10762
10763   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10764                      N0.getValueType(), &Ops[0], Ops.size());
10765 }
10766
10767 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10768                                     SDValue N1, SDValue N2){
10769   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10770
10771   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10772                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
10773
10774   // If we got a simplified select_cc node back from SimplifySelectCC, then
10775   // break it down into a new SETCC node, and a new SELECT node, and then return
10776   // the SELECT node, since we were called with a SELECT node.
10777   if (SCC.getNode()) {
10778     // Check to see if we got a select_cc back (to turn into setcc/select).
10779     // Otherwise, just return whatever node we got back, like fabs.
10780     if (SCC.getOpcode() == ISD::SELECT_CC) {
10781       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10782                                   N0.getValueType(),
10783                                   SCC.getOperand(0), SCC.getOperand(1),
10784                                   SCC.getOperand(4));
10785       AddToWorkList(SETCC.getNode());
10786       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10787                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
10788     }
10789
10790     return SCC;
10791   }
10792   return SDValue();
10793 }
10794
10795 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10796 /// are the two values being selected between, see if we can simplify the
10797 /// select.  Callers of this should assume that TheSelect is deleted if this
10798 /// returns true.  As such, they should return the appropriate thing (e.g. the
10799 /// node) back to the top-level of the DAG combiner loop to avoid it being
10800 /// looked at.
10801 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10802                                     SDValue RHS) {
10803
10804   // Cannot simplify select with vector condition
10805   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10806
10807   // If this is a select from two identical things, try to pull the operation
10808   // through the select.
10809   if (LHS.getOpcode() != RHS.getOpcode() ||
10810       !LHS.hasOneUse() || !RHS.hasOneUse())
10811     return false;
10812
10813   // If this is a load and the token chain is identical, replace the select
10814   // of two loads with a load through a select of the address to load from.
10815   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10816   // constants have been dropped into the constant pool.
10817   if (LHS.getOpcode() == ISD::LOAD) {
10818     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10819     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10820
10821     // Token chains must be identical.
10822     if (LHS.getOperand(0) != RHS.getOperand(0) ||
10823         // Do not let this transformation reduce the number of volatile loads.
10824         LLD->isVolatile() || RLD->isVolatile() ||
10825         // If this is an EXTLOAD, the VT's must match.
10826         LLD->getMemoryVT() != RLD->getMemoryVT() ||
10827         // If this is an EXTLOAD, the kind of extension must match.
10828         (LLD->getExtensionType() != RLD->getExtensionType() &&
10829          // The only exception is if one of the extensions is anyext.
10830          LLD->getExtensionType() != ISD::EXTLOAD &&
10831          RLD->getExtensionType() != ISD::EXTLOAD) ||
10832         // FIXME: this discards src value information.  This is
10833         // over-conservative. It would be beneficial to be able to remember
10834         // both potential memory locations.  Since we are discarding
10835         // src value info, don't do the transformation if the memory
10836         // locations are not in the default address space.
10837         LLD->getPointerInfo().getAddrSpace() != 0 ||
10838         RLD->getPointerInfo().getAddrSpace() != 0 ||
10839         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10840                                       LLD->getBasePtr().getValueType()))
10841       return false;
10842
10843     // Check that the select condition doesn't reach either load.  If so,
10844     // folding this will induce a cycle into the DAG.  If not, this is safe to
10845     // xform, so create a select of the addresses.
10846     SDValue Addr;
10847     if (TheSelect->getOpcode() == ISD::SELECT) {
10848       SDNode *CondNode = TheSelect->getOperand(0).getNode();
10849       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10850           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10851         return false;
10852       // The loads must not depend on one another.
10853       if (LLD->isPredecessorOf(RLD) ||
10854           RLD->isPredecessorOf(LLD))
10855         return false;
10856       Addr = DAG.getSelect(SDLoc(TheSelect),
10857                            LLD->getBasePtr().getValueType(),
10858                            TheSelect->getOperand(0), LLD->getBasePtr(),
10859                            RLD->getBasePtr());
10860     } else {  // Otherwise SELECT_CC
10861       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10862       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10863
10864       if ((LLD->hasAnyUseOfValue(1) &&
10865            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10866           (RLD->hasAnyUseOfValue(1) &&
10867            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10868         return false;
10869
10870       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10871                          LLD->getBasePtr().getValueType(),
10872                          TheSelect->getOperand(0),
10873                          TheSelect->getOperand(1),
10874                          LLD->getBasePtr(), RLD->getBasePtr(),
10875                          TheSelect->getOperand(4));
10876     }
10877
10878     SDValue Load;
10879     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10880       Load = DAG.getLoad(TheSelect->getValueType(0),
10881                          SDLoc(TheSelect),
10882                          // FIXME: Discards pointer and TBAA info.
10883                          LLD->getChain(), Addr, MachinePointerInfo(),
10884                          LLD->isVolatile(), LLD->isNonTemporal(),
10885                          LLD->isInvariant(), LLD->getAlignment());
10886     } else {
10887       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10888                             RLD->getExtensionType() : LLD->getExtensionType(),
10889                             SDLoc(TheSelect),
10890                             TheSelect->getValueType(0),
10891                             // FIXME: Discards pointer and TBAA info.
10892                             LLD->getChain(), Addr, MachinePointerInfo(),
10893                             LLD->getMemoryVT(), LLD->isVolatile(),
10894                             LLD->isNonTemporal(), LLD->getAlignment());
10895     }
10896
10897     // Users of the select now use the result of the load.
10898     CombineTo(TheSelect, Load);
10899
10900     // Users of the old loads now use the new load's chain.  We know the
10901     // old-load value is dead now.
10902     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10903     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10904     return true;
10905   }
10906
10907   return false;
10908 }
10909
10910 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10911 /// where 'cond' is the comparison specified by CC.
10912 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10913                                       SDValue N2, SDValue N3,
10914                                       ISD::CondCode CC, bool NotExtCompare) {
10915   // (x ? y : y) -> y.
10916   if (N2 == N3) return N2;
10917
10918   EVT VT = N2.getValueType();
10919   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10920   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10921   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10922
10923   // Determine if the condition we're dealing with is constant
10924   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10925                               N0, N1, CC, DL, false);
10926   if (SCC.getNode()) AddToWorkList(SCC.getNode());
10927   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10928
10929   // fold select_cc true, x, y -> x
10930   if (SCCC && !SCCC->isNullValue())
10931     return N2;
10932   // fold select_cc false, x, y -> y
10933   if (SCCC && SCCC->isNullValue())
10934     return N3;
10935
10936   // Check to see if we can simplify the select into an fabs node
10937   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10938     // Allow either -0.0 or 0.0
10939     if (CFP->getValueAPF().isZero()) {
10940       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10941       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10942           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10943           N2 == N3.getOperand(0))
10944         return DAG.getNode(ISD::FABS, DL, VT, N0);
10945
10946       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10947       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10948           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10949           N2.getOperand(0) == N3)
10950         return DAG.getNode(ISD::FABS, DL, VT, N3);
10951     }
10952   }
10953
10954   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10955   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10956   // in it.  This is a win when the constant is not otherwise available because
10957   // it replaces two constant pool loads with one.  We only do this if the FP
10958   // type is known to be legal, because if it isn't, then we are before legalize
10959   // types an we want the other legalization to happen first (e.g. to avoid
10960   // messing with soft float) and if the ConstantFP is not legal, because if
10961   // it is legal, we may not need to store the FP constant in a constant pool.
10962   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10963     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10964       if (TLI.isTypeLegal(N2.getValueType()) &&
10965           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10966            TargetLowering::Legal) &&
10967           // If both constants have multiple uses, then we won't need to do an
10968           // extra load, they are likely around in registers for other users.
10969           (TV->hasOneUse() || FV->hasOneUse())) {
10970         Constant *Elts[] = {
10971           const_cast<ConstantFP*>(FV->getConstantFPValue()),
10972           const_cast<ConstantFP*>(TV->getConstantFPValue())
10973         };
10974         Type *FPTy = Elts[0]->getType();
10975         const DataLayout &TD = *TLI.getDataLayout();
10976
10977         // Create a ConstantArray of the two constants.
10978         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10979         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10980                                             TD.getPrefTypeAlignment(FPTy));
10981         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10982
10983         // Get the offsets to the 0 and 1 element of the array so that we can
10984         // select between them.
10985         SDValue Zero = DAG.getIntPtrConstant(0);
10986         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10987         SDValue One = DAG.getIntPtrConstant(EltSize);
10988
10989         SDValue Cond = DAG.getSetCC(DL,
10990                                     getSetCCResultType(N0.getValueType()),
10991                                     N0, N1, CC);
10992         AddToWorkList(Cond.getNode());
10993         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10994                                           Cond, One, Zero);
10995         AddToWorkList(CstOffset.getNode());
10996         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10997                             CstOffset);
10998         AddToWorkList(CPIdx.getNode());
10999         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11000                            MachinePointerInfo::getConstantPool(), false,
11001                            false, false, Alignment);
11002
11003       }
11004     }
11005
11006   // Check to see if we can perform the "gzip trick", transforming
11007   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11008   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11009       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11010        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11011     EVT XType = N0.getValueType();
11012     EVT AType = N2.getValueType();
11013     if (XType.bitsGE(AType)) {
11014       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11015       // single-bit constant.
11016       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11017         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11018         ShCtV = XType.getSizeInBits()-ShCtV-1;
11019         SDValue ShCt = DAG.getConstant(ShCtV,
11020                                        getShiftAmountTy(N0.getValueType()));
11021         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11022                                     XType, N0, ShCt);
11023         AddToWorkList(Shift.getNode());
11024
11025         if (XType.bitsGT(AType)) {
11026           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11027           AddToWorkList(Shift.getNode());
11028         }
11029
11030         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11031       }
11032
11033       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11034                                   XType, N0,
11035                                   DAG.getConstant(XType.getSizeInBits()-1,
11036                                          getShiftAmountTy(N0.getValueType())));
11037       AddToWorkList(Shift.getNode());
11038
11039       if (XType.bitsGT(AType)) {
11040         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11041         AddToWorkList(Shift.getNode());
11042       }
11043
11044       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11045     }
11046   }
11047
11048   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11049   // where y is has a single bit set.
11050   // A plaintext description would be, we can turn the SELECT_CC into an AND
11051   // when the condition can be materialized as an all-ones register.  Any
11052   // single bit-test can be materialized as an all-ones register with
11053   // shift-left and shift-right-arith.
11054   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11055       N0->getValueType(0) == VT &&
11056       N1C && N1C->isNullValue() &&
11057       N2C && N2C->isNullValue()) {
11058     SDValue AndLHS = N0->getOperand(0);
11059     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11060     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11061       // Shift the tested bit over the sign bit.
11062       APInt AndMask = ConstAndRHS->getAPIntValue();
11063       SDValue ShlAmt =
11064         DAG.getConstant(AndMask.countLeadingZeros(),
11065                         getShiftAmountTy(AndLHS.getValueType()));
11066       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11067
11068       // Now arithmetic right shift it all the way over, so the result is either
11069       // all-ones, or zero.
11070       SDValue ShrAmt =
11071         DAG.getConstant(AndMask.getBitWidth()-1,
11072                         getShiftAmountTy(Shl.getValueType()));
11073       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11074
11075       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11076     }
11077   }
11078
11079   // fold select C, 16, 0 -> shl C, 4
11080   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11081     TLI.getBooleanContents(N0.getValueType().isVector()) ==
11082       TargetLowering::ZeroOrOneBooleanContent) {
11083
11084     // If the caller doesn't want us to simplify this into a zext of a compare,
11085     // don't do it.
11086     if (NotExtCompare && N2C->getAPIntValue() == 1)
11087       return SDValue();
11088
11089     // Get a SetCC of the condition
11090     // NOTE: Don't create a SETCC if it's not legal on this target.
11091     if (!LegalOperations ||
11092         TLI.isOperationLegal(ISD::SETCC,
11093           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11094       SDValue Temp, SCC;
11095       // cast from setcc result type to select result type
11096       if (LegalTypes) {
11097         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11098                             N0, N1, CC);
11099         if (N2.getValueType().bitsLT(SCC.getValueType()))
11100           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11101                                         N2.getValueType());
11102         else
11103           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11104                              N2.getValueType(), SCC);
11105       } else {
11106         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11107         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11108                            N2.getValueType(), SCC);
11109       }
11110
11111       AddToWorkList(SCC.getNode());
11112       AddToWorkList(Temp.getNode());
11113
11114       if (N2C->getAPIntValue() == 1)
11115         return Temp;
11116
11117       // shl setcc result by log2 n2c
11118       return DAG.getNode(
11119           ISD::SHL, DL, N2.getValueType(), Temp,
11120           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11121                           getShiftAmountTy(Temp.getValueType())));
11122     }
11123   }
11124
11125   // Check to see if this is the equivalent of setcc
11126   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11127   // otherwise, go ahead with the folds.
11128   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11129     EVT XType = N0.getValueType();
11130     if (!LegalOperations ||
11131         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11132       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11133       if (Res.getValueType() != VT)
11134         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11135       return Res;
11136     }
11137
11138     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11139     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11140         (!LegalOperations ||
11141          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11142       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11143       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11144                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11145                                        getShiftAmountTy(Ctlz.getValueType())));
11146     }
11147     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11148     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11149       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11150                                   XType, DAG.getConstant(0, XType), N0);
11151       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11152       return DAG.getNode(ISD::SRL, DL, XType,
11153                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11154                          DAG.getConstant(XType.getSizeInBits()-1,
11155                                          getShiftAmountTy(XType)));
11156     }
11157     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11158     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11159       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11160                                  DAG.getConstant(XType.getSizeInBits()-1,
11161                                          getShiftAmountTy(N0.getValueType())));
11162       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11163     }
11164   }
11165
11166   // Check to see if this is an integer abs.
11167   // select_cc setg[te] X,  0,  X, -X ->
11168   // select_cc setgt    X, -1,  X, -X ->
11169   // select_cc setl[te] X,  0, -X,  X ->
11170   // select_cc setlt    X,  1, -X,  X ->
11171   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11172   if (N1C) {
11173     ConstantSDNode *SubC = nullptr;
11174     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11175          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11176         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11177       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11178     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11179               (N1C->isOne() && CC == ISD::SETLT)) &&
11180              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11181       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11182
11183     EVT XType = N0.getValueType();
11184     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11185       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11186                                   N0,
11187                                   DAG.getConstant(XType.getSizeInBits()-1,
11188                                          getShiftAmountTy(N0.getValueType())));
11189       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11190                                 XType, N0, Shift);
11191       AddToWorkList(Shift.getNode());
11192       AddToWorkList(Add.getNode());
11193       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11194     }
11195   }
11196
11197   return SDValue();
11198 }
11199
11200 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11201 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11202                                    SDValue N1, ISD::CondCode Cond,
11203                                    SDLoc DL, bool foldBooleans) {
11204   TargetLowering::DAGCombinerInfo
11205     DagCombineInfo(DAG, Level, false, this);
11206   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11207 }
11208
11209 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11210 /// return a DAG expression to select that will generate the same value by
11211 /// multiplying by a magic number.  See:
11212 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11213 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11214   std::vector<SDNode*> Built;
11215   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11216
11217   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11218        ii != ee; ++ii)
11219     AddToWorkList(*ii);
11220   return S;
11221 }
11222
11223 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11224 /// return a DAG expression to select that will generate the same value by
11225 /// multiplying by a magic number.  See:
11226 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11227 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11228   std::vector<SDNode*> Built;
11229   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11230
11231   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11232        ii != ee; ++ii)
11233     AddToWorkList(*ii);
11234   return S;
11235 }
11236
11237 /// FindBaseOffset - Return true if base is a frame index, which is known not
11238 // to alias with anything but itself.  Provides base object and offset as
11239 // results.
11240 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11241                            const GlobalValue *&GV, const void *&CV) {
11242   // Assume it is a primitive operation.
11243   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11244
11245   // If it's an adding a simple constant then integrate the offset.
11246   if (Base.getOpcode() == ISD::ADD) {
11247     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11248       Base = Base.getOperand(0);
11249       Offset += C->getZExtValue();
11250     }
11251   }
11252
11253   // Return the underlying GlobalValue, and update the Offset.  Return false
11254   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11255   // by multiple nodes with different offsets.
11256   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11257     GV = G->getGlobal();
11258     Offset += G->getOffset();
11259     return false;
11260   }
11261
11262   // Return the underlying Constant value, and update the Offset.  Return false
11263   // for ConstantSDNodes since the same constant pool entry may be represented
11264   // by multiple nodes with different offsets.
11265   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11266     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11267                                          : (const void *)C->getConstVal();
11268     Offset += C->getOffset();
11269     return false;
11270   }
11271   // If it's any of the following then it can't alias with anything but itself.
11272   return isa<FrameIndexSDNode>(Base);
11273 }
11274
11275 /// isAlias - Return true if there is any possibility that the two addresses
11276 /// overlap.
11277 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11278   // If they are the same then they must be aliases.
11279   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11280
11281   // If they are both volatile then they cannot be reordered.
11282   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11283
11284   // Gather base node and offset information.
11285   SDValue Base1, Base2;
11286   int64_t Offset1, Offset2;
11287   const GlobalValue *GV1, *GV2;
11288   const void *CV1, *CV2;
11289   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11290                                       Base1, Offset1, GV1, CV1);
11291   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11292                                       Base2, Offset2, GV2, CV2);
11293
11294   // If they have a same base address then check to see if they overlap.
11295   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11296     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11297              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11298
11299   // It is possible for different frame indices to alias each other, mostly
11300   // when tail call optimization reuses return address slots for arguments.
11301   // To catch this case, look up the actual index of frame indices to compute
11302   // the real alias relationship.
11303   if (isFrameIndex1 && isFrameIndex2) {
11304     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11305     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11306     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11307     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11308              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11309   }
11310
11311   // Otherwise, if we know what the bases are, and they aren't identical, then
11312   // we know they cannot alias.
11313   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11314     return false;
11315
11316   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11317   // compared to the size and offset of the access, we may be able to prove they
11318   // do not alias.  This check is conservative for now to catch cases created by
11319   // splitting vector types.
11320   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11321       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11322       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11323        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11324       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11325     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11326     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11327
11328     // There is no overlap between these relatively aligned accesses of similar
11329     // size, return no alias.
11330     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11331         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11332       return false;
11333   }
11334
11335   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11336     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11337 #ifndef NDEBUG
11338   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11339       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11340     UseAA = false;
11341 #endif
11342   if (UseAA &&
11343       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11344     // Use alias analysis information.
11345     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11346                                  Op1->getSrcValueOffset());
11347     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11348         Op0->getSrcValueOffset() - MinOffset;
11349     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11350         Op1->getSrcValueOffset() - MinOffset;
11351     AliasAnalysis::AliasResult AAResult =
11352         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11353                                          Overlap1,
11354                                          UseTBAA ? Op0->getTBAAInfo() : nullptr),
11355                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11356                                          Overlap2,
11357                                          UseTBAA ? Op1->getTBAAInfo() : nullptr));
11358     if (AAResult == AliasAnalysis::NoAlias)
11359       return false;
11360   }
11361
11362   // Otherwise we have to assume they alias.
11363   return true;
11364 }
11365
11366 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11367 /// looking for aliasing nodes and adding them to the Aliases vector.
11368 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11369                                    SmallVectorImpl<SDValue> &Aliases) {
11370   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11371   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11372
11373   // Get alias information for node.
11374   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11375
11376   // Starting off.
11377   Chains.push_back(OriginalChain);
11378   unsigned Depth = 0;
11379
11380   // Look at each chain and determine if it is an alias.  If so, add it to the
11381   // aliases list.  If not, then continue up the chain looking for the next
11382   // candidate.
11383   while (!Chains.empty()) {
11384     SDValue Chain = Chains.back();
11385     Chains.pop_back();
11386
11387     // For TokenFactor nodes, look at each operand and only continue up the
11388     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11389     // find more and revert to original chain since the xform is unlikely to be
11390     // profitable.
11391     //
11392     // FIXME: The depth check could be made to return the last non-aliasing
11393     // chain we found before we hit a tokenfactor rather than the original
11394     // chain.
11395     if (Depth > 6 || Aliases.size() == 2) {
11396       Aliases.clear();
11397       Aliases.push_back(OriginalChain);
11398       return;
11399     }
11400
11401     // Don't bother if we've been before.
11402     if (!Visited.insert(Chain.getNode()))
11403       continue;
11404
11405     switch (Chain.getOpcode()) {
11406     case ISD::EntryToken:
11407       // Entry token is ideal chain operand, but handled in FindBetterChain.
11408       break;
11409
11410     case ISD::LOAD:
11411     case ISD::STORE: {
11412       // Get alias information for Chain.
11413       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11414           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11415
11416       // If chain is alias then stop here.
11417       if (!(IsLoad && IsOpLoad) &&
11418           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11419         Aliases.push_back(Chain);
11420       } else {
11421         // Look further up the chain.
11422         Chains.push_back(Chain.getOperand(0));
11423         ++Depth;
11424       }
11425       break;
11426     }
11427
11428     case ISD::TokenFactor:
11429       // We have to check each of the operands of the token factor for "small"
11430       // token factors, so we queue them up.  Adding the operands to the queue
11431       // (stack) in reverse order maintains the original order and increases the
11432       // likelihood that getNode will find a matching token factor (CSE.)
11433       if (Chain.getNumOperands() > 16) {
11434         Aliases.push_back(Chain);
11435         break;
11436       }
11437       for (unsigned n = Chain.getNumOperands(); n;)
11438         Chains.push_back(Chain.getOperand(--n));
11439       ++Depth;
11440       break;
11441
11442     default:
11443       // For all other instructions we will just have to take what we can get.
11444       Aliases.push_back(Chain);
11445       break;
11446     }
11447   }
11448
11449   // We need to be careful here to also search for aliases through the
11450   // value operand of a store, etc. Consider the following situation:
11451   //   Token1 = ...
11452   //   L1 = load Token1, %52
11453   //   S1 = store Token1, L1, %51
11454   //   L2 = load Token1, %52+8
11455   //   S2 = store Token1, L2, %51+8
11456   //   Token2 = Token(S1, S2)
11457   //   L3 = load Token2, %53
11458   //   S3 = store Token2, L3, %52
11459   //   L4 = load Token2, %53+8
11460   //   S4 = store Token2, L4, %52+8
11461   // If we search for aliases of S3 (which loads address %52), and we look
11462   // only through the chain, then we'll miss the trivial dependence on L1
11463   // (which also loads from %52). We then might change all loads and
11464   // stores to use Token1 as their chain operand, which could result in
11465   // copying %53 into %52 before copying %52 into %51 (which should
11466   // happen first).
11467   //
11468   // The problem is, however, that searching for such data dependencies
11469   // can become expensive, and the cost is not directly related to the
11470   // chain depth. Instead, we'll rule out such configurations here by
11471   // insisting that we've visited all chain users (except for users
11472   // of the original chain, which is not necessary). When doing this,
11473   // we need to look through nodes we don't care about (otherwise, things
11474   // like register copies will interfere with trivial cases).
11475
11476   SmallVector<const SDNode *, 16> Worklist;
11477   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11478        IE = Visited.end(); I != IE; ++I)
11479     if (*I != OriginalChain.getNode())
11480       Worklist.push_back(*I);
11481
11482   while (!Worklist.empty()) {
11483     const SDNode *M = Worklist.pop_back_val();
11484
11485     // We have already visited M, and want to make sure we've visited any uses
11486     // of M that we care about. For uses that we've not visisted, and don't
11487     // care about, queue them to the worklist.
11488
11489     for (SDNode::use_iterator UI = M->use_begin(),
11490          UIE = M->use_end(); UI != UIE; ++UI)
11491       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11492         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11493           // We've not visited this use, and we care about it (it could have an
11494           // ordering dependency with the original node).
11495           Aliases.clear();
11496           Aliases.push_back(OriginalChain);
11497           return;
11498         }
11499
11500         // We've not visited this use, but we don't care about it. Mark it as
11501         // visited and enqueue it to the worklist.
11502         Worklist.push_back(*UI);
11503       }
11504   }
11505 }
11506
11507 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11508 /// for a better chain (aliasing node.)
11509 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11510   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11511
11512   // Accumulate all the aliases to this node.
11513   GatherAllAliases(N, OldChain, Aliases);
11514
11515   // If no operands then chain to entry token.
11516   if (Aliases.size() == 0)
11517     return DAG.getEntryNode();
11518
11519   // If a single operand then chain to it.  We don't need to revisit it.
11520   if (Aliases.size() == 1)
11521     return Aliases[0];
11522
11523   // Construct a custom tailored token factor.
11524   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11525                      &Aliases[0], Aliases.size());
11526 }
11527
11528 // SelectionDAG::Combine - This is the entry point for the file.
11529 //
11530 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11531                            CodeGenOpt::Level OptLevel) {
11532   /// run - This is the main entry point to this class.
11533   ///
11534   DAGCombiner(*this, AA, OptLevel).Run(Level);
11535 }