Make sure no loads resulting from load->switch DAGCombine are marked invariant
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.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 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// AddUsersToWorklist - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// visit - call the node-specific routine that knows how to fold each
126     /// particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// AddToWorklist - Add to the work list making sure its instance is at the
131     /// back (next to be processed.)
132     void AddToWorklist(SDNode *N) {
133       // Skip handle nodes as they can't usefully be combined and confuse the
134       // zero-use deletion strategy.
135       if (N->getOpcode() == ISD::HANDLENODE)
136         return;
137
138       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139         Worklist.push_back(N);
140     }
141
142     /// removeFromWorklist - remove all instances of N from the worklist.
143     ///
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     bool recursivelyDeleteUnusedNodes(SDNode *N);
157
158     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
159                       bool AddTo = true);
160
161     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
162       return CombineTo(N, &Res, 1, AddTo);
163     }
164
165     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
166                       bool AddTo = true) {
167       SDValue To[] = { Res0, Res1 };
168       return CombineTo(N, To, 2, AddTo);
169     }
170
171     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
172
173   private:
174
175     /// SimplifyDemandedBits - Check the specified integer node value to see if
176     /// it can be simplified or if things it uses can be simplified by bit
177     /// propagation.  If so, return true.
178     bool SimplifyDemandedBits(SDValue Op) {
179       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
180       APInt Demanded = APInt::getAllOnesValue(BitWidth);
181       return SimplifyDemandedBits(Op, Demanded);
182     }
183
184     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
185
186     bool CombineToPreIndexedLoadStore(SDNode *N);
187     bool CombineToPostIndexedLoadStore(SDNode *N);
188     bool SliceUpLoad(SDNode *N);
189
190     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
191     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
192     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
193     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
194     SDValue PromoteIntBinOp(SDValue Op);
195     SDValue PromoteIntShiftOp(SDValue Op);
196     SDValue PromoteExtend(SDValue Op);
197     bool PromoteLoad(SDValue Op);
198
199     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
200                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
201                          ISD::NodeType ExtType);
202
203     /// combine - call the node-specific routine that knows how to fold each
204     /// particular type of node. If that doesn't do anything, try the
205     /// target-specific DAG combines.
206     SDValue combine(SDNode *N);
207
208     // Visitation implementation - Implement dag node combining for different
209     // node types.  The semantics are as follows:
210     // Return Value:
211     //   SDValue.getNode() == 0 - No change was made
212     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
213     //   otherwise              - N should be replaced by the returned Operand.
214     //
215     SDValue visitTokenFactor(SDNode *N);
216     SDValue visitMERGE_VALUES(SDNode *N);
217     SDValue visitADD(SDNode *N);
218     SDValue visitSUB(SDNode *N);
219     SDValue visitADDC(SDNode *N);
220     SDValue visitSUBC(SDNode *N);
221     SDValue visitADDE(SDNode *N);
222     SDValue visitSUBE(SDNode *N);
223     SDValue visitMUL(SDNode *N);
224     SDValue visitSDIV(SDNode *N);
225     SDValue visitUDIV(SDNode *N);
226     SDValue visitSREM(SDNode *N);
227     SDValue visitUREM(SDNode *N);
228     SDValue visitMULHU(SDNode *N);
229     SDValue visitMULHS(SDNode *N);
230     SDValue visitSMUL_LOHI(SDNode *N);
231     SDValue visitUMUL_LOHI(SDNode *N);
232     SDValue visitSMULO(SDNode *N);
233     SDValue visitUMULO(SDNode *N);
234     SDValue visitSDIVREM(SDNode *N);
235     SDValue visitUDIVREM(SDNode *N);
236     SDValue visitAND(SDNode *N);
237     SDValue visitOR(SDNode *N);
238     SDValue visitXOR(SDNode *N);
239     SDValue SimplifyVBinOp(SDNode *N);
240     SDValue SimplifyVUnaryOp(SDNode *N);
241     SDValue visitSHL(SDNode *N);
242     SDValue visitSRA(SDNode *N);
243     SDValue visitSRL(SDNode *N);
244     SDValue visitRotate(SDNode *N);
245     SDValue visitCTLZ(SDNode *N);
246     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
247     SDValue visitCTTZ(SDNode *N);
248     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
249     SDValue visitCTPOP(SDNode *N);
250     SDValue visitSELECT(SDNode *N);
251     SDValue visitVSELECT(SDNode *N);
252     SDValue visitSELECT_CC(SDNode *N);
253     SDValue visitSETCC(SDNode *N);
254     SDValue visitSIGN_EXTEND(SDNode *N);
255     SDValue visitZERO_EXTEND(SDNode *N);
256     SDValue visitANY_EXTEND(SDNode *N);
257     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
258     SDValue visitTRUNCATE(SDNode *N);
259     SDValue visitBITCAST(SDNode *N);
260     SDValue visitBUILD_PAIR(SDNode *N);
261     SDValue visitFADD(SDNode *N);
262     SDValue visitFSUB(SDNode *N);
263     SDValue visitFMUL(SDNode *N);
264     SDValue visitFMA(SDNode *N);
265     SDValue visitFDIV(SDNode *N);
266     SDValue visitFREM(SDNode *N);
267     SDValue visitFCOPYSIGN(SDNode *N);
268     SDValue visitSINT_TO_FP(SDNode *N);
269     SDValue visitUINT_TO_FP(SDNode *N);
270     SDValue visitFP_TO_SINT(SDNode *N);
271     SDValue visitFP_TO_UINT(SDNode *N);
272     SDValue visitFP_ROUND(SDNode *N);
273     SDValue visitFP_ROUND_INREG(SDNode *N);
274     SDValue visitFP_EXTEND(SDNode *N);
275     SDValue visitFNEG(SDNode *N);
276     SDValue visitFABS(SDNode *N);
277     SDValue visitFCEIL(SDNode *N);
278     SDValue visitFTRUNC(SDNode *N);
279     SDValue visitFFLOOR(SDNode *N);
280     SDValue visitBRCOND(SDNode *N);
281     SDValue visitBR_CC(SDNode *N);
282     SDValue visitLOAD(SDNode *N);
283     SDValue visitSTORE(SDNode *N);
284     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
285     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
286     SDValue visitBUILD_VECTOR(SDNode *N);
287     SDValue visitCONCAT_VECTORS(SDNode *N);
288     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
289     SDValue visitVECTOR_SHUFFLE(SDNode *N);
290     SDValue visitINSERT_SUBVECTOR(SDNode *N);
291
292     SDValue XformToShuffleWithZero(SDNode *N);
293     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
294
295     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
296
297     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
298     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
299     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
300     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
301                              SDValue N3, ISD::CondCode CC,
302                              bool NotExtCompare = false);
303     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
304                           SDLoc DL, bool foldBooleans = true);
305
306     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
307                            SDValue &CC) const;
308     bool isOneUseSetCC(SDValue N) const;
309
310     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
311                                          unsigned HiOp);
312     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
313     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
314     SDValue BuildSDIV(SDNode *N);
315     SDValue BuildSDIVPow2(SDNode *N);
316     SDValue BuildUDIV(SDNode *N);
317     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
318                                bool DemandHighBits = true);
319     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
320     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
321                               SDValue InnerPos, SDValue InnerNeg,
322                               unsigned PosOpcode, unsigned NegOpcode,
323                               SDLoc DL);
324     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
325     SDValue ReduceLoadWidth(SDNode *N);
326     SDValue ReduceLoadOpStoreWidth(SDNode *N);
327     SDValue TransformFPLoadStorePair(SDNode *N);
328     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
329     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
330
331     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
332
333     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
334     /// looking for aliasing nodes and adding them to the Aliases vector.
335     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
336                           SmallVectorImpl<SDValue> &Aliases);
337
338     /// isAlias - Return true if there is any possibility that the two addresses
339     /// overlap.
340     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
341
342     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343     /// looking for a better chain (aliasing node.)
344     SDValue FindBetterChain(SDNode *N, SDValue Chain);
345
346     /// Merge consecutive store operations into a wide store.
347     /// This optimization uses wide integers or vectors when possible.
348     /// \return True if some memory operations were changed.
349     bool MergeConsecutiveStores(StoreSDNode *N);
350
351     /// \brief Try to transform a truncation where C is a constant:
352     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
353     ///
354     /// \p N needs to be a truncation and its first operand an AND. Other
355     /// requirements are checked by the function (e.g. that trunc is
356     /// single-use) and if missed an empty SDValue is returned.
357     SDValue distributeTruncateThroughAnd(SDNode *N);
358
359   public:
360     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363       AttributeSet FnAttrs =
364           DAG.getMachineFunction().getFunction()->getAttributes();
365       ForCodeSize =
366           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367                                Attribute::OptimizeForSize) ||
368           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
369     }
370
371     /// Run - runs the dag combiner on all nodes in the work list
372     void Run(CombineLevel AtLevel);
373
374     SelectionDAG &getDAG() const { return DAG; }
375
376     /// getShiftAmountTy - Returns a type large enough to hold any valid
377     /// shift amount - before type legalization these can be huge.
378     EVT getShiftAmountTy(EVT LHSTy) {
379       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380       if (LHSTy.isVector())
381         return LHSTy;
382       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383                         : TLI.getPointerTy();
384     }
385
386     /// isTypeLegal - This method returns true if we are running before type
387     /// legalization or if the specified VT is legal.
388     bool isTypeLegal(const EVT &VT) {
389       if (!LegalTypes) return true;
390       return TLI.isTypeLegal(VT);
391     }
392
393     /// getSetCCResultType - Convenience wrapper around
394     /// TargetLowering::getSetCCResultType
395     EVT getSetCCResultType(EVT VT) const {
396       return TLI.getSetCCResultType(*DAG.getContext(), VT);
397     }
398   };
399 }
400
401
402 namespace {
403 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
406   DAGCombiner &DC;
407 public:
408   explicit WorklistRemover(DAGCombiner &dc)
409     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
410
411   void NodeDeleted(SDNode *N, SDNode *E) override {
412     DC.removeFromWorklist(N);
413   }
414 };
415 }
416
417 //===----------------------------------------------------------------------===//
418 //  TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
420
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422   ((DAGCombiner*)DC)->AddToWorklist(N);
423 }
424
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426   ((DAGCombiner*)DC)->removeFromWorklist(N);
427 }
428
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
432 }
433
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
437 }
438
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
443 }
444
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
448 }
449
450 //===----------------------------------------------------------------------===//
451 // Helper Functions
452 //===----------------------------------------------------------------------===//
453
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458                                const TargetLowering &TLI,
459                                const TargetOptions *Options,
460                                unsigned Depth = 0) {
461   // fneg is removable even if it has multiple uses.
462   if (Op.getOpcode() == ISD::FNEG) return 2;
463
464   // Don't allow anything with multiple uses.
465   if (!Op.hasOneUse()) return 0;
466
467   // Don't recurse exponentially.
468   if (Depth > 6) return 0;
469
470   switch (Op.getOpcode()) {
471   default: return false;
472   case ISD::ConstantFP:
473     // Don't invert constant FP values after legalize.  The negated constant
474     // isn't necessarily legal.
475     return LegalOperations ? 0 : 1;
476   case ISD::FADD:
477     // FIXME: determine better conditions for this xform.
478     if (!Options->UnsafeFPMath) return 0;
479
480     // After operation legalization, it might not be legal to create new FSUBs.
481     if (LegalOperations &&
482         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
483       return 0;
484
485     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487                                     Options, Depth + 1))
488       return V;
489     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
491                               Depth + 1);
492   case ISD::FSUB:
493     // We can't turn -(A-B) into B-A when we honor signed zeros.
494     if (!Options->UnsafeFPMath) return 0;
495
496     // fold (fneg (fsub A, B)) -> (fsub B, A)
497     return 1;
498
499   case ISD::FMUL:
500   case ISD::FDIV:
501     if (Options->HonorSignDependentRoundingFPMath()) return 0;
502
503     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
505                                     Options, Depth + 1))
506       return V;
507
508     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
509                               Depth + 1);
510
511   case ISD::FP_EXTEND:
512   case ISD::FP_ROUND:
513   case ISD::FSIN:
514     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
515                               Depth + 1);
516   }
517 }
518
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522                                     bool LegalOperations, unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
525
526   // Don't allow anything with multiple uses.
527   assert(Op.hasOneUse() && "Unknown reuse!");
528
529   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530   switch (Op.getOpcode()) {
531   default: llvm_unreachable("Unknown code");
532   case ISD::ConstantFP: {
533     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
534     V.changeSign();
535     return DAG.getConstantFP(V, Op.getValueType());
536   }
537   case ISD::FADD:
538     // FIXME: determine better conditions for this xform.
539     assert(DAG.getTarget().Options.UnsafeFPMath);
540
541     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                            DAG.getTargetLoweringInfo(),
544                            &DAG.getTarget().Options, Depth+1))
545       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                          GetNegatedExpression(Op.getOperand(0), DAG,
547                                               LegalOperations, Depth+1),
548                          Op.getOperand(1));
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551                        GetNegatedExpression(Op.getOperand(1), DAG,
552                                             LegalOperations, Depth+1),
553                        Op.getOperand(0));
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     assert(DAG.getTarget().Options.UnsafeFPMath);
557
558     // fold (fneg (fsub 0, B)) -> B
559     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560       if (N0CFP->getValueAPF().isZero())
561         return Op.getOperand(1);
562
563     // fold (fneg (fsub A, B)) -> (fsub B, A)
564     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565                        Op.getOperand(1), Op.getOperand(0));
566
567   case ISD::FMUL:
568   case ISD::FDIV:
569     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
570
571     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573                            DAG.getTargetLoweringInfo(),
574                            &DAG.getTarget().Options, Depth+1))
575       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576                          GetNegatedExpression(Op.getOperand(0), DAG,
577                                               LegalOperations, Depth+1),
578                          Op.getOperand(1));
579
580     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
582                        Op.getOperand(0),
583                        GetNegatedExpression(Op.getOperand(1), DAG,
584                                             LegalOperations, Depth+1));
585
586   case ISD::FP_EXTEND:
587   case ISD::FSIN:
588     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589                        GetNegatedExpression(Op.getOperand(0), DAG,
590                                             LegalOperations, Depth+1));
591   case ISD::FP_ROUND:
592       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593                          GetNegatedExpression(Op.getOperand(0), DAG,
594                                               LegalOperations, Depth+1),
595                          Op.getOperand(1));
596   }
597 }
598
599 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
600 // that selects between the target values used for true and false, making it
601 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
602 // the appropriate nodes based on the type of node we are checking. This
603 // simplifies life a bit for the callers.
604 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
605                                     SDValue &CC) const {
606   if (N.getOpcode() == ISD::SETCC) {
607     LHS = N.getOperand(0);
608     RHS = N.getOperand(1);
609     CC  = N.getOperand(2);
610     return true;
611   }
612
613   if (N.getOpcode() != ISD::SELECT_CC ||
614       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
615       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
616     return false;
617
618   LHS = N.getOperand(0);
619   RHS = N.getOperand(1);
620   CC  = N.getOperand(4);
621   return true;
622 }
623
624 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
625 // one use.  If this is true, it allows the users to invert the operation for
626 // free when it is profitable to do so.
627 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
628   SDValue N0, N1, N2;
629   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
630     return true;
631   return false;
632 }
633
634 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
635 /// elements are all the same constant or undefined.
636 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
637   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
638   if (!C)
639     return false;
640
641   APInt SplatUndef;
642   unsigned SplatBitSize;
643   bool HasAnyUndefs;
644   EVT EltVT = N->getValueType(0).getVectorElementType();
645   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
646                              HasAnyUndefs) &&
647           EltVT.getSizeInBits() >= SplatBitSize);
648 }
649
650 // \brief Returns the SDNode if it is a constant BuildVector or constant.
651 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
652   if (isa<ConstantSDNode>(N))
653     return N.getNode();
654   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
655   if(BV && BV->isConstant())
656     return BV;
657   return nullptr;
658 }
659
660 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
661 // int.
662 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
663   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
664     return CN;
665
666   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
667     BitVector UndefElements;
668     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
669
670     // BuildVectors can truncate their operands. Ignore that case here.
671     // FIXME: We blindly ignore splats which include undef which is overly
672     // pessimistic.
673     if (CN && UndefElements.none() &&
674         CN->getValueType(0) == N.getValueType().getScalarType())
675       return CN;
676   }
677
678   return nullptr;
679 }
680
681 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
682                                     SDValue N0, SDValue N1) {
683   EVT VT = N0.getValueType();
684   if (N0.getOpcode() == Opc) {
685     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
686       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
687         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
688         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
689         if (!OpNode.getNode())
690           return SDValue();
691         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
692       }
693       if (N0.hasOneUse()) {
694         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
695         // use
696         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
697         if (!OpNode.getNode())
698           return SDValue();
699         AddToWorklist(OpNode.getNode());
700         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
701       }
702     }
703   }
704
705   if (N1.getOpcode() == Opc) {
706     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
707       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
708         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
709         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
710         if (!OpNode.getNode())
711           return SDValue();
712         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
713       }
714       if (N1.hasOneUse()) {
715         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
716         // use
717         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
718         if (!OpNode.getNode())
719           return SDValue();
720         AddToWorklist(OpNode.getNode());
721         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
722       }
723     }
724   }
725
726   return SDValue();
727 }
728
729 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
730                                bool AddTo) {
731   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
732   ++NodesCombined;
733   DEBUG(dbgs() << "\nReplacing.1 ";
734         N->dump(&DAG);
735         dbgs() << "\nWith: ";
736         To[0].getNode()->dump(&DAG);
737         dbgs() << " and " << NumTo-1 << " other values\n";
738         for (unsigned i = 0, e = NumTo; i != e; ++i)
739           assert((!To[i].getNode() ||
740                   N->getValueType(i) == To[i].getValueType()) &&
741                  "Cannot combine value to value of different type!"));
742   WorklistRemover DeadNodes(*this);
743   DAG.ReplaceAllUsesWith(N, To);
744   if (AddTo) {
745     // Push the new nodes and any users onto the worklist
746     for (unsigned i = 0, e = NumTo; i != e; ++i) {
747       if (To[i].getNode()) {
748         AddToWorklist(To[i].getNode());
749         AddUsersToWorklist(To[i].getNode());
750       }
751     }
752   }
753
754   // Finally, if the node is now dead, remove it from the graph.  The node
755   // may not be dead if the replacement process recursively simplified to
756   // something else needing this node.
757   if (N->use_empty()) {
758     // Nodes can be reintroduced into the worklist.  Make sure we do not
759     // process a node that has been replaced.
760     removeFromWorklist(N);
761
762     // Finally, since the node is now dead, remove it from the graph.
763     DAG.DeleteNode(N);
764   }
765   return SDValue(N, 0);
766 }
767
768 void DAGCombiner::
769 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
770   // Replace all uses.  If any nodes become isomorphic to other nodes and
771   // are deleted, make sure to remove them from our worklist.
772   WorklistRemover DeadNodes(*this);
773   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
774
775   // Push the new node and any (possibly new) users onto the worklist.
776   AddToWorklist(TLO.New.getNode());
777   AddUsersToWorklist(TLO.New.getNode());
778
779   // Finally, if the node is now dead, remove it from the graph.  The node
780   // may not be dead if the replacement process recursively simplified to
781   // something else needing this node.
782   if (TLO.Old.getNode()->use_empty()) {
783     removeFromWorklist(TLO.Old.getNode());
784
785     // If the operands of this node are only used by the node, they will now
786     // be dead.  Make sure to visit them first to delete dead nodes early.
787     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
788       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
789         AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
790
791     DAG.DeleteNode(TLO.Old.getNode());
792   }
793 }
794
795 /// SimplifyDemandedBits - Check the specified integer node value to see if
796 /// it can be simplified or if things it uses can be simplified by bit
797 /// propagation.  If so, return true.
798 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
799   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
800   APInt KnownZero, KnownOne;
801   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
802     return false;
803
804   // Revisit the node.
805   AddToWorklist(Op.getNode());
806
807   // Replace the old value with the new one.
808   ++NodesCombined;
809   DEBUG(dbgs() << "\nReplacing.2 ";
810         TLO.Old.getNode()->dump(&DAG);
811         dbgs() << "\nWith: ";
812         TLO.New.getNode()->dump(&DAG);
813         dbgs() << '\n');
814
815   CommitTargetLoweringOpt(TLO);
816   return true;
817 }
818
819 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
820   SDLoc dl(Load);
821   EVT VT = Load->getValueType(0);
822   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
823
824   DEBUG(dbgs() << "\nReplacing.9 ";
825         Load->dump(&DAG);
826         dbgs() << "\nWith: ";
827         Trunc.getNode()->dump(&DAG);
828         dbgs() << '\n');
829   WorklistRemover DeadNodes(*this);
830   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
831   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
832   removeFromWorklist(Load);
833   DAG.DeleteNode(Load);
834   AddToWorklist(Trunc.getNode());
835 }
836
837 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
838   Replace = false;
839   SDLoc dl(Op);
840   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
841     EVT MemVT = LD->getMemoryVT();
842     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
843       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
844                                                   : ISD::EXTLOAD)
845       : LD->getExtensionType();
846     Replace = true;
847     return DAG.getExtLoad(ExtType, dl, PVT,
848                           LD->getChain(), LD->getBasePtr(),
849                           MemVT, LD->getMemOperand());
850   }
851
852   unsigned Opc = Op.getOpcode();
853   switch (Opc) {
854   default: break;
855   case ISD::AssertSext:
856     return DAG.getNode(ISD::AssertSext, dl, PVT,
857                        SExtPromoteOperand(Op.getOperand(0), PVT),
858                        Op.getOperand(1));
859   case ISD::AssertZext:
860     return DAG.getNode(ISD::AssertZext, dl, PVT,
861                        ZExtPromoteOperand(Op.getOperand(0), PVT),
862                        Op.getOperand(1));
863   case ISD::Constant: {
864     unsigned ExtOpc =
865       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
866     return DAG.getNode(ExtOpc, dl, PVT, Op);
867   }
868   }
869
870   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
871     return SDValue();
872   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
873 }
874
875 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
876   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
877     return SDValue();
878   EVT OldVT = Op.getValueType();
879   SDLoc dl(Op);
880   bool Replace = false;
881   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
882   if (!NewOp.getNode())
883     return SDValue();
884   AddToWorklist(NewOp.getNode());
885
886   if (Replace)
887     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
888   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
889                      DAG.getValueType(OldVT));
890 }
891
892 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
893   EVT OldVT = Op.getValueType();
894   SDLoc dl(Op);
895   bool Replace = false;
896   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
897   if (!NewOp.getNode())
898     return SDValue();
899   AddToWorklist(NewOp.getNode());
900
901   if (Replace)
902     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
903   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
904 }
905
906 /// PromoteIntBinOp - Promote the specified integer binary operation if the
907 /// target indicates it is beneficial. e.g. On x86, it's usually better to
908 /// promote i16 operations to i32 since i16 instructions are longer.
909 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
910   if (!LegalOperations)
911     return SDValue();
912
913   EVT VT = Op.getValueType();
914   if (VT.isVector() || !VT.isInteger())
915     return SDValue();
916
917   // If operation type is 'undesirable', e.g. i16 on x86, consider
918   // promoting it.
919   unsigned Opc = Op.getOpcode();
920   if (TLI.isTypeDesirableForOp(Opc, VT))
921     return SDValue();
922
923   EVT PVT = VT;
924   // Consult target whether it is a good idea to promote this operation and
925   // what's the right type to promote it to.
926   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
927     assert(PVT != VT && "Don't know what type to promote to!");
928
929     bool Replace0 = false;
930     SDValue N0 = Op.getOperand(0);
931     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
932     if (!NN0.getNode())
933       return SDValue();
934
935     bool Replace1 = false;
936     SDValue N1 = Op.getOperand(1);
937     SDValue NN1;
938     if (N0 == N1)
939       NN1 = NN0;
940     else {
941       NN1 = PromoteOperand(N1, PVT, Replace1);
942       if (!NN1.getNode())
943         return SDValue();
944     }
945
946     AddToWorklist(NN0.getNode());
947     if (NN1.getNode())
948       AddToWorklist(NN1.getNode());
949
950     if (Replace0)
951       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
952     if (Replace1)
953       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
954
955     DEBUG(dbgs() << "\nPromoting ";
956           Op.getNode()->dump(&DAG));
957     SDLoc dl(Op);
958     return DAG.getNode(ISD::TRUNCATE, dl, VT,
959                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
960   }
961   return SDValue();
962 }
963
964 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
965 /// target indicates it is beneficial. e.g. On x86, it's usually better to
966 /// promote i16 operations to i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
968   if (!LegalOperations)
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   if (VT.isVector() || !VT.isInteger())
973     return SDValue();
974
975   // If operation type is 'undesirable', e.g. i16 on x86, consider
976   // promoting it.
977   unsigned Opc = Op.getOpcode();
978   if (TLI.isTypeDesirableForOp(Opc, VT))
979     return SDValue();
980
981   EVT PVT = VT;
982   // Consult target whether it is a good idea to promote this operation and
983   // what's the right type to promote it to.
984   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985     assert(PVT != VT && "Don't know what type to promote to!");
986
987     bool Replace = false;
988     SDValue N0 = Op.getOperand(0);
989     if (Opc == ISD::SRA)
990       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
991     else if (Opc == ISD::SRL)
992       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
993     else
994       N0 = PromoteOperand(N0, PVT, Replace);
995     if (!N0.getNode())
996       return SDValue();
997
998     AddToWorklist(N0.getNode());
999     if (Replace)
1000       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1001
1002     DEBUG(dbgs() << "\nPromoting ";
1003           Op.getNode()->dump(&DAG));
1004     SDLoc dl(Op);
1005     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1006                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1007   }
1008   return SDValue();
1009 }
1010
1011 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1012   if (!LegalOperations)
1013     return SDValue();
1014
1015   EVT VT = Op.getValueType();
1016   if (VT.isVector() || !VT.isInteger())
1017     return SDValue();
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 SDValue();
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     // fold (aext (aext x)) -> (aext x)
1031     // fold (aext (zext x)) -> (zext x)
1032     // fold (aext (sext x)) -> (sext x)
1033     DEBUG(dbgs() << "\nPromoting ";
1034           Op.getNode()->dump(&DAG));
1035     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1036   }
1037   return SDValue();
1038 }
1039
1040 bool DAGCombiner::PromoteLoad(SDValue Op) {
1041   if (!LegalOperations)
1042     return false;
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return false;
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return false;
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     SDLoc dl(Op);
1061     SDNode *N = Op.getNode();
1062     LoadSDNode *LD = cast<LoadSDNode>(N);
1063     EVT MemVT = LD->getMemoryVT();
1064     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1065       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1066                                                   : ISD::EXTLOAD)
1067       : LD->getExtensionType();
1068     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1069                                    LD->getChain(), LD->getBasePtr(),
1070                                    MemVT, LD->getMemOperand());
1071     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           N->dump(&DAG);
1075           dbgs() << "\nTo: ";
1076           Result.getNode()->dump(&DAG);
1077           dbgs() << '\n');
1078     WorklistRemover DeadNodes(*this);
1079     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1080     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1081     removeFromWorklist(N);
1082     DAG.DeleteNode(N);
1083     AddToWorklist(Result.getNode());
1084     return true;
1085   }
1086   return false;
1087 }
1088
1089 /// \brief Recursively delete a node which has no uses and any operands for
1090 /// which it is the only use.
1091 ///
1092 /// Note that this both deletes the nodes and removes them from the worklist.
1093 /// It also adds any nodes who have had a user deleted to the worklist as they
1094 /// may now have only one use and subject to other combines.
1095 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1096   if (!N->use_empty())
1097     return false;
1098
1099   SmallSetVector<SDNode *, 16> Nodes;
1100   Nodes.insert(N);
1101   do {
1102     N = Nodes.pop_back_val();
1103     if (!N)
1104       continue;
1105
1106     if (N->use_empty()) {
1107       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1108         Nodes.insert(N->getOperand(i).getNode());
1109
1110       removeFromWorklist(N);
1111       DAG.DeleteNode(N);
1112     } else {
1113       AddToWorklist(N);
1114     }
1115   } while (!Nodes.empty());
1116   return true;
1117 }
1118
1119 //===----------------------------------------------------------------------===//
1120 //  Main DAG Combiner implementation
1121 //===----------------------------------------------------------------------===//
1122
1123 void DAGCombiner::Run(CombineLevel AtLevel) {
1124   // set the instance variables, so that the various visit routines may use it.
1125   Level = AtLevel;
1126   LegalOperations = Level >= AfterLegalizeVectorOps;
1127   LegalTypes = Level >= AfterLegalizeTypes;
1128
1129   // Add all the dag nodes to the worklist.
1130   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1131        E = DAG.allnodes_end(); I != E; ++I)
1132     AddToWorklist(I);
1133
1134   // Create a dummy node (which is not added to allnodes), that adds a reference
1135   // to the root node, preventing it from being deleted, and tracking any
1136   // changes of the root.
1137   HandleSDNode Dummy(DAG.getRoot());
1138
1139   // while the worklist isn't empty, find a node and
1140   // try and combine it.
1141   while (!WorklistMap.empty()) {
1142     SDNode *N;
1143     // The Worklist holds the SDNodes in order, but it may contain null entries.
1144     do {
1145       N = Worklist.pop_back_val();
1146     } while (!N);
1147
1148     bool GoodWorklistEntry = WorklistMap.erase(N);
1149     (void)GoodWorklistEntry;
1150     assert(GoodWorklistEntry &&
1151            "Found a worklist entry without a corresponding map entry!");
1152
1153     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1154     // N is deleted from the DAG, since they too may now be dead or may have a
1155     // reduced number of uses, allowing other xforms.
1156     if (recursivelyDeleteUnusedNodes(N))
1157       continue;
1158
1159     // Add any operands of the new node which have not yet been combined to the
1160     // worklist as well. Because the worklist uniques things already, this
1161     // won't repeatedly process the same operand.
1162     CombinedNodes.insert(N);
1163     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1164       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1165         AddToWorklist(N->getOperand(i).getNode());
1166
1167     WorklistRemover DeadNodes(*this);
1168
1169     // If this combine is running after legalizing the DAG, re-legalize any
1170     // nodes pulled off the worklist.
1171     if (Level == AfterLegalizeDAG) {
1172       SmallSetVector<SDNode *, 16> UpdatedNodes;
1173       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1174
1175       for (SDNode *LN : UpdatedNodes) {
1176         AddToWorklist(LN);
1177         AddUsersToWorklist(LN);
1178       }
1179       if (!NIsValid)
1180         continue;
1181     }
1182
1183     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1184
1185     SDValue RV = combine(N);
1186
1187     if (!RV.getNode())
1188       continue;
1189
1190     ++NodesCombined;
1191
1192     // If we get back the same node we passed in, rather than a new node or
1193     // zero, we know that the node must have defined multiple values and
1194     // CombineTo was used.  Since CombineTo takes care of the worklist
1195     // mechanics for us, we have no work to do in this case.
1196     if (RV.getNode() == N)
1197       continue;
1198
1199     assert(N->getOpcode() != ISD::DELETED_NODE &&
1200            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1201            "Node was deleted but visit returned new node!");
1202
1203     DEBUG(dbgs() << " ... into: ";
1204           RV.getNode()->dump(&DAG));
1205
1206     // Transfer debug value.
1207     DAG.TransferDbgValues(SDValue(N, 0), RV);
1208     if (N->getNumValues() == RV.getNode()->getNumValues())
1209       DAG.ReplaceAllUsesWith(N, RV.getNode());
1210     else {
1211       assert(N->getValueType(0) == RV.getValueType() &&
1212              N->getNumValues() == 1 && "Type mismatch");
1213       SDValue OpV = RV;
1214       DAG.ReplaceAllUsesWith(N, &OpV);
1215     }
1216
1217     // Push the new node and any users onto the worklist
1218     AddToWorklist(RV.getNode());
1219     AddUsersToWorklist(RV.getNode());
1220
1221     // Finally, if the node is now dead, remove it from the graph.  The node
1222     // may not be dead if the replacement process recursively simplified to
1223     // something else needing this node. This will also take care of adding any
1224     // operands which have lost a user to the worklist.
1225     recursivelyDeleteUnusedNodes(N);
1226   }
1227
1228   // If the root changed (e.g. it was a dead load, update the root).
1229   DAG.setRoot(Dummy.getValue());
1230   DAG.RemoveDeadNodes();
1231 }
1232
1233 SDValue DAGCombiner::visit(SDNode *N) {
1234   switch (N->getOpcode()) {
1235   default: break;
1236   case ISD::TokenFactor:        return visitTokenFactor(N);
1237   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1238   case ISD::ADD:                return visitADD(N);
1239   case ISD::SUB:                return visitSUB(N);
1240   case ISD::ADDC:               return visitADDC(N);
1241   case ISD::SUBC:               return visitSUBC(N);
1242   case ISD::ADDE:               return visitADDE(N);
1243   case ISD::SUBE:               return visitSUBE(N);
1244   case ISD::MUL:                return visitMUL(N);
1245   case ISD::SDIV:               return visitSDIV(N);
1246   case ISD::UDIV:               return visitUDIV(N);
1247   case ISD::SREM:               return visitSREM(N);
1248   case ISD::UREM:               return visitUREM(N);
1249   case ISD::MULHU:              return visitMULHU(N);
1250   case ISD::MULHS:              return visitMULHS(N);
1251   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1252   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1253   case ISD::SMULO:              return visitSMULO(N);
1254   case ISD::UMULO:              return visitUMULO(N);
1255   case ISD::SDIVREM:            return visitSDIVREM(N);
1256   case ISD::UDIVREM:            return visitUDIVREM(N);
1257   case ISD::AND:                return visitAND(N);
1258   case ISD::OR:                 return visitOR(N);
1259   case ISD::XOR:                return visitXOR(N);
1260   case ISD::SHL:                return visitSHL(N);
1261   case ISD::SRA:                return visitSRA(N);
1262   case ISD::SRL:                return visitSRL(N);
1263   case ISD::ROTR:
1264   case ISD::ROTL:               return visitRotate(N);
1265   case ISD::CTLZ:               return visitCTLZ(N);
1266   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1267   case ISD::CTTZ:               return visitCTTZ(N);
1268   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1269   case ISD::CTPOP:              return visitCTPOP(N);
1270   case ISD::SELECT:             return visitSELECT(N);
1271   case ISD::VSELECT:            return visitVSELECT(N);
1272   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1273   case ISD::SETCC:              return visitSETCC(N);
1274   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1275   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1276   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1277   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1278   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1279   case ISD::BITCAST:            return visitBITCAST(N);
1280   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1281   case ISD::FADD:               return visitFADD(N);
1282   case ISD::FSUB:               return visitFSUB(N);
1283   case ISD::FMUL:               return visitFMUL(N);
1284   case ISD::FMA:                return visitFMA(N);
1285   case ISD::FDIV:               return visitFDIV(N);
1286   case ISD::FREM:               return visitFREM(N);
1287   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1288   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1289   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1290   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1291   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1292   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1293   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1294   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1295   case ISD::FNEG:               return visitFNEG(N);
1296   case ISD::FABS:               return visitFABS(N);
1297   case ISD::FFLOOR:             return visitFFLOOR(N);
1298   case ISD::FCEIL:              return visitFCEIL(N);
1299   case ISD::FTRUNC:             return visitFTRUNC(N);
1300   case ISD::BRCOND:             return visitBRCOND(N);
1301   case ISD::BR_CC:              return visitBR_CC(N);
1302   case ISD::LOAD:               return visitLOAD(N);
1303   case ISD::STORE:              return visitSTORE(N);
1304   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1305   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1306   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1307   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1308   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1309   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1310   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1311   }
1312   return SDValue();
1313 }
1314
1315 SDValue DAGCombiner::combine(SDNode *N) {
1316   SDValue RV = visit(N);
1317
1318   // If nothing happened, try a target-specific DAG combine.
1319   if (!RV.getNode()) {
1320     assert(N->getOpcode() != ISD::DELETED_NODE &&
1321            "Node was deleted but visit returned NULL!");
1322
1323     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1324         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1325
1326       // Expose the DAG combiner to the target combiner impls.
1327       TargetLowering::DAGCombinerInfo
1328         DagCombineInfo(DAG, Level, false, this);
1329
1330       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1331     }
1332   }
1333
1334   // If nothing happened still, try promoting the operation.
1335   if (!RV.getNode()) {
1336     switch (N->getOpcode()) {
1337     default: break;
1338     case ISD::ADD:
1339     case ISD::SUB:
1340     case ISD::MUL:
1341     case ISD::AND:
1342     case ISD::OR:
1343     case ISD::XOR:
1344       RV = PromoteIntBinOp(SDValue(N, 0));
1345       break;
1346     case ISD::SHL:
1347     case ISD::SRA:
1348     case ISD::SRL:
1349       RV = PromoteIntShiftOp(SDValue(N, 0));
1350       break;
1351     case ISD::SIGN_EXTEND:
1352     case ISD::ZERO_EXTEND:
1353     case ISD::ANY_EXTEND:
1354       RV = PromoteExtend(SDValue(N, 0));
1355       break;
1356     case ISD::LOAD:
1357       if (PromoteLoad(SDValue(N, 0)))
1358         RV = SDValue(N, 0);
1359       break;
1360     }
1361   }
1362
1363   // If N is a commutative binary node, try commuting it to enable more
1364   // sdisel CSE.
1365   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1366       N->getNumValues() == 1) {
1367     SDValue N0 = N->getOperand(0);
1368     SDValue N1 = N->getOperand(1);
1369
1370     // Constant operands are canonicalized to RHS.
1371     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1372       SDValue Ops[] = {N1, N0};
1373       SDNode *CSENode;
1374       if (const BinaryWithFlagsSDNode *BinNode =
1375               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1376         CSENode = DAG.getNodeIfExists(
1377             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1378             BinNode->hasNoSignedWrap(), BinNode->isExact());
1379       } else {
1380         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1381       }
1382       if (CSENode)
1383         return SDValue(CSENode, 0);
1384     }
1385   }
1386
1387   return RV;
1388 }
1389
1390 /// getInputChainForNode - Given a node, return its input chain if it has one,
1391 /// otherwise return a null sd operand.
1392 static SDValue getInputChainForNode(SDNode *N) {
1393   if (unsigned NumOps = N->getNumOperands()) {
1394     if (N->getOperand(0).getValueType() == MVT::Other)
1395       return N->getOperand(0);
1396     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1397       return N->getOperand(NumOps-1);
1398     for (unsigned i = 1; i < NumOps-1; ++i)
1399       if (N->getOperand(i).getValueType() == MVT::Other)
1400         return N->getOperand(i);
1401   }
1402   return SDValue();
1403 }
1404
1405 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1406   // If N has two operands, where one has an input chain equal to the other,
1407   // the 'other' chain is redundant.
1408   if (N->getNumOperands() == 2) {
1409     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1410       return N->getOperand(0);
1411     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1412       return N->getOperand(1);
1413   }
1414
1415   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1416   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1417   SmallPtrSet<SDNode*, 16> SeenOps;
1418   bool Changed = false;             // If we should replace this token factor.
1419
1420   // Start out with this token factor.
1421   TFs.push_back(N);
1422
1423   // Iterate through token factors.  The TFs grows when new token factors are
1424   // encountered.
1425   for (unsigned i = 0; i < TFs.size(); ++i) {
1426     SDNode *TF = TFs[i];
1427
1428     // Check each of the operands.
1429     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1430       SDValue Op = TF->getOperand(i);
1431
1432       switch (Op.getOpcode()) {
1433       case ISD::EntryToken:
1434         // Entry tokens don't need to be added to the list. They are
1435         // rededundant.
1436         Changed = true;
1437         break;
1438
1439       case ISD::TokenFactor:
1440         if (Op.hasOneUse() &&
1441             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1442           // Queue up for processing.
1443           TFs.push_back(Op.getNode());
1444           // Clean up in case the token factor is removed.
1445           AddToWorklist(Op.getNode());
1446           Changed = true;
1447           break;
1448         }
1449         // Fall thru
1450
1451       default:
1452         // Only add if it isn't already in the list.
1453         if (SeenOps.insert(Op.getNode()))
1454           Ops.push_back(Op);
1455         else
1456           Changed = true;
1457         break;
1458       }
1459     }
1460   }
1461
1462   SDValue Result;
1463
1464   // If we've change things around then replace token factor.
1465   if (Changed) {
1466     if (Ops.empty()) {
1467       // The entry token is the only possible outcome.
1468       Result = DAG.getEntryNode();
1469     } else {
1470       // New and improved token factor.
1471       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1472     }
1473
1474     // Don't add users to work list.
1475     return CombineTo(N, Result, false);
1476   }
1477
1478   return Result;
1479 }
1480
1481 /// MERGE_VALUES can always be eliminated.
1482 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1483   WorklistRemover DeadNodes(*this);
1484   // Replacing results may cause a different MERGE_VALUES to suddenly
1485   // be CSE'd with N, and carry its uses with it. Iterate until no
1486   // uses remain, to ensure that the node can be safely deleted.
1487   // First add the users of this node to the work list so that they
1488   // can be tried again once they have new operands.
1489   AddUsersToWorklist(N);
1490   do {
1491     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1492       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1493   } while (!N->use_empty());
1494   removeFromWorklist(N);
1495   DAG.DeleteNode(N);
1496   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1497 }
1498
1499 static
1500 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1501                               SelectionDAG &DAG) {
1502   EVT VT = N0.getValueType();
1503   SDValue N00 = N0.getOperand(0);
1504   SDValue N01 = N0.getOperand(1);
1505   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1506
1507   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1508       isa<ConstantSDNode>(N00.getOperand(1))) {
1509     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1510     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1511                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1512                                  N00.getOperand(0), N01),
1513                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1514                                  N00.getOperand(1), N01));
1515     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1516   }
1517
1518   return SDValue();
1519 }
1520
1521 SDValue DAGCombiner::visitADD(SDNode *N) {
1522   SDValue N0 = N->getOperand(0);
1523   SDValue N1 = N->getOperand(1);
1524   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1525   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1526   EVT VT = N0.getValueType();
1527
1528   // fold vector ops
1529   if (VT.isVector()) {
1530     SDValue FoldedVOp = SimplifyVBinOp(N);
1531     if (FoldedVOp.getNode()) return FoldedVOp;
1532
1533     // fold (add x, 0) -> x, vector edition
1534     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1535       return N0;
1536     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1537       return N1;
1538   }
1539
1540   // fold (add x, undef) -> undef
1541   if (N0.getOpcode() == ISD::UNDEF)
1542     return N0;
1543   if (N1.getOpcode() == ISD::UNDEF)
1544     return N1;
1545   // fold (add c1, c2) -> c1+c2
1546   if (N0C && N1C)
1547     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1548   // canonicalize constant to RHS
1549   if (N0C && !N1C)
1550     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1551   // fold (add x, 0) -> x
1552   if (N1C && N1C->isNullValue())
1553     return N0;
1554   // fold (add Sym, c) -> Sym+c
1555   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1556     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1557         GA->getOpcode() == ISD::GlobalAddress)
1558       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1559                                   GA->getOffset() +
1560                                     (uint64_t)N1C->getSExtValue());
1561   // fold ((c1-A)+c2) -> (c1+c2)-A
1562   if (N1C && N0.getOpcode() == ISD::SUB)
1563     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1564       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1565                          DAG.getConstant(N1C->getAPIntValue()+
1566                                          N0C->getAPIntValue(), VT),
1567                          N0.getOperand(1));
1568   // reassociate add
1569   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1570   if (RADD.getNode())
1571     return RADD;
1572   // fold ((0-A) + B) -> B-A
1573   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1574       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1575     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1576   // fold (A + (0-B)) -> A-B
1577   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1578       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1579     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1580   // fold (A+(B-A)) -> B
1581   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1582     return N1.getOperand(0);
1583   // fold ((B-A)+A) -> B
1584   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1585     return N0.getOperand(0);
1586   // fold (A+(B-(A+C))) to (B-C)
1587   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1588       N0 == N1.getOperand(1).getOperand(0))
1589     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1590                        N1.getOperand(1).getOperand(1));
1591   // fold (A+(B-(C+A))) to (B-C)
1592   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1593       N0 == N1.getOperand(1).getOperand(1))
1594     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1595                        N1.getOperand(1).getOperand(0));
1596   // fold (A+((B-A)+or-C)) to (B+or-C)
1597   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1598       N1.getOperand(0).getOpcode() == ISD::SUB &&
1599       N0 == N1.getOperand(0).getOperand(1))
1600     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1601                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1602
1603   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1604   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1605     SDValue N00 = N0.getOperand(0);
1606     SDValue N01 = N0.getOperand(1);
1607     SDValue N10 = N1.getOperand(0);
1608     SDValue N11 = N1.getOperand(1);
1609
1610     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1611       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1612                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1613                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1614   }
1615
1616   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1617     return SDValue(N, 0);
1618
1619   // fold (a+b) -> (a|b) iff a and b share no bits.
1620   if (VT.isInteger() && !VT.isVector()) {
1621     APInt LHSZero, LHSOne;
1622     APInt RHSZero, RHSOne;
1623     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1624
1625     if (LHSZero.getBoolValue()) {
1626       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1627
1628       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1629       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1630       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1631         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1632           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1633       }
1634     }
1635   }
1636
1637   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1638   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1639     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1640     if (Result.getNode()) return Result;
1641   }
1642   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1643     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1644     if (Result.getNode()) return Result;
1645   }
1646
1647   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1648   if (N1.getOpcode() == ISD::SHL &&
1649       N1.getOperand(0).getOpcode() == ISD::SUB)
1650     if (ConstantSDNode *C =
1651           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1652       if (C->getAPIntValue() == 0)
1653         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1654                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1655                                        N1.getOperand(0).getOperand(1),
1656                                        N1.getOperand(1)));
1657   if (N0.getOpcode() == ISD::SHL &&
1658       N0.getOperand(0).getOpcode() == ISD::SUB)
1659     if (ConstantSDNode *C =
1660           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1661       if (C->getAPIntValue() == 0)
1662         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1663                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1664                                        N0.getOperand(0).getOperand(1),
1665                                        N0.getOperand(1)));
1666
1667   if (N1.getOpcode() == ISD::AND) {
1668     SDValue AndOp0 = N1.getOperand(0);
1669     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1670     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1671     unsigned DestBits = VT.getScalarType().getSizeInBits();
1672
1673     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1674     // and similar xforms where the inner op is either ~0 or 0.
1675     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1676       SDLoc DL(N);
1677       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1678     }
1679   }
1680
1681   // add (sext i1), X -> sub X, (zext i1)
1682   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1683       N0.getOperand(0).getValueType() == MVT::i1 &&
1684       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1685     SDLoc DL(N);
1686     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1687     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1688   }
1689
1690   return SDValue();
1691 }
1692
1693 SDValue DAGCombiner::visitADDC(SDNode *N) {
1694   SDValue N0 = N->getOperand(0);
1695   SDValue N1 = N->getOperand(1);
1696   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1697   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1698   EVT VT = N0.getValueType();
1699
1700   // If the flag result is dead, turn this into an ADD.
1701   if (!N->hasAnyUseOfValue(1))
1702     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1703                      DAG.getNode(ISD::CARRY_FALSE,
1704                                  SDLoc(N), MVT::Glue));
1705
1706   // canonicalize constant to RHS.
1707   if (N0C && !N1C)
1708     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1709
1710   // fold (addc x, 0) -> x + no carry out
1711   if (N1C && N1C->isNullValue())
1712     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1713                                         SDLoc(N), MVT::Glue));
1714
1715   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1716   APInt LHSZero, LHSOne;
1717   APInt RHSZero, RHSOne;
1718   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1719
1720   if (LHSZero.getBoolValue()) {
1721     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1722
1723     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1724     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1725     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1726       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1727                        DAG.getNode(ISD::CARRY_FALSE,
1728                                    SDLoc(N), MVT::Glue));
1729   }
1730
1731   return SDValue();
1732 }
1733
1734 SDValue DAGCombiner::visitADDE(SDNode *N) {
1735   SDValue N0 = N->getOperand(0);
1736   SDValue N1 = N->getOperand(1);
1737   SDValue CarryIn = N->getOperand(2);
1738   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1739   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1740
1741   // canonicalize constant to RHS
1742   if (N0C && !N1C)
1743     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1744                        N1, N0, CarryIn);
1745
1746   // fold (adde x, y, false) -> (addc x, y)
1747   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1748     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1749
1750   return SDValue();
1751 }
1752
1753 // Since it may not be valid to emit a fold to zero for vector initializers
1754 // check if we can before folding.
1755 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1756                              SelectionDAG &DAG,
1757                              bool LegalOperations, bool LegalTypes) {
1758   if (!VT.isVector())
1759     return DAG.getConstant(0, VT);
1760   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1761     return DAG.getConstant(0, VT);
1762   return SDValue();
1763 }
1764
1765 SDValue DAGCombiner::visitSUB(SDNode *N) {
1766   SDValue N0 = N->getOperand(0);
1767   SDValue N1 = N->getOperand(1);
1768   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1769   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1770   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1771     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1772   EVT VT = N0.getValueType();
1773
1774   // fold vector ops
1775   if (VT.isVector()) {
1776     SDValue FoldedVOp = SimplifyVBinOp(N);
1777     if (FoldedVOp.getNode()) return FoldedVOp;
1778
1779     // fold (sub x, 0) -> x, vector edition
1780     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1781       return N0;
1782   }
1783
1784   // fold (sub x, x) -> 0
1785   // FIXME: Refactor this and xor and other similar operations together.
1786   if (N0 == N1)
1787     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1788   // fold (sub c1, c2) -> c1-c2
1789   if (N0C && N1C)
1790     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1791   // fold (sub x, c) -> (add x, -c)
1792   if (N1C)
1793     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1794                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1795   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1796   if (N0C && N0C->isAllOnesValue())
1797     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1798   // fold A-(A-B) -> B
1799   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1800     return N1.getOperand(1);
1801   // fold (A+B)-A -> B
1802   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1803     return N0.getOperand(1);
1804   // fold (A+B)-B -> A
1805   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1806     return N0.getOperand(0);
1807   // fold C2-(A+C1) -> (C2-C1)-A
1808   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1809     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1810                                    VT);
1811     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1812                        N1.getOperand(0));
1813   }
1814   // fold ((A+(B+or-C))-B) -> A+or-C
1815   if (N0.getOpcode() == ISD::ADD &&
1816       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1817        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1818       N0.getOperand(1).getOperand(0) == N1)
1819     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1820                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1821   // fold ((A+(C+B))-B) -> A+C
1822   if (N0.getOpcode() == ISD::ADD &&
1823       N0.getOperand(1).getOpcode() == ISD::ADD &&
1824       N0.getOperand(1).getOperand(1) == N1)
1825     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1826                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1827   // fold ((A-(B-C))-C) -> A-B
1828   if (N0.getOpcode() == ISD::SUB &&
1829       N0.getOperand(1).getOpcode() == ISD::SUB &&
1830       N0.getOperand(1).getOperand(1) == N1)
1831     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1832                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1833
1834   // If either operand of a sub is undef, the result is undef
1835   if (N0.getOpcode() == ISD::UNDEF)
1836     return N0;
1837   if (N1.getOpcode() == ISD::UNDEF)
1838     return N1;
1839
1840   // If the relocation model supports it, consider symbol offsets.
1841   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1842     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1843       // fold (sub Sym, c) -> Sym-c
1844       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1845         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1846                                     GA->getOffset() -
1847                                       (uint64_t)N1C->getSExtValue());
1848       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1849       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1850         if (GA->getGlobal() == GB->getGlobal())
1851           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1852                                  VT);
1853     }
1854
1855   return SDValue();
1856 }
1857
1858 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1859   SDValue N0 = N->getOperand(0);
1860   SDValue N1 = N->getOperand(1);
1861   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1862   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1863   EVT VT = N0.getValueType();
1864
1865   // If the flag result is dead, turn this into an SUB.
1866   if (!N->hasAnyUseOfValue(1))
1867     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1868                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1869                                  MVT::Glue));
1870
1871   // fold (subc x, x) -> 0 + no borrow
1872   if (N0 == N1)
1873     return CombineTo(N, DAG.getConstant(0, VT),
1874                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1875                                  MVT::Glue));
1876
1877   // fold (subc x, 0) -> x + no borrow
1878   if (N1C && N1C->isNullValue())
1879     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1880                                         MVT::Glue));
1881
1882   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1883   if (N0C && N0C->isAllOnesValue())
1884     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1885                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1886                                  MVT::Glue));
1887
1888   return SDValue();
1889 }
1890
1891 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1892   SDValue N0 = N->getOperand(0);
1893   SDValue N1 = N->getOperand(1);
1894   SDValue CarryIn = N->getOperand(2);
1895
1896   // fold (sube x, y, false) -> (subc x, y)
1897   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1898     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1899
1900   return SDValue();
1901 }
1902
1903 SDValue DAGCombiner::visitMUL(SDNode *N) {
1904   SDValue N0 = N->getOperand(0);
1905   SDValue N1 = N->getOperand(1);
1906   EVT VT = N0.getValueType();
1907
1908   // fold (mul x, undef) -> 0
1909   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1910     return DAG.getConstant(0, VT);
1911
1912   bool N0IsConst = false;
1913   bool N1IsConst = false;
1914   APInt ConstValue0, ConstValue1;
1915   // fold vector ops
1916   if (VT.isVector()) {
1917     SDValue FoldedVOp = SimplifyVBinOp(N);
1918     if (FoldedVOp.getNode()) return FoldedVOp;
1919
1920     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1921     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1922   } else {
1923     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1924     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1925                             : APInt();
1926     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1927     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1928                             : APInt();
1929   }
1930
1931   // fold (mul c1, c2) -> c1*c2
1932   if (N0IsConst && N1IsConst)
1933     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1934
1935   // canonicalize constant to RHS
1936   if (N0IsConst && !N1IsConst)
1937     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1938   // fold (mul x, 0) -> 0
1939   if (N1IsConst && ConstValue1 == 0)
1940     return N1;
1941   // We require a splat of the entire scalar bit width for non-contiguous
1942   // bit patterns.
1943   bool IsFullSplat =
1944     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1945   // fold (mul x, 1) -> x
1946   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1947     return N0;
1948   // fold (mul x, -1) -> 0-x
1949   if (N1IsConst && ConstValue1.isAllOnesValue())
1950     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1951                        DAG.getConstant(0, VT), N0);
1952   // fold (mul x, (1 << c)) -> x << c
1953   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1954     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1955                        DAG.getConstant(ConstValue1.logBase2(),
1956                                        getShiftAmountTy(N0.getValueType())));
1957   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1958   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1959     unsigned Log2Val = (-ConstValue1).logBase2();
1960     // FIXME: If the input is something that is easily negated (e.g. a
1961     // single-use add), we should put the negate there.
1962     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1963                        DAG.getConstant(0, VT),
1964                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1965                             DAG.getConstant(Log2Val,
1966                                       getShiftAmountTy(N0.getValueType()))));
1967   }
1968
1969   APInt Val;
1970   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1971   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1972       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1973                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1974     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1975                              N1, N0.getOperand(1));
1976     AddToWorklist(C3.getNode());
1977     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1978                        N0.getOperand(0), C3);
1979   }
1980
1981   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1982   // use.
1983   {
1984     SDValue Sh(nullptr,0), Y(nullptr,0);
1985     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1986     if (N0.getOpcode() == ISD::SHL &&
1987         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1988                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1989         N0.getNode()->hasOneUse()) {
1990       Sh = N0; Y = N1;
1991     } else if (N1.getOpcode() == ISD::SHL &&
1992                isa<ConstantSDNode>(N1.getOperand(1)) &&
1993                N1.getNode()->hasOneUse()) {
1994       Sh = N1; Y = N0;
1995     }
1996
1997     if (Sh.getNode()) {
1998       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1999                                 Sh.getOperand(0), Y);
2000       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2001                          Mul, Sh.getOperand(1));
2002     }
2003   }
2004
2005   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2006   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2007       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2008                      isa<ConstantSDNode>(N0.getOperand(1))))
2009     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2010                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2011                                    N0.getOperand(0), N1),
2012                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2013                                    N0.getOperand(1), N1));
2014
2015   // reassociate mul
2016   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2017   if (RMUL.getNode())
2018     return RMUL;
2019
2020   return SDValue();
2021 }
2022
2023 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2024   SDValue N0 = N->getOperand(0);
2025   SDValue N1 = N->getOperand(1);
2026   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2027   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2028   EVT VT = N->getValueType(0);
2029
2030   // fold vector ops
2031   if (VT.isVector()) {
2032     SDValue FoldedVOp = SimplifyVBinOp(N);
2033     if (FoldedVOp.getNode()) return FoldedVOp;
2034   }
2035
2036   // fold (sdiv c1, c2) -> c1/c2
2037   if (N0C && N1C && !N1C->isNullValue())
2038     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2039   // fold (sdiv X, 1) -> X
2040   if (N1C && N1C->getAPIntValue() == 1LL)
2041     return N0;
2042   // fold (sdiv X, -1) -> 0-X
2043   if (N1C && N1C->isAllOnesValue())
2044     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2045                        DAG.getConstant(0, VT), N0);
2046   // If we know the sign bits of both operands are zero, strength reduce to a
2047   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2048   if (!VT.isVector()) {
2049     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2050       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2051                          N0, N1);
2052   }
2053
2054   // fold (sdiv X, pow2) -> simple ops after legalize
2055   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2056                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2057     // If dividing by powers of two is cheap, then don't perform the following
2058     // fold.
2059     if (TLI.isPow2DivCheap())
2060       return SDValue();
2061
2062     // Target-specific implementation of sdiv x, pow2.
2063     SDValue Res = BuildSDIVPow2(N);
2064     if (Res.getNode())
2065       return Res;
2066
2067     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2068
2069     // Splat the sign bit into the register
2070     SDValue SGN =
2071         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2072                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2073                                     getShiftAmountTy(N0.getValueType())));
2074     AddToWorklist(SGN.getNode());
2075
2076     // Add (N0 < 0) ? abs2 - 1 : 0;
2077     SDValue SRL =
2078         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2079                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2080                                     getShiftAmountTy(SGN.getValueType())));
2081     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2082     AddToWorklist(SRL.getNode());
2083     AddToWorklist(ADD.getNode());    // Divide by pow2
2084     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2085                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2086
2087     // If we're dividing by a positive value, we're done.  Otherwise, we must
2088     // negate the result.
2089     if (N1C->getAPIntValue().isNonNegative())
2090       return SRA;
2091
2092     AddToWorklist(SRA.getNode());
2093     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2094   }
2095
2096   // if integer divide is expensive and we satisfy the requirements, emit an
2097   // alternate sequence.
2098   if (N1C && !TLI.isIntDivCheap()) {
2099     SDValue Op = BuildSDIV(N);
2100     if (Op.getNode()) return Op;
2101   }
2102
2103   // undef / X -> 0
2104   if (N0.getOpcode() == ISD::UNDEF)
2105     return DAG.getConstant(0, VT);
2106   // X / undef -> undef
2107   if (N1.getOpcode() == ISD::UNDEF)
2108     return N1;
2109
2110   return SDValue();
2111 }
2112
2113 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2114   SDValue N0 = N->getOperand(0);
2115   SDValue N1 = N->getOperand(1);
2116   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2117   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2118   EVT VT = N->getValueType(0);
2119
2120   // fold vector ops
2121   if (VT.isVector()) {
2122     SDValue FoldedVOp = SimplifyVBinOp(N);
2123     if (FoldedVOp.getNode()) return FoldedVOp;
2124   }
2125
2126   // fold (udiv c1, c2) -> c1/c2
2127   if (N0C && N1C && !N1C->isNullValue())
2128     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2129   // fold (udiv x, (1 << c)) -> x >>u c
2130   if (N1C && N1C->getAPIntValue().isPowerOf2())
2131     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2132                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2133                                        getShiftAmountTy(N0.getValueType())));
2134   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2135   if (N1.getOpcode() == ISD::SHL) {
2136     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2137       if (SHC->getAPIntValue().isPowerOf2()) {
2138         EVT ADDVT = N1.getOperand(1).getValueType();
2139         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2140                                   N1.getOperand(1),
2141                                   DAG.getConstant(SHC->getAPIntValue()
2142                                                                   .logBase2(),
2143                                                   ADDVT));
2144         AddToWorklist(Add.getNode());
2145         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2146       }
2147     }
2148   }
2149   // fold (udiv x, c) -> alternate
2150   if (N1C && !TLI.isIntDivCheap()) {
2151     SDValue Op = BuildUDIV(N);
2152     if (Op.getNode()) return Op;
2153   }
2154
2155   // undef / X -> 0
2156   if (N0.getOpcode() == ISD::UNDEF)
2157     return DAG.getConstant(0, VT);
2158   // X / undef -> undef
2159   if (N1.getOpcode() == ISD::UNDEF)
2160     return N1;
2161
2162   return SDValue();
2163 }
2164
2165 SDValue DAGCombiner::visitSREM(SDNode *N) {
2166   SDValue N0 = N->getOperand(0);
2167   SDValue N1 = N->getOperand(1);
2168   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2169   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2170   EVT VT = N->getValueType(0);
2171
2172   // fold (srem c1, c2) -> c1%c2
2173   if (N0C && N1C && !N1C->isNullValue())
2174     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2175   // If we know the sign bits of both operands are zero, strength reduce to a
2176   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2177   if (!VT.isVector()) {
2178     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2179       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2180   }
2181
2182   // If X/C can be simplified by the division-by-constant logic, lower
2183   // X%C to the equivalent of X-X/C*C.
2184   if (N1C && !N1C->isNullValue()) {
2185     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2186     AddToWorklist(Div.getNode());
2187     SDValue OptimizedDiv = combine(Div.getNode());
2188     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2189       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2190                                 OptimizedDiv, N1);
2191       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2192       AddToWorklist(Mul.getNode());
2193       return Sub;
2194     }
2195   }
2196
2197   // undef % X -> 0
2198   if (N0.getOpcode() == ISD::UNDEF)
2199     return DAG.getConstant(0, VT);
2200   // X % undef -> undef
2201   if (N1.getOpcode() == ISD::UNDEF)
2202     return N1;
2203
2204   return SDValue();
2205 }
2206
2207 SDValue DAGCombiner::visitUREM(SDNode *N) {
2208   SDValue N0 = N->getOperand(0);
2209   SDValue N1 = N->getOperand(1);
2210   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2211   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2212   EVT VT = N->getValueType(0);
2213
2214   // fold (urem c1, c2) -> c1%c2
2215   if (N0C && N1C && !N1C->isNullValue())
2216     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2217   // fold (urem x, pow2) -> (and x, pow2-1)
2218   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2219     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2220                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2221   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2222   if (N1.getOpcode() == ISD::SHL) {
2223     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2224       if (SHC->getAPIntValue().isPowerOf2()) {
2225         SDValue Add =
2226           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2227                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2228                                  VT));
2229         AddToWorklist(Add.getNode());
2230         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2231       }
2232     }
2233   }
2234
2235   // If X/C can be simplified by the division-by-constant logic, lower
2236   // X%C to the equivalent of X-X/C*C.
2237   if (N1C && !N1C->isNullValue()) {
2238     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2239     AddToWorklist(Div.getNode());
2240     SDValue OptimizedDiv = combine(Div.getNode());
2241     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2242       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2243                                 OptimizedDiv, N1);
2244       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2245       AddToWorklist(Mul.getNode());
2246       return Sub;
2247     }
2248   }
2249
2250   // undef % X -> 0
2251   if (N0.getOpcode() == ISD::UNDEF)
2252     return DAG.getConstant(0, VT);
2253   // X % undef -> undef
2254   if (N1.getOpcode() == ISD::UNDEF)
2255     return N1;
2256
2257   return SDValue();
2258 }
2259
2260 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2261   SDValue N0 = N->getOperand(0);
2262   SDValue N1 = N->getOperand(1);
2263   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2264   EVT VT = N->getValueType(0);
2265   SDLoc DL(N);
2266
2267   // fold (mulhs x, 0) -> 0
2268   if (N1C && N1C->isNullValue())
2269     return N1;
2270   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2271   if (N1C && N1C->getAPIntValue() == 1)
2272     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2273                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2274                                        getShiftAmountTy(N0.getValueType())));
2275   // fold (mulhs x, undef) -> 0
2276   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2277     return DAG.getConstant(0, VT);
2278
2279   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2280   // plus a shift.
2281   if (VT.isSimple() && !VT.isVector()) {
2282     MVT Simple = VT.getSimpleVT();
2283     unsigned SimpleSize = Simple.getSizeInBits();
2284     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2285     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2286       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2287       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2288       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2289       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2290             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2291       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2292     }
2293   }
2294
2295   return SDValue();
2296 }
2297
2298 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2299   SDValue N0 = N->getOperand(0);
2300   SDValue N1 = N->getOperand(1);
2301   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2302   EVT VT = N->getValueType(0);
2303   SDLoc DL(N);
2304
2305   // fold (mulhu x, 0) -> 0
2306   if (N1C && N1C->isNullValue())
2307     return N1;
2308   // fold (mulhu x, 1) -> 0
2309   if (N1C && N1C->getAPIntValue() == 1)
2310     return DAG.getConstant(0, N0.getValueType());
2311   // fold (mulhu x, undef) -> 0
2312   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2313     return DAG.getConstant(0, VT);
2314
2315   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2316   // plus a shift.
2317   if (VT.isSimple() && !VT.isVector()) {
2318     MVT Simple = VT.getSimpleVT();
2319     unsigned SimpleSize = Simple.getSizeInBits();
2320     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2323       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2324       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2325       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2326             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2327       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2328     }
2329   }
2330
2331   return SDValue();
2332 }
2333
2334 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2335 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2336 /// that are being performed. Return true if a simplification was made.
2337 ///
2338 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2339                                                 unsigned HiOp) {
2340   // If the high half is not needed, just compute the low half.
2341   bool HiExists = N->hasAnyUseOfValue(1);
2342   if (!HiExists &&
2343       (!LegalOperations ||
2344        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2345     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2346                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2347     return CombineTo(N, Res, Res);
2348   }
2349
2350   // If the low half is not needed, just compute the high half.
2351   bool LoExists = N->hasAnyUseOfValue(0);
2352   if (!LoExists &&
2353       (!LegalOperations ||
2354        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2355     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2356                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2357     return CombineTo(N, Res, Res);
2358   }
2359
2360   // If both halves are used, return as it is.
2361   if (LoExists && HiExists)
2362     return SDValue();
2363
2364   // If the two computed results can be simplified separately, separate them.
2365   if (LoExists) {
2366     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2367                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2368     AddToWorklist(Lo.getNode());
2369     SDValue LoOpt = combine(Lo.getNode());
2370     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2371         (!LegalOperations ||
2372          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2373       return CombineTo(N, LoOpt, LoOpt);
2374   }
2375
2376   if (HiExists) {
2377     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2378                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2379     AddToWorklist(Hi.getNode());
2380     SDValue HiOpt = combine(Hi.getNode());
2381     if (HiOpt.getNode() && HiOpt != Hi &&
2382         (!LegalOperations ||
2383          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2384       return CombineTo(N, HiOpt, HiOpt);
2385   }
2386
2387   return SDValue();
2388 }
2389
2390 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2391   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2392   if (Res.getNode()) return Res;
2393
2394   EVT VT = N->getValueType(0);
2395   SDLoc DL(N);
2396
2397   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2398   // plus a shift.
2399   if (VT.isSimple() && !VT.isVector()) {
2400     MVT Simple = VT.getSimpleVT();
2401     unsigned SimpleSize = Simple.getSizeInBits();
2402     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2403     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2404       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2405       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2406       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2407       // Compute the high part as N1.
2408       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2409             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2410       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2411       // Compute the low part as N0.
2412       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2413       return CombineTo(N, Lo, Hi);
2414     }
2415   }
2416
2417   return SDValue();
2418 }
2419
2420 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2421   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2422   if (Res.getNode()) return Res;
2423
2424   EVT VT = N->getValueType(0);
2425   SDLoc DL(N);
2426
2427   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2428   // plus a shift.
2429   if (VT.isSimple() && !VT.isVector()) {
2430     MVT Simple = VT.getSimpleVT();
2431     unsigned SimpleSize = Simple.getSizeInBits();
2432     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2433     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2434       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2435       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2436       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2437       // Compute the high part as N1.
2438       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2439             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2440       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2441       // Compute the low part as N0.
2442       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2443       return CombineTo(N, Lo, Hi);
2444     }
2445   }
2446
2447   return SDValue();
2448 }
2449
2450 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2451   // (smulo x, 2) -> (saddo x, x)
2452   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2453     if (C2->getAPIntValue() == 2)
2454       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2455                          N->getOperand(0), N->getOperand(0));
2456
2457   return SDValue();
2458 }
2459
2460 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2461   // (umulo x, 2) -> (uaddo x, x)
2462   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2463     if (C2->getAPIntValue() == 2)
2464       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2465                          N->getOperand(0), N->getOperand(0));
2466
2467   return SDValue();
2468 }
2469
2470 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2471   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2472   if (Res.getNode()) return Res;
2473
2474   return SDValue();
2475 }
2476
2477 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2478   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2479   if (Res.getNode()) return Res;
2480
2481   return SDValue();
2482 }
2483
2484 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2485 /// two operands of the same opcode, try to simplify it.
2486 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2487   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2488   EVT VT = N0.getValueType();
2489   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2490
2491   // Bail early if none of these transforms apply.
2492   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2493
2494   // For each of OP in AND/OR/XOR:
2495   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2496   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2497   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2498   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2499   //
2500   // do not sink logical op inside of a vector extend, since it may combine
2501   // into a vsetcc.
2502   EVT Op0VT = N0.getOperand(0).getValueType();
2503   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2504        N0.getOpcode() == ISD::SIGN_EXTEND ||
2505        // Avoid infinite looping with PromoteIntBinOp.
2506        (N0.getOpcode() == ISD::ANY_EXTEND &&
2507         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2508        (N0.getOpcode() == ISD::TRUNCATE &&
2509         (!TLI.isZExtFree(VT, Op0VT) ||
2510          !TLI.isTruncateFree(Op0VT, VT)) &&
2511         TLI.isTypeLegal(Op0VT))) &&
2512       !VT.isVector() &&
2513       Op0VT == N1.getOperand(0).getValueType() &&
2514       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2515     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2516                                  N0.getOperand(0).getValueType(),
2517                                  N0.getOperand(0), N1.getOperand(0));
2518     AddToWorklist(ORNode.getNode());
2519     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2520   }
2521
2522   // For each of OP in SHL/SRL/SRA/AND...
2523   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2524   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2525   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2526   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2527        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2528       N0.getOperand(1) == N1.getOperand(1)) {
2529     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2530                                  N0.getOperand(0).getValueType(),
2531                                  N0.getOperand(0), N1.getOperand(0));
2532     AddToWorklist(ORNode.getNode());
2533     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2534                        ORNode, N0.getOperand(1));
2535   }
2536
2537   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2538   // Only perform this optimization after type legalization and before
2539   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2540   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2541   // we don't want to undo this promotion.
2542   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2543   // on scalars.
2544   if ((N0.getOpcode() == ISD::BITCAST ||
2545        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2546       Level == AfterLegalizeTypes) {
2547     SDValue In0 = N0.getOperand(0);
2548     SDValue In1 = N1.getOperand(0);
2549     EVT In0Ty = In0.getValueType();
2550     EVT In1Ty = In1.getValueType();
2551     SDLoc DL(N);
2552     // If both incoming values are integers, and the original types are the
2553     // same.
2554     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2555       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2556       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2557       AddToWorklist(Op.getNode());
2558       return BC;
2559     }
2560   }
2561
2562   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2563   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2564   // If both shuffles use the same mask, and both shuffle within a single
2565   // vector, then it is worthwhile to move the swizzle after the operation.
2566   // The type-legalizer generates this pattern when loading illegal
2567   // vector types from memory. In many cases this allows additional shuffle
2568   // optimizations.
2569   // There are other cases where moving the shuffle after the xor/and/or
2570   // is profitable even if shuffles don't perform a swizzle.
2571   // If both shuffles use the same mask, and both shuffles have the same first
2572   // or second operand, then it might still be profitable to move the shuffle
2573   // after the xor/and/or operation.
2574   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2575     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2576     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2577
2578     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2579            "Inputs to shuffles are not the same type");
2580
2581     // Check that both shuffles use the same mask. The masks are known to be of
2582     // the same length because the result vector type is the same.
2583     // Check also that shuffles have only one use to avoid introducing extra
2584     // instructions.
2585     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2586         SVN0->getMask().equals(SVN1->getMask())) {
2587       SDValue ShOp = N0->getOperand(1);
2588
2589       // Don't try to fold this node if it requires introducing a
2590       // build vector of all zeros that might be illegal at this stage.
2591       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2592         if (!LegalTypes)
2593           ShOp = DAG.getConstant(0, VT);
2594         else
2595           ShOp = SDValue();
2596       }
2597
2598       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2599       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2600       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2601       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2602         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2603                                       N0->getOperand(0), N1->getOperand(0));
2604         AddToWorklist(NewNode.getNode());
2605         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2606                                     &SVN0->getMask()[0]);
2607       }
2608
2609       // Don't try to fold this node if it requires introducing a
2610       // build vector of all zeros that might be illegal at this stage.
2611       ShOp = N0->getOperand(0);
2612       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2613         if (!LegalTypes)
2614           ShOp = DAG.getConstant(0, VT);
2615         else
2616           ShOp = SDValue();
2617       }
2618
2619       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2620       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2621       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2622       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2623         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2624                                       N0->getOperand(1), N1->getOperand(1));
2625         AddToWorklist(NewNode.getNode());
2626         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2627                                     &SVN0->getMask()[0]);
2628       }
2629     }
2630   }
2631
2632   return SDValue();
2633 }
2634
2635 SDValue DAGCombiner::visitAND(SDNode *N) {
2636   SDValue N0 = N->getOperand(0);
2637   SDValue N1 = N->getOperand(1);
2638   SDValue LL, LR, RL, RR, CC0, CC1;
2639   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2640   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2641   EVT VT = N1.getValueType();
2642   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2643
2644   // fold vector ops
2645   if (VT.isVector()) {
2646     SDValue FoldedVOp = SimplifyVBinOp(N);
2647     if (FoldedVOp.getNode()) return FoldedVOp;
2648
2649     // fold (and x, 0) -> 0, vector edition
2650     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2651       return N0;
2652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2653       return N1;
2654
2655     // fold (and x, -1) -> x, vector edition
2656     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2657       return N1;
2658     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2659       return N0;
2660   }
2661
2662   // fold (and x, undef) -> 0
2663   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2664     return DAG.getConstant(0, VT);
2665   // fold (and c1, c2) -> c1&c2
2666   if (N0C && N1C)
2667     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2668   // canonicalize constant to RHS
2669   if (N0C && !N1C)
2670     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2671   // fold (and x, -1) -> x
2672   if (N1C && N1C->isAllOnesValue())
2673     return N0;
2674   // if (and x, c) is known to be zero, return 0
2675   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2676                                    APInt::getAllOnesValue(BitWidth)))
2677     return DAG.getConstant(0, VT);
2678   // reassociate and
2679   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2680   if (RAND.getNode())
2681     return RAND;
2682   // fold (and (or x, C), D) -> D if (C & D) == D
2683   if (N1C && N0.getOpcode() == ISD::OR)
2684     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2685       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2686         return N1;
2687   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2688   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2689     SDValue N0Op0 = N0.getOperand(0);
2690     APInt Mask = ~N1C->getAPIntValue();
2691     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2692     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2693       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2694                                  N0.getValueType(), N0Op0);
2695
2696       // Replace uses of the AND with uses of the Zero extend node.
2697       CombineTo(N, Zext);
2698
2699       // We actually want to replace all uses of the any_extend with the
2700       // zero_extend, to avoid duplicating things.  This will later cause this
2701       // AND to be folded.
2702       CombineTo(N0.getNode(), Zext);
2703       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2704     }
2705   }
2706   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2707   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2708   // already be zero by virtue of the width of the base type of the load.
2709   //
2710   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2711   // more cases.
2712   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2713        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2714       N0.getOpcode() == ISD::LOAD) {
2715     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2716                                          N0 : N0.getOperand(0) );
2717
2718     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2719     // This can be a pure constant or a vector splat, in which case we treat the
2720     // vector as a scalar and use the splat value.
2721     APInt Constant = APInt::getNullValue(1);
2722     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2723       Constant = C->getAPIntValue();
2724     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2725       APInt SplatValue, SplatUndef;
2726       unsigned SplatBitSize;
2727       bool HasAnyUndefs;
2728       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2729                                              SplatBitSize, HasAnyUndefs);
2730       if (IsSplat) {
2731         // Undef bits can contribute to a possible optimisation if set, so
2732         // set them.
2733         SplatValue |= SplatUndef;
2734
2735         // The splat value may be something like "0x00FFFFFF", which means 0 for
2736         // the first vector value and FF for the rest, repeating. We need a mask
2737         // that will apply equally to all members of the vector, so AND all the
2738         // lanes of the constant together.
2739         EVT VT = Vector->getValueType(0);
2740         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2741
2742         // If the splat value has been compressed to a bitlength lower
2743         // than the size of the vector lane, we need to re-expand it to
2744         // the lane size.
2745         if (BitWidth > SplatBitSize)
2746           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2747                SplatBitSize < BitWidth;
2748                SplatBitSize = SplatBitSize * 2)
2749             SplatValue |= SplatValue.shl(SplatBitSize);
2750
2751         Constant = APInt::getAllOnesValue(BitWidth);
2752         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2753           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2754       }
2755     }
2756
2757     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2758     // actually legal and isn't going to get expanded, else this is a false
2759     // optimisation.
2760     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2761                                                     Load->getMemoryVT());
2762
2763     // Resize the constant to the same size as the original memory access before
2764     // extension. If it is still the AllOnesValue then this AND is completely
2765     // unneeded.
2766     Constant =
2767       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2768
2769     bool B;
2770     switch (Load->getExtensionType()) {
2771     default: B = false; break;
2772     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2773     case ISD::ZEXTLOAD:
2774     case ISD::NON_EXTLOAD: B = true; break;
2775     }
2776
2777     if (B && Constant.isAllOnesValue()) {
2778       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2779       // preserve semantics once we get rid of the AND.
2780       SDValue NewLoad(Load, 0);
2781       if (Load->getExtensionType() == ISD::EXTLOAD) {
2782         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2783                               Load->getValueType(0), SDLoc(Load),
2784                               Load->getChain(), Load->getBasePtr(),
2785                               Load->getOffset(), Load->getMemoryVT(),
2786                               Load->getMemOperand());
2787         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2788         if (Load->getNumValues() == 3) {
2789           // PRE/POST_INC loads have 3 values.
2790           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2791                            NewLoad.getValue(2) };
2792           CombineTo(Load, To, 3, true);
2793         } else {
2794           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2795         }
2796       }
2797
2798       // Fold the AND away, taking care not to fold to the old load node if we
2799       // replaced it.
2800       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2801
2802       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2803     }
2804   }
2805   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2806   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2807     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2808     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2809
2810     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2811         LL.getValueType().isInteger()) {
2812       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2813       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2814         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2815                                      LR.getValueType(), LL, RL);
2816         AddToWorklist(ORNode.getNode());
2817         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2818       }
2819       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2820       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2821         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2822                                       LR.getValueType(), LL, RL);
2823         AddToWorklist(ANDNode.getNode());
2824         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2825       }
2826       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2827       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2828         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2829                                      LR.getValueType(), LL, RL);
2830         AddToWorklist(ORNode.getNode());
2831         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2832       }
2833     }
2834     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2835     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2836         Op0 == Op1 && LL.getValueType().isInteger() &&
2837       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2838                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2839                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2840                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2841       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2842                                     LL, DAG.getConstant(1, LL.getValueType()));
2843       AddToWorklist(ADDNode.getNode());
2844       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2845                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2846     }
2847     // canonicalize equivalent to ll == rl
2848     if (LL == RR && LR == RL) {
2849       Op1 = ISD::getSetCCSwappedOperands(Op1);
2850       std::swap(RL, RR);
2851     }
2852     if (LL == RL && LR == RR) {
2853       bool isInteger = LL.getValueType().isInteger();
2854       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2855       if (Result != ISD::SETCC_INVALID &&
2856           (!LegalOperations ||
2857            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2858             TLI.isOperationLegal(ISD::SETCC,
2859                             getSetCCResultType(N0.getSimpleValueType())))))
2860         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2861                             LL, LR, Result);
2862     }
2863   }
2864
2865   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2866   if (N0.getOpcode() == N1.getOpcode()) {
2867     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2868     if (Tmp.getNode()) return Tmp;
2869   }
2870
2871   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2872   // fold (and (sra)) -> (and (srl)) when possible.
2873   if (!VT.isVector() &&
2874       SimplifyDemandedBits(SDValue(N, 0)))
2875     return SDValue(N, 0);
2876
2877   // fold (zext_inreg (extload x)) -> (zextload x)
2878   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2879     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2880     EVT MemVT = LN0->getMemoryVT();
2881     // If we zero all the possible extended bits, then we can turn this into
2882     // a zextload if we are running before legalize or the operation is legal.
2883     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2884     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2885                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2886         ((!LegalOperations && !LN0->isVolatile()) ||
2887          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2888       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2889                                        LN0->getChain(), LN0->getBasePtr(),
2890                                        MemVT, LN0->getMemOperand());
2891       AddToWorklist(N);
2892       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2893       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2894     }
2895   }
2896   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2897   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2898       N0.hasOneUse()) {
2899     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2900     EVT MemVT = LN0->getMemoryVT();
2901     // If we zero all the possible extended bits, then we can turn this into
2902     // a zextload if we are running before legalize or the operation is legal.
2903     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2904     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2905                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2906         ((!LegalOperations && !LN0->isVolatile()) ||
2907          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2908       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2909                                        LN0->getChain(), LN0->getBasePtr(),
2910                                        MemVT, LN0->getMemOperand());
2911       AddToWorklist(N);
2912       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2913       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2914     }
2915   }
2916
2917   // fold (and (load x), 255) -> (zextload x, i8)
2918   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2919   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2920   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2921               (N0.getOpcode() == ISD::ANY_EXTEND &&
2922                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2923     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2924     LoadSDNode *LN0 = HasAnyExt
2925       ? cast<LoadSDNode>(N0.getOperand(0))
2926       : cast<LoadSDNode>(N0);
2927     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2928         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2929       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2930       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2931         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2932         EVT LoadedVT = LN0->getMemoryVT();
2933
2934         if (ExtVT == LoadedVT &&
2935             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2936           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2937
2938           SDValue NewLoad =
2939             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2940                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2941                            LN0->getMemOperand());
2942           AddToWorklist(N);
2943           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2944           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2945         }
2946
2947         // Do not change the width of a volatile load.
2948         // Do not generate loads of non-round integer types since these can
2949         // be expensive (and would be wrong if the type is not byte sized).
2950         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2951             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2952           EVT PtrType = LN0->getOperand(1).getValueType();
2953
2954           unsigned Alignment = LN0->getAlignment();
2955           SDValue NewPtr = LN0->getBasePtr();
2956
2957           // For big endian targets, we need to add an offset to the pointer
2958           // to load the correct bytes.  For little endian systems, we merely
2959           // need to read fewer bytes from the same pointer.
2960           if (TLI.isBigEndian()) {
2961             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2962             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2963             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2964             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2965                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2966             Alignment = MinAlign(Alignment, PtrOff);
2967           }
2968
2969           AddToWorklist(NewPtr.getNode());
2970
2971           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2972           SDValue Load =
2973             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2974                            LN0->getChain(), NewPtr,
2975                            LN0->getPointerInfo(),
2976                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2977                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2978           AddToWorklist(N);
2979           CombineTo(LN0, Load, Load.getValue(1));
2980           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2981         }
2982       }
2983     }
2984   }
2985
2986   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2987       VT.getSizeInBits() <= 64) {
2988     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2989       APInt ADDC = ADDI->getAPIntValue();
2990       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2991         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2992         // immediate for an add, but it is legal if its top c2 bits are set,
2993         // transform the ADD so the immediate doesn't need to be materialized
2994         // in a register.
2995         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2996           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2997                                              SRLI->getZExtValue());
2998           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2999             ADDC |= Mask;
3000             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3001               SDValue NewAdd =
3002                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3003                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3004               CombineTo(N0.getNode(), NewAdd);
3005               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3006             }
3007           }
3008         }
3009       }
3010     }
3011   }
3012
3013   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3014   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3015     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3016                                        N0.getOperand(1), false);
3017     if (BSwap.getNode())
3018       return BSwap;
3019   }
3020
3021   return SDValue();
3022 }
3023
3024 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3025 ///
3026 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3027                                         bool DemandHighBits) {
3028   if (!LegalOperations)
3029     return SDValue();
3030
3031   EVT VT = N->getValueType(0);
3032   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3033     return SDValue();
3034   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3035     return SDValue();
3036
3037   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3038   bool LookPassAnd0 = false;
3039   bool LookPassAnd1 = false;
3040   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3041       std::swap(N0, N1);
3042   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3043       std::swap(N0, N1);
3044   if (N0.getOpcode() == ISD::AND) {
3045     if (!N0.getNode()->hasOneUse())
3046       return SDValue();
3047     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3048     if (!N01C || N01C->getZExtValue() != 0xFF00)
3049       return SDValue();
3050     N0 = N0.getOperand(0);
3051     LookPassAnd0 = true;
3052   }
3053
3054   if (N1.getOpcode() == ISD::AND) {
3055     if (!N1.getNode()->hasOneUse())
3056       return SDValue();
3057     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3058     if (!N11C || N11C->getZExtValue() != 0xFF)
3059       return SDValue();
3060     N1 = N1.getOperand(0);
3061     LookPassAnd1 = true;
3062   }
3063
3064   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3065     std::swap(N0, N1);
3066   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3067     return SDValue();
3068   if (!N0.getNode()->hasOneUse() ||
3069       !N1.getNode()->hasOneUse())
3070     return SDValue();
3071
3072   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3073   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3074   if (!N01C || !N11C)
3075     return SDValue();
3076   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3077     return SDValue();
3078
3079   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3080   SDValue N00 = N0->getOperand(0);
3081   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3082     if (!N00.getNode()->hasOneUse())
3083       return SDValue();
3084     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3085     if (!N001C || N001C->getZExtValue() != 0xFF)
3086       return SDValue();
3087     N00 = N00.getOperand(0);
3088     LookPassAnd0 = true;
3089   }
3090
3091   SDValue N10 = N1->getOperand(0);
3092   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3093     if (!N10.getNode()->hasOneUse())
3094       return SDValue();
3095     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3096     if (!N101C || N101C->getZExtValue() != 0xFF00)
3097       return SDValue();
3098     N10 = N10.getOperand(0);
3099     LookPassAnd1 = true;
3100   }
3101
3102   if (N00 != N10)
3103     return SDValue();
3104
3105   // Make sure everything beyond the low halfword gets set to zero since the SRL
3106   // 16 will clear the top bits.
3107   unsigned OpSizeInBits = VT.getSizeInBits();
3108   if (DemandHighBits && OpSizeInBits > 16) {
3109     // If the left-shift isn't masked out then the only way this is a bswap is
3110     // if all bits beyond the low 8 are 0. In that case the entire pattern
3111     // reduces to a left shift anyway: leave it for other parts of the combiner.
3112     if (!LookPassAnd0)
3113       return SDValue();
3114
3115     // However, if the right shift isn't masked out then it might be because
3116     // it's not needed. See if we can spot that too.
3117     if (!LookPassAnd1 &&
3118         !DAG.MaskedValueIsZero(
3119             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3120       return SDValue();
3121   }
3122
3123   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3124   if (OpSizeInBits > 16)
3125     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3126                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3127   return Res;
3128 }
3129
3130 /// isBSwapHWordElement - Return true if the specified node is an element
3131 /// that makes up a 32-bit packed halfword byteswap. i.e.
3132 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3133 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3134   if (!N.getNode()->hasOneUse())
3135     return false;
3136
3137   unsigned Opc = N.getOpcode();
3138   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3139     return false;
3140
3141   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3142   if (!N1C)
3143     return false;
3144
3145   unsigned Num;
3146   switch (N1C->getZExtValue()) {
3147   default:
3148     return false;
3149   case 0xFF:       Num = 0; break;
3150   case 0xFF00:     Num = 1; break;
3151   case 0xFF0000:   Num = 2; break;
3152   case 0xFF000000: Num = 3; break;
3153   }
3154
3155   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3156   SDValue N0 = N.getOperand(0);
3157   if (Opc == ISD::AND) {
3158     if (Num == 0 || Num == 2) {
3159       // (x >> 8) & 0xff
3160       // (x >> 8) & 0xff0000
3161       if (N0.getOpcode() != ISD::SRL)
3162         return false;
3163       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3164       if (!C || C->getZExtValue() != 8)
3165         return false;
3166     } else {
3167       // (x << 8) & 0xff00
3168       // (x << 8) & 0xff000000
3169       if (N0.getOpcode() != ISD::SHL)
3170         return false;
3171       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3172       if (!C || C->getZExtValue() != 8)
3173         return false;
3174     }
3175   } else if (Opc == ISD::SHL) {
3176     // (x & 0xff) << 8
3177     // (x & 0xff0000) << 8
3178     if (Num != 0 && Num != 2)
3179       return false;
3180     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3181     if (!C || C->getZExtValue() != 8)
3182       return false;
3183   } else { // Opc == ISD::SRL
3184     // (x & 0xff00) >> 8
3185     // (x & 0xff000000) >> 8
3186     if (Num != 1 && Num != 3)
3187       return false;
3188     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3189     if (!C || C->getZExtValue() != 8)
3190       return false;
3191   }
3192
3193   if (Parts[Num])
3194     return false;
3195
3196   Parts[Num] = N0.getOperand(0).getNode();
3197   return true;
3198 }
3199
3200 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3201 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3202 /// => (rotl (bswap x), 16)
3203 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3204   if (!LegalOperations)
3205     return SDValue();
3206
3207   EVT VT = N->getValueType(0);
3208   if (VT != MVT::i32)
3209     return SDValue();
3210   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3211     return SDValue();
3212
3213   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3214   // Look for either
3215   // (or (or (and), (and)), (or (and), (and)))
3216   // (or (or (or (and), (and)), (and)), (and))
3217   if (N0.getOpcode() != ISD::OR)
3218     return SDValue();
3219   SDValue N00 = N0.getOperand(0);
3220   SDValue N01 = N0.getOperand(1);
3221
3222   if (N1.getOpcode() == ISD::OR &&
3223       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3224     // (or (or (and), (and)), (or (and), (and)))
3225     SDValue N000 = N00.getOperand(0);
3226     if (!isBSwapHWordElement(N000, Parts))
3227       return SDValue();
3228
3229     SDValue N001 = N00.getOperand(1);
3230     if (!isBSwapHWordElement(N001, Parts))
3231       return SDValue();
3232     SDValue N010 = N01.getOperand(0);
3233     if (!isBSwapHWordElement(N010, Parts))
3234       return SDValue();
3235     SDValue N011 = N01.getOperand(1);
3236     if (!isBSwapHWordElement(N011, Parts))
3237       return SDValue();
3238   } else {
3239     // (or (or (or (and), (and)), (and)), (and))
3240     if (!isBSwapHWordElement(N1, Parts))
3241       return SDValue();
3242     if (!isBSwapHWordElement(N01, Parts))
3243       return SDValue();
3244     if (N00.getOpcode() != ISD::OR)
3245       return SDValue();
3246     SDValue N000 = N00.getOperand(0);
3247     if (!isBSwapHWordElement(N000, Parts))
3248       return SDValue();
3249     SDValue N001 = N00.getOperand(1);
3250     if (!isBSwapHWordElement(N001, Parts))
3251       return SDValue();
3252   }
3253
3254   // Make sure the parts are all coming from the same node.
3255   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3256     return SDValue();
3257
3258   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3259                               SDValue(Parts[0],0));
3260
3261   // Result of the bswap should be rotated by 16. If it's not legal, then
3262   // do  (x << 16) | (x >> 16).
3263   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3264   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3265     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3266   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3267     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3268   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3269                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3270                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3271 }
3272
3273 SDValue DAGCombiner::visitOR(SDNode *N) {
3274   SDValue N0 = N->getOperand(0);
3275   SDValue N1 = N->getOperand(1);
3276   SDValue LL, LR, RL, RR, CC0, CC1;
3277   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3278   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3279   EVT VT = N1.getValueType();
3280
3281   // fold vector ops
3282   if (VT.isVector()) {
3283     SDValue FoldedVOp = SimplifyVBinOp(N);
3284     if (FoldedVOp.getNode()) return FoldedVOp;
3285
3286     // fold (or x, 0) -> x, vector edition
3287     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3288       return N1;
3289     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3290       return N0;
3291
3292     // fold (or x, -1) -> -1, vector edition
3293     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3294       return N0;
3295     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3296       return N1;
3297
3298     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3299     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3300     // Do this only if the resulting shuffle is legal.
3301     if (isa<ShuffleVectorSDNode>(N0) &&
3302         isa<ShuffleVectorSDNode>(N1) &&
3303         // Avoid folding a node with illegal type.
3304         TLI.isTypeLegal(VT) &&
3305         N0->getOperand(1) == N1->getOperand(1) &&
3306         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3307       bool CanFold = true;
3308       unsigned NumElts = VT.getVectorNumElements();
3309       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3310       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3311       // We construct two shuffle masks:
3312       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3313       // and N1 as the second operand.
3314       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3315       // and N0 as the second operand.
3316       // We do this because OR is commutable and therefore there might be
3317       // two ways to fold this node into a shuffle.
3318       SmallVector<int,4> Mask1;
3319       SmallVector<int,4> Mask2;
3320
3321       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3322         int M0 = SV0->getMaskElt(i);
3323         int M1 = SV1->getMaskElt(i);
3324
3325         // Both shuffle indexes are undef. Propagate Undef.
3326         if (M0 < 0 && M1 < 0) {
3327           Mask1.push_back(M0);
3328           Mask2.push_back(M0);
3329           continue;
3330         }
3331
3332         if (M0 < 0 || M1 < 0 ||
3333             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3334             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3335           CanFold = false;
3336           break;
3337         }
3338
3339         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3340         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3341       }
3342
3343       if (CanFold) {
3344         // Fold this sequence only if the resulting shuffle is 'legal'.
3345         if (TLI.isShuffleMaskLegal(Mask1, VT))
3346           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3347                                       N1->getOperand(0), &Mask1[0]);
3348         if (TLI.isShuffleMaskLegal(Mask2, VT))
3349           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3350                                       N0->getOperand(0), &Mask2[0]);
3351       }
3352     }
3353   }
3354
3355   // fold (or x, undef) -> -1
3356   if (!LegalOperations &&
3357       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3358     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3359     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3360   }
3361   // fold (or c1, c2) -> c1|c2
3362   if (N0C && N1C)
3363     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3364   // canonicalize constant to RHS
3365   if (N0C && !N1C)
3366     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3367   // fold (or x, 0) -> x
3368   if (N1C && N1C->isNullValue())
3369     return N0;
3370   // fold (or x, -1) -> -1
3371   if (N1C && N1C->isAllOnesValue())
3372     return N1;
3373   // fold (or x, c) -> c iff (x & ~c) == 0
3374   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3375     return N1;
3376
3377   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3378   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3379   if (BSwap.getNode())
3380     return BSwap;
3381   BSwap = MatchBSwapHWordLow(N, N0, N1);
3382   if (BSwap.getNode())
3383     return BSwap;
3384
3385   // reassociate or
3386   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3387   if (ROR.getNode())
3388     return ROR;
3389   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3390   // iff (c1 & c2) == 0.
3391   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3392              isa<ConstantSDNode>(N0.getOperand(1))) {
3393     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3394     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3395       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3396       if (!COR.getNode())
3397         return SDValue();
3398       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3399                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3400                                      N0.getOperand(0), N1), COR);
3401     }
3402   }
3403   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3404   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3405     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3406     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3407
3408     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3409         LL.getValueType().isInteger()) {
3410       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3411       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3412       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3413           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3414         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3415                                      LR.getValueType(), LL, RL);
3416         AddToWorklist(ORNode.getNode());
3417         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3418       }
3419       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3420       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3421       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3422           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3423         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3424                                       LR.getValueType(), LL, RL);
3425         AddToWorklist(ANDNode.getNode());
3426         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3427       }
3428     }
3429     // canonicalize equivalent to ll == rl
3430     if (LL == RR && LR == RL) {
3431       Op1 = ISD::getSetCCSwappedOperands(Op1);
3432       std::swap(RL, RR);
3433     }
3434     if (LL == RL && LR == RR) {
3435       bool isInteger = LL.getValueType().isInteger();
3436       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3437       if (Result != ISD::SETCC_INVALID &&
3438           (!LegalOperations ||
3439            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3440             TLI.isOperationLegal(ISD::SETCC,
3441               getSetCCResultType(N0.getValueType())))))
3442         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3443                             LL, LR, Result);
3444     }
3445   }
3446
3447   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3448   if (N0.getOpcode() == N1.getOpcode()) {
3449     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3450     if (Tmp.getNode()) return Tmp;
3451   }
3452
3453   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3454   if (N0.getOpcode() == ISD::AND &&
3455       N1.getOpcode() == ISD::AND &&
3456       N0.getOperand(1).getOpcode() == ISD::Constant &&
3457       N1.getOperand(1).getOpcode() == ISD::Constant &&
3458       // Don't increase # computations.
3459       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3460     // We can only do this xform if we know that bits from X that are set in C2
3461     // but not in C1 are already zero.  Likewise for Y.
3462     const APInt &LHSMask =
3463       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3464     const APInt &RHSMask =
3465       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3466
3467     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3468         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3469       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3470                               N0.getOperand(0), N1.getOperand(0));
3471       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3472                          DAG.getConstant(LHSMask | RHSMask, VT));
3473     }
3474   }
3475
3476   // See if this is some rotate idiom.
3477   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3478     return SDValue(Rot, 0);
3479
3480   // Simplify the operands using demanded-bits information.
3481   if (!VT.isVector() &&
3482       SimplifyDemandedBits(SDValue(N, 0)))
3483     return SDValue(N, 0);
3484
3485   return SDValue();
3486 }
3487
3488 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3489 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3490   if (Op.getOpcode() == ISD::AND) {
3491     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3492       Mask = Op.getOperand(1);
3493       Op = Op.getOperand(0);
3494     } else {
3495       return false;
3496     }
3497   }
3498
3499   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3500     Shift = Op;
3501     return true;
3502   }
3503
3504   return false;
3505 }
3506
3507 // Return true if we can prove that, whenever Neg and Pos are both in the
3508 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3509 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3510 //
3511 //     (or (shift1 X, Neg), (shift2 X, Pos))
3512 //
3513 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3514 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3515 // to consider shift amounts with defined behavior.
3516 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3517   // If OpSize is a power of 2 then:
3518   //
3519   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3520   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3521   //
3522   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3523   // for the stronger condition:
3524   //
3525   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3526   //
3527   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3528   // we can just replace Neg with Neg' for the rest of the function.
3529   //
3530   // In other cases we check for the even stronger condition:
3531   //
3532   //     Neg == OpSize - Pos                                    [B]
3533   //
3534   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3535   // behavior if Pos == 0 (and consequently Neg == OpSize).
3536   //
3537   // We could actually use [A] whenever OpSize is a power of 2, but the
3538   // only extra cases that it would match are those uninteresting ones
3539   // where Neg and Pos are never in range at the same time.  E.g. for
3540   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3541   // as well as (sub 32, Pos), but:
3542   //
3543   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3544   //
3545   // always invokes undefined behavior for 32-bit X.
3546   //
3547   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3548   unsigned MaskLoBits = 0;
3549   if (Neg.getOpcode() == ISD::AND &&
3550       isPowerOf2_64(OpSize) &&
3551       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3552       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3553     Neg = Neg.getOperand(0);
3554     MaskLoBits = Log2_64(OpSize);
3555   }
3556
3557   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3558   if (Neg.getOpcode() != ISD::SUB)
3559     return 0;
3560   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3561   if (!NegC)
3562     return 0;
3563   SDValue NegOp1 = Neg.getOperand(1);
3564
3565   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3566   // Pos'.  The truncation is redundant for the purpose of the equality.
3567   if (MaskLoBits &&
3568       Pos.getOpcode() == ISD::AND &&
3569       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3570       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3571     Pos = Pos.getOperand(0);
3572
3573   // The condition we need is now:
3574   //
3575   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3576   //
3577   // If NegOp1 == Pos then we need:
3578   //
3579   //              OpSize & Mask == NegC & Mask
3580   //
3581   // (because "x & Mask" is a truncation and distributes through subtraction).
3582   APInt Width;
3583   if (Pos == NegOp1)
3584     Width = NegC->getAPIntValue();
3585   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3586   // Then the condition we want to prove becomes:
3587   //
3588   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3589   //
3590   // which, again because "x & Mask" is a truncation, becomes:
3591   //
3592   //                NegC & Mask == (OpSize - PosC) & Mask
3593   //              OpSize & Mask == (NegC + PosC) & Mask
3594   else if (Pos.getOpcode() == ISD::ADD &&
3595            Pos.getOperand(0) == NegOp1 &&
3596            Pos.getOperand(1).getOpcode() == ISD::Constant)
3597     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3598              NegC->getAPIntValue());
3599   else
3600     return false;
3601
3602   // Now we just need to check that OpSize & Mask == Width & Mask.
3603   if (MaskLoBits)
3604     // Opsize & Mask is 0 since Mask is Opsize - 1.
3605     return Width.getLoBits(MaskLoBits) == 0;
3606   return Width == OpSize;
3607 }
3608
3609 // A subroutine of MatchRotate used once we have found an OR of two opposite
3610 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3611 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3612 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3613 // Neg with outer conversions stripped away.
3614 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3615                                        SDValue Neg, SDValue InnerPos,
3616                                        SDValue InnerNeg, unsigned PosOpcode,
3617                                        unsigned NegOpcode, SDLoc DL) {
3618   // fold (or (shl x, (*ext y)),
3619   //          (srl x, (*ext (sub 32, y)))) ->
3620   //   (rotl x, y) or (rotr x, (sub 32, y))
3621   //
3622   // fold (or (shl x, (*ext (sub 32, y))),
3623   //          (srl x, (*ext y))) ->
3624   //   (rotr x, y) or (rotl x, (sub 32, y))
3625   EVT VT = Shifted.getValueType();
3626   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3627     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3628     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3629                        HasPos ? Pos : Neg).getNode();
3630   }
3631
3632   return nullptr;
3633 }
3634
3635 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3636 // idioms for rotate, and if the target supports rotation instructions, generate
3637 // a rot[lr].
3638 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3639   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3640   EVT VT = LHS.getValueType();
3641   if (!TLI.isTypeLegal(VT)) return nullptr;
3642
3643   // The target must have at least one rotate flavor.
3644   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3645   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3646   if (!HasROTL && !HasROTR) return nullptr;
3647
3648   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3649   SDValue LHSShift;   // The shift.
3650   SDValue LHSMask;    // AND value if any.
3651   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3652     return nullptr; // Not part of a rotate.
3653
3654   SDValue RHSShift;   // The shift.
3655   SDValue RHSMask;    // AND value if any.
3656   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3657     return nullptr; // Not part of a rotate.
3658
3659   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3660     return nullptr;   // Not shifting the same value.
3661
3662   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3663     return nullptr;   // Shifts must disagree.
3664
3665   // Canonicalize shl to left side in a shl/srl pair.
3666   if (RHSShift.getOpcode() == ISD::SHL) {
3667     std::swap(LHS, RHS);
3668     std::swap(LHSShift, RHSShift);
3669     std::swap(LHSMask , RHSMask );
3670   }
3671
3672   unsigned OpSizeInBits = VT.getSizeInBits();
3673   SDValue LHSShiftArg = LHSShift.getOperand(0);
3674   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3675   SDValue RHSShiftArg = RHSShift.getOperand(0);
3676   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3677
3678   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3679   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3680   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3681       RHSShiftAmt.getOpcode() == ISD::Constant) {
3682     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3683     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3684     if ((LShVal + RShVal) != OpSizeInBits)
3685       return nullptr;
3686
3687     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3688                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3689
3690     // If there is an AND of either shifted operand, apply it to the result.
3691     if (LHSMask.getNode() || RHSMask.getNode()) {
3692       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3693
3694       if (LHSMask.getNode()) {
3695         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3696         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3697       }
3698       if (RHSMask.getNode()) {
3699         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3700         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3701       }
3702
3703       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3704     }
3705
3706     return Rot.getNode();
3707   }
3708
3709   // If there is a mask here, and we have a variable shift, we can't be sure
3710   // that we're masking out the right stuff.
3711   if (LHSMask.getNode() || RHSMask.getNode())
3712     return nullptr;
3713
3714   // If the shift amount is sign/zext/any-extended just peel it off.
3715   SDValue LExtOp0 = LHSShiftAmt;
3716   SDValue RExtOp0 = RHSShiftAmt;
3717   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3718        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3719        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3720        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3721       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3722        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3723        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3724        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3725     LExtOp0 = LHSShiftAmt.getOperand(0);
3726     RExtOp0 = RHSShiftAmt.getOperand(0);
3727   }
3728
3729   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3730                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3731   if (TryL)
3732     return TryL;
3733
3734   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3735                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3736   if (TryR)
3737     return TryR;
3738
3739   return nullptr;
3740 }
3741
3742 SDValue DAGCombiner::visitXOR(SDNode *N) {
3743   SDValue N0 = N->getOperand(0);
3744   SDValue N1 = N->getOperand(1);
3745   SDValue LHS, RHS, CC;
3746   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3747   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3748   EVT VT = N0.getValueType();
3749
3750   // fold vector ops
3751   if (VT.isVector()) {
3752     SDValue FoldedVOp = SimplifyVBinOp(N);
3753     if (FoldedVOp.getNode()) return FoldedVOp;
3754
3755     // fold (xor x, 0) -> x, vector edition
3756     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3757       return N1;
3758     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3759       return N0;
3760   }
3761
3762   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3763   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3764     return DAG.getConstant(0, VT);
3765   // fold (xor x, undef) -> undef
3766   if (N0.getOpcode() == ISD::UNDEF)
3767     return N0;
3768   if (N1.getOpcode() == ISD::UNDEF)
3769     return N1;
3770   // fold (xor c1, c2) -> c1^c2
3771   if (N0C && N1C)
3772     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3773   // canonicalize constant to RHS
3774   if (N0C && !N1C)
3775     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3776   // fold (xor x, 0) -> x
3777   if (N1C && N1C->isNullValue())
3778     return N0;
3779   // reassociate xor
3780   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3781   if (RXOR.getNode())
3782     return RXOR;
3783
3784   // fold !(x cc y) -> (x !cc y)
3785   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3786     bool isInt = LHS.getValueType().isInteger();
3787     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3788                                                isInt);
3789
3790     if (!LegalOperations ||
3791         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3792       switch (N0.getOpcode()) {
3793       default:
3794         llvm_unreachable("Unhandled SetCC Equivalent!");
3795       case ISD::SETCC:
3796         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3797       case ISD::SELECT_CC:
3798         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3799                                N0.getOperand(3), NotCC);
3800       }
3801     }
3802   }
3803
3804   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3805   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3806       N0.getNode()->hasOneUse() &&
3807       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3808     SDValue V = N0.getOperand(0);
3809     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3810                     DAG.getConstant(1, V.getValueType()));
3811     AddToWorklist(V.getNode());
3812     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3813   }
3814
3815   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3816   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3817       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3818     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3819     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3820       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3821       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3822       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3823       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3824       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3825     }
3826   }
3827   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3828   if (N1C && N1C->isAllOnesValue() &&
3829       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3830     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3831     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3832       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3833       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3834       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3835       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3836       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3837     }
3838   }
3839   // fold (xor (and x, y), y) -> (and (not x), y)
3840   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3841       N0->getOperand(1) == N1) {
3842     SDValue X = N0->getOperand(0);
3843     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3844     AddToWorklist(NotX.getNode());
3845     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3846   }
3847   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3848   if (N1C && N0.getOpcode() == ISD::XOR) {
3849     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3850     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3851     if (N00C)
3852       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3853                          DAG.getConstant(N1C->getAPIntValue() ^
3854                                          N00C->getAPIntValue(), VT));
3855     if (N01C)
3856       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3857                          DAG.getConstant(N1C->getAPIntValue() ^
3858                                          N01C->getAPIntValue(), VT));
3859   }
3860   // fold (xor x, x) -> 0
3861   if (N0 == N1)
3862     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3863
3864   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3865   if (N0.getOpcode() == N1.getOpcode()) {
3866     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3867     if (Tmp.getNode()) return Tmp;
3868   }
3869
3870   // Simplify the expression using non-local knowledge.
3871   if (!VT.isVector() &&
3872       SimplifyDemandedBits(SDValue(N, 0)))
3873     return SDValue(N, 0);
3874
3875   return SDValue();
3876 }
3877
3878 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3879 /// the shift amount is a constant.
3880 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3881   // We can't and shouldn't fold opaque constants.
3882   if (Amt->isOpaque())
3883     return SDValue();
3884
3885   SDNode *LHS = N->getOperand(0).getNode();
3886   if (!LHS->hasOneUse()) return SDValue();
3887
3888   // We want to pull some binops through shifts, so that we have (and (shift))
3889   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3890   // thing happens with address calculations, so it's important to canonicalize
3891   // it.
3892   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3893
3894   switch (LHS->getOpcode()) {
3895   default: return SDValue();
3896   case ISD::OR:
3897   case ISD::XOR:
3898     HighBitSet = false; // We can only transform sra if the high bit is clear.
3899     break;
3900   case ISD::AND:
3901     HighBitSet = true;  // We can only transform sra if the high bit is set.
3902     break;
3903   case ISD::ADD:
3904     if (N->getOpcode() != ISD::SHL)
3905       return SDValue(); // only shl(add) not sr[al](add).
3906     HighBitSet = false; // We can only transform sra if the high bit is clear.
3907     break;
3908   }
3909
3910   // We require the RHS of the binop to be a constant and not opaque as well.
3911   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3912   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3913
3914   // FIXME: disable this unless the input to the binop is a shift by a constant.
3915   // If it is not a shift, it pessimizes some common cases like:
3916   //
3917   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3918   //    int bar(int *X, int i) { return X[i & 255]; }
3919   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3920   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3921        BinOpLHSVal->getOpcode() != ISD::SRA &&
3922        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3923       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3924     return SDValue();
3925
3926   EVT VT = N->getValueType(0);
3927
3928   // If this is a signed shift right, and the high bit is modified by the
3929   // logical operation, do not perform the transformation. The highBitSet
3930   // boolean indicates the value of the high bit of the constant which would
3931   // cause it to be modified for this operation.
3932   if (N->getOpcode() == ISD::SRA) {
3933     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3934     if (BinOpRHSSignSet != HighBitSet)
3935       return SDValue();
3936   }
3937
3938   if (!TLI.isDesirableToCommuteWithShift(LHS))
3939     return SDValue();
3940
3941   // Fold the constants, shifting the binop RHS by the shift amount.
3942   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3943                                N->getValueType(0),
3944                                LHS->getOperand(1), N->getOperand(1));
3945   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3946
3947   // Create the new shift.
3948   SDValue NewShift = DAG.getNode(N->getOpcode(),
3949                                  SDLoc(LHS->getOperand(0)),
3950                                  VT, LHS->getOperand(0), N->getOperand(1));
3951
3952   // Create the new binop.
3953   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3954 }
3955
3956 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3957   assert(N->getOpcode() == ISD::TRUNCATE);
3958   assert(N->getOperand(0).getOpcode() == ISD::AND);
3959
3960   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3961   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3962     SDValue N01 = N->getOperand(0).getOperand(1);
3963
3964     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3965       EVT TruncVT = N->getValueType(0);
3966       SDValue N00 = N->getOperand(0).getOperand(0);
3967       APInt TruncC = N01C->getAPIntValue();
3968       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3969
3970       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3971                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3972                          DAG.getConstant(TruncC, TruncVT));
3973     }
3974   }
3975
3976   return SDValue();
3977 }
3978
3979 SDValue DAGCombiner::visitRotate(SDNode *N) {
3980   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3981   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3982       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3983     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3984     if (NewOp1.getNode())
3985       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3986                          N->getOperand(0), NewOp1);
3987   }
3988   return SDValue();
3989 }
3990
3991 SDValue DAGCombiner::visitSHL(SDNode *N) {
3992   SDValue N0 = N->getOperand(0);
3993   SDValue N1 = N->getOperand(1);
3994   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3995   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3996   EVT VT = N0.getValueType();
3997   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3998
3999   // fold vector ops
4000   if (VT.isVector()) {
4001     SDValue FoldedVOp = SimplifyVBinOp(N);
4002     if (FoldedVOp.getNode()) return FoldedVOp;
4003
4004     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4005     // If setcc produces all-one true value then:
4006     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4007     if (N1CV && N1CV->isConstant()) {
4008       if (N0.getOpcode() == ISD::AND) {
4009         SDValue N00 = N0->getOperand(0);
4010         SDValue N01 = N0->getOperand(1);
4011         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4012
4013         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4014             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4015                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4016           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4017           if (C.getNode())
4018             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4019         }
4020       } else {
4021         N1C = isConstOrConstSplat(N1);
4022       }
4023     }
4024   }
4025
4026   // fold (shl c1, c2) -> c1<<c2
4027   if (N0C && N1C)
4028     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4029   // fold (shl 0, x) -> 0
4030   if (N0C && N0C->isNullValue())
4031     return N0;
4032   // fold (shl x, c >= size(x)) -> undef
4033   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4034     return DAG.getUNDEF(VT);
4035   // fold (shl x, 0) -> x
4036   if (N1C && N1C->isNullValue())
4037     return N0;
4038   // fold (shl undef, x) -> 0
4039   if (N0.getOpcode() == ISD::UNDEF)
4040     return DAG.getConstant(0, VT);
4041   // if (shl x, c) is known to be zero, return 0
4042   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4043                             APInt::getAllOnesValue(OpSizeInBits)))
4044     return DAG.getConstant(0, VT);
4045   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4046   if (N1.getOpcode() == ISD::TRUNCATE &&
4047       N1.getOperand(0).getOpcode() == ISD::AND) {
4048     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4049     if (NewOp1.getNode())
4050       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4051   }
4052
4053   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4054     return SDValue(N, 0);
4055
4056   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4057   if (N1C && N0.getOpcode() == ISD::SHL) {
4058     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4059       uint64_t c1 = N0C1->getZExtValue();
4060       uint64_t c2 = N1C->getZExtValue();
4061       if (c1 + c2 >= OpSizeInBits)
4062         return DAG.getConstant(0, VT);
4063       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4064                          DAG.getConstant(c1 + c2, N1.getValueType()));
4065     }
4066   }
4067
4068   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4069   // For this to be valid, the second form must not preserve any of the bits
4070   // that are shifted out by the inner shift in the first form.  This means
4071   // the outer shift size must be >= the number of bits added by the ext.
4072   // As a corollary, we don't care what kind of ext it is.
4073   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4074               N0.getOpcode() == ISD::ANY_EXTEND ||
4075               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4076       N0.getOperand(0).getOpcode() == ISD::SHL) {
4077     SDValue N0Op0 = N0.getOperand(0);
4078     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4079       uint64_t c1 = N0Op0C1->getZExtValue();
4080       uint64_t c2 = N1C->getZExtValue();
4081       EVT InnerShiftVT = N0Op0.getValueType();
4082       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4083       if (c2 >= OpSizeInBits - InnerShiftSize) {
4084         if (c1 + c2 >= OpSizeInBits)
4085           return DAG.getConstant(0, VT);
4086         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4087                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4088                                        N0Op0->getOperand(0)),
4089                            DAG.getConstant(c1 + c2, N1.getValueType()));
4090       }
4091     }
4092   }
4093
4094   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4095   // Only fold this if the inner zext has no other uses to avoid increasing
4096   // the total number of instructions.
4097   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4098       N0.getOperand(0).getOpcode() == ISD::SRL) {
4099     SDValue N0Op0 = N0.getOperand(0);
4100     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4101       uint64_t c1 = N0Op0C1->getZExtValue();
4102       if (c1 < VT.getScalarSizeInBits()) {
4103         uint64_t c2 = N1C->getZExtValue();
4104         if (c1 == c2) {
4105           SDValue NewOp0 = N0.getOperand(0);
4106           EVT CountVT = NewOp0.getOperand(1).getValueType();
4107           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4108                                        NewOp0, DAG.getConstant(c2, CountVT));
4109           AddToWorklist(NewSHL.getNode());
4110           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4111         }
4112       }
4113     }
4114   }
4115
4116   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4117   //                               (and (srl x, (sub c1, c2), MASK)
4118   // Only fold this if the inner shift has no other uses -- if it does, folding
4119   // this will increase the total number of instructions.
4120   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4121     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4122       uint64_t c1 = N0C1->getZExtValue();
4123       if (c1 < OpSizeInBits) {
4124         uint64_t c2 = N1C->getZExtValue();
4125         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4126         SDValue Shift;
4127         if (c2 > c1) {
4128           Mask = Mask.shl(c2 - c1);
4129           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4130                               DAG.getConstant(c2 - c1, N1.getValueType()));
4131         } else {
4132           Mask = Mask.lshr(c1 - c2);
4133           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4134                               DAG.getConstant(c1 - c2, N1.getValueType()));
4135         }
4136         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4137                            DAG.getConstant(Mask, VT));
4138       }
4139     }
4140   }
4141   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4142   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4143     unsigned BitSize = VT.getScalarSizeInBits();
4144     SDValue HiBitsMask =
4145       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4146                                             BitSize - N1C->getZExtValue()), VT);
4147     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4148                        HiBitsMask);
4149   }
4150
4151   if (N1C) {
4152     SDValue NewSHL = visitShiftByConstant(N, N1C);
4153     if (NewSHL.getNode())
4154       return NewSHL;
4155   }
4156
4157   return SDValue();
4158 }
4159
4160 SDValue DAGCombiner::visitSRA(SDNode *N) {
4161   SDValue N0 = N->getOperand(0);
4162   SDValue N1 = N->getOperand(1);
4163   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4164   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4165   EVT VT = N0.getValueType();
4166   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4167
4168   // fold vector ops
4169   if (VT.isVector()) {
4170     SDValue FoldedVOp = SimplifyVBinOp(N);
4171     if (FoldedVOp.getNode()) return FoldedVOp;
4172
4173     N1C = isConstOrConstSplat(N1);
4174   }
4175
4176   // fold (sra c1, c2) -> (sra c1, c2)
4177   if (N0C && N1C)
4178     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4179   // fold (sra 0, x) -> 0
4180   if (N0C && N0C->isNullValue())
4181     return N0;
4182   // fold (sra -1, x) -> -1
4183   if (N0C && N0C->isAllOnesValue())
4184     return N0;
4185   // fold (sra x, (setge c, size(x))) -> undef
4186   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4187     return DAG.getUNDEF(VT);
4188   // fold (sra x, 0) -> x
4189   if (N1C && N1C->isNullValue())
4190     return N0;
4191   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4192   // sext_inreg.
4193   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4194     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4195     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4196     if (VT.isVector())
4197       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4198                                ExtVT, VT.getVectorNumElements());
4199     if ((!LegalOperations ||
4200          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4201       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4202                          N0.getOperand(0), DAG.getValueType(ExtVT));
4203   }
4204
4205   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4206   if (N1C && N0.getOpcode() == ISD::SRA) {
4207     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4208       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4209       if (Sum >= OpSizeInBits)
4210         Sum = OpSizeInBits - 1;
4211       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4212                          DAG.getConstant(Sum, N1.getValueType()));
4213     }
4214   }
4215
4216   // fold (sra (shl X, m), (sub result_size, n))
4217   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4218   // result_size - n != m.
4219   // If truncate is free for the target sext(shl) is likely to result in better
4220   // code.
4221   if (N0.getOpcode() == ISD::SHL && N1C) {
4222     // Get the two constanst of the shifts, CN0 = m, CN = n.
4223     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4224     if (N01C) {
4225       LLVMContext &Ctx = *DAG.getContext();
4226       // Determine what the truncate's result bitsize and type would be.
4227       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4228
4229       if (VT.isVector())
4230         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4231
4232       // Determine the residual right-shift amount.
4233       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4234
4235       // If the shift is not a no-op (in which case this should be just a sign
4236       // extend already), the truncated to type is legal, sign_extend is legal
4237       // on that type, and the truncate to that type is both legal and free,
4238       // perform the transform.
4239       if ((ShiftAmt > 0) &&
4240           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4241           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4242           TLI.isTruncateFree(VT, TruncVT)) {
4243
4244           SDValue Amt = DAG.getConstant(ShiftAmt,
4245               getShiftAmountTy(N0.getOperand(0).getValueType()));
4246           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4247                                       N0.getOperand(0), Amt);
4248           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4249                                       Shift);
4250           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4251                              N->getValueType(0), Trunc);
4252       }
4253     }
4254   }
4255
4256   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4257   if (N1.getOpcode() == ISD::TRUNCATE &&
4258       N1.getOperand(0).getOpcode() == ISD::AND) {
4259     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4260     if (NewOp1.getNode())
4261       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4262   }
4263
4264   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4265   //      if c1 is equal to the number of bits the trunc removes
4266   if (N0.getOpcode() == ISD::TRUNCATE &&
4267       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4268        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4269       N0.getOperand(0).hasOneUse() &&
4270       N0.getOperand(0).getOperand(1).hasOneUse() &&
4271       N1C) {
4272     SDValue N0Op0 = N0.getOperand(0);
4273     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4274       unsigned LargeShiftVal = LargeShift->getZExtValue();
4275       EVT LargeVT = N0Op0.getValueType();
4276
4277       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4278         SDValue Amt =
4279           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4280                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4281         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4282                                   N0Op0.getOperand(0), Amt);
4283         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4284       }
4285     }
4286   }
4287
4288   // Simplify, based on bits shifted out of the LHS.
4289   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4290     return SDValue(N, 0);
4291
4292
4293   // If the sign bit is known to be zero, switch this to a SRL.
4294   if (DAG.SignBitIsZero(N0))
4295     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4296
4297   if (N1C) {
4298     SDValue NewSRA = visitShiftByConstant(N, N1C);
4299     if (NewSRA.getNode())
4300       return NewSRA;
4301   }
4302
4303   return SDValue();
4304 }
4305
4306 SDValue DAGCombiner::visitSRL(SDNode *N) {
4307   SDValue N0 = N->getOperand(0);
4308   SDValue N1 = N->getOperand(1);
4309   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4310   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4311   EVT VT = N0.getValueType();
4312   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4313
4314   // fold vector ops
4315   if (VT.isVector()) {
4316     SDValue FoldedVOp = SimplifyVBinOp(N);
4317     if (FoldedVOp.getNode()) return FoldedVOp;
4318
4319     N1C = isConstOrConstSplat(N1);
4320   }
4321
4322   // fold (srl c1, c2) -> c1 >>u c2
4323   if (N0C && N1C)
4324     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4325   // fold (srl 0, x) -> 0
4326   if (N0C && N0C->isNullValue())
4327     return N0;
4328   // fold (srl x, c >= size(x)) -> undef
4329   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4330     return DAG.getUNDEF(VT);
4331   // fold (srl x, 0) -> x
4332   if (N1C && N1C->isNullValue())
4333     return N0;
4334   // if (srl x, c) is known to be zero, return 0
4335   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4336                                    APInt::getAllOnesValue(OpSizeInBits)))
4337     return DAG.getConstant(0, VT);
4338
4339   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4340   if (N1C && N0.getOpcode() == ISD::SRL) {
4341     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4342       uint64_t c1 = N01C->getZExtValue();
4343       uint64_t c2 = N1C->getZExtValue();
4344       if (c1 + c2 >= OpSizeInBits)
4345         return DAG.getConstant(0, VT);
4346       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4347                          DAG.getConstant(c1 + c2, N1.getValueType()));
4348     }
4349   }
4350
4351   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4352   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4353       N0.getOperand(0).getOpcode() == ISD::SRL &&
4354       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4355     uint64_t c1 =
4356       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4357     uint64_t c2 = N1C->getZExtValue();
4358     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4359     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4360     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4361     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4362     if (c1 + OpSizeInBits == InnerShiftSize) {
4363       if (c1 + c2 >= InnerShiftSize)
4364         return DAG.getConstant(0, VT);
4365       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4366                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4367                                      N0.getOperand(0)->getOperand(0),
4368                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4369     }
4370   }
4371
4372   // fold (srl (shl x, c), c) -> (and x, cst2)
4373   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4374     unsigned BitSize = N0.getScalarValueSizeInBits();
4375     if (BitSize <= 64) {
4376       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4377       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4378                          DAG.getConstant(~0ULL >> ShAmt, VT));
4379     }
4380   }
4381
4382   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4383   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4384     // Shifting in all undef bits?
4385     EVT SmallVT = N0.getOperand(0).getValueType();
4386     unsigned BitSize = SmallVT.getScalarSizeInBits();
4387     if (N1C->getZExtValue() >= BitSize)
4388       return DAG.getUNDEF(VT);
4389
4390     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4391       uint64_t ShiftAmt = N1C->getZExtValue();
4392       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4393                                        N0.getOperand(0),
4394                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4395       AddToWorklist(SmallShift.getNode());
4396       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4397       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4398                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4399                          DAG.getConstant(Mask, VT));
4400     }
4401   }
4402
4403   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4404   // bit, which is unmodified by sra.
4405   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4406     if (N0.getOpcode() == ISD::SRA)
4407       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4408   }
4409
4410   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4411   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4412       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4413     APInt KnownZero, KnownOne;
4414     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4415
4416     // If any of the input bits are KnownOne, then the input couldn't be all
4417     // zeros, thus the result of the srl will always be zero.
4418     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4419
4420     // If all of the bits input the to ctlz node are known to be zero, then
4421     // the result of the ctlz is "32" and the result of the shift is one.
4422     APInt UnknownBits = ~KnownZero;
4423     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4424
4425     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4426     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4427       // Okay, we know that only that the single bit specified by UnknownBits
4428       // could be set on input to the CTLZ node. If this bit is set, the SRL
4429       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4430       // to an SRL/XOR pair, which is likely to simplify more.
4431       unsigned ShAmt = UnknownBits.countTrailingZeros();
4432       SDValue Op = N0.getOperand(0);
4433
4434       if (ShAmt) {
4435         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4436                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4437         AddToWorklist(Op.getNode());
4438       }
4439
4440       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4441                          Op, DAG.getConstant(1, VT));
4442     }
4443   }
4444
4445   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4446   if (N1.getOpcode() == ISD::TRUNCATE &&
4447       N1.getOperand(0).getOpcode() == ISD::AND) {
4448     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4449     if (NewOp1.getNode())
4450       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4451   }
4452
4453   // fold operands of srl based on knowledge that the low bits are not
4454   // demanded.
4455   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4456     return SDValue(N, 0);
4457
4458   if (N1C) {
4459     SDValue NewSRL = visitShiftByConstant(N, N1C);
4460     if (NewSRL.getNode())
4461       return NewSRL;
4462   }
4463
4464   // Attempt to convert a srl of a load into a narrower zero-extending load.
4465   SDValue NarrowLoad = ReduceLoadWidth(N);
4466   if (NarrowLoad.getNode())
4467     return NarrowLoad;
4468
4469   // Here is a common situation. We want to optimize:
4470   //
4471   //   %a = ...
4472   //   %b = and i32 %a, 2
4473   //   %c = srl i32 %b, 1
4474   //   brcond i32 %c ...
4475   //
4476   // into
4477   //
4478   //   %a = ...
4479   //   %b = and %a, 2
4480   //   %c = setcc eq %b, 0
4481   //   brcond %c ...
4482   //
4483   // However when after the source operand of SRL is optimized into AND, the SRL
4484   // itself may not be optimized further. Look for it and add the BRCOND into
4485   // the worklist.
4486   if (N->hasOneUse()) {
4487     SDNode *Use = *N->use_begin();
4488     if (Use->getOpcode() == ISD::BRCOND)
4489       AddToWorklist(Use);
4490     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4491       // Also look pass the truncate.
4492       Use = *Use->use_begin();
4493       if (Use->getOpcode() == ISD::BRCOND)
4494         AddToWorklist(Use);
4495     }
4496   }
4497
4498   return SDValue();
4499 }
4500
4501 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4502   SDValue N0 = N->getOperand(0);
4503   EVT VT = N->getValueType(0);
4504
4505   // fold (ctlz c1) -> c2
4506   if (isa<ConstantSDNode>(N0))
4507     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4508   return SDValue();
4509 }
4510
4511 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4512   SDValue N0 = N->getOperand(0);
4513   EVT VT = N->getValueType(0);
4514
4515   // fold (ctlz_zero_undef c1) -> c2
4516   if (isa<ConstantSDNode>(N0))
4517     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4518   return SDValue();
4519 }
4520
4521 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4522   SDValue N0 = N->getOperand(0);
4523   EVT VT = N->getValueType(0);
4524
4525   // fold (cttz c1) -> c2
4526   if (isa<ConstantSDNode>(N0))
4527     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4528   return SDValue();
4529 }
4530
4531 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4532   SDValue N0 = N->getOperand(0);
4533   EVT VT = N->getValueType(0);
4534
4535   // fold (cttz_zero_undef c1) -> c2
4536   if (isa<ConstantSDNode>(N0))
4537     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4538   return SDValue();
4539 }
4540
4541 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4542   SDValue N0 = N->getOperand(0);
4543   EVT VT = N->getValueType(0);
4544
4545   // fold (ctpop c1) -> c2
4546   if (isa<ConstantSDNode>(N0))
4547     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4548   return SDValue();
4549 }
4550
4551 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4552   SDValue N0 = N->getOperand(0);
4553   SDValue N1 = N->getOperand(1);
4554   SDValue N2 = N->getOperand(2);
4555   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4556   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4557   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4558   EVT VT = N->getValueType(0);
4559   EVT VT0 = N0.getValueType();
4560
4561   // fold (select C, X, X) -> X
4562   if (N1 == N2)
4563     return N1;
4564   // fold (select true, X, Y) -> X
4565   if (N0C && !N0C->isNullValue())
4566     return N1;
4567   // fold (select false, X, Y) -> Y
4568   if (N0C && N0C->isNullValue())
4569     return N2;
4570   // fold (select C, 1, X) -> (or C, X)
4571   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4572     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4573   // fold (select C, 0, 1) -> (xor C, 1)
4574   // We can't do this reliably if integer based booleans have different contents
4575   // to floating point based booleans. This is because we can't tell whether we
4576   // have an integer-based boolean or a floating-point-based boolean unless we
4577   // can find the SETCC that produced it and inspect its operands. This is
4578   // fairly easy if C is the SETCC node, but it can potentially be
4579   // undiscoverable (or not reasonably discoverable). For example, it could be
4580   // in another basic block or it could require searching a complicated
4581   // expression.
4582   if (VT.isInteger() &&
4583       (VT0 == MVT::i1 || (VT0.isInteger() &&
4584                           TLI.getBooleanContents(false, false) ==
4585                               TLI.getBooleanContents(false, true) &&
4586                           TLI.getBooleanContents(false, false) ==
4587                               TargetLowering::ZeroOrOneBooleanContent)) &&
4588       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4589     SDValue XORNode;
4590     if (VT == VT0)
4591       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4592                          N0, DAG.getConstant(1, VT0));
4593     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4594                           N0, DAG.getConstant(1, VT0));
4595     AddToWorklist(XORNode.getNode());
4596     if (VT.bitsGT(VT0))
4597       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4598     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4599   }
4600   // fold (select C, 0, X) -> (and (not C), X)
4601   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4602     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4603     AddToWorklist(NOTNode.getNode());
4604     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4605   }
4606   // fold (select C, X, 1) -> (or (not C), X)
4607   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4608     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4609     AddToWorklist(NOTNode.getNode());
4610     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4611   }
4612   // fold (select C, X, 0) -> (and C, X)
4613   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4614     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4615   // fold (select X, X, Y) -> (or X, Y)
4616   // fold (select X, 1, Y) -> (or X, Y)
4617   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4618     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4619   // fold (select X, Y, X) -> (and X, Y)
4620   // fold (select X, Y, 0) -> (and X, Y)
4621   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4622     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4623
4624   // If we can fold this based on the true/false value, do so.
4625   if (SimplifySelectOps(N, N1, N2))
4626     return SDValue(N, 0);  // Don't revisit N.
4627
4628   // fold selects based on a setcc into other things, such as min/max/abs
4629   if (N0.getOpcode() == ISD::SETCC) {
4630     if ((!LegalOperations &&
4631          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4632         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4633       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4634                          N0.getOperand(0), N0.getOperand(1),
4635                          N1, N2, N0.getOperand(2));
4636     return SimplifySelect(SDLoc(N), N0, N1, N2);
4637   }
4638
4639   return SDValue();
4640 }
4641
4642 static
4643 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4644   SDLoc DL(N);
4645   EVT LoVT, HiVT;
4646   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4647
4648   // Split the inputs.
4649   SDValue Lo, Hi, LL, LH, RL, RH;
4650   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4651   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4652
4653   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4654   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4655
4656   return std::make_pair(Lo, Hi);
4657 }
4658
4659 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4660 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4661 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4662   SDLoc dl(N);
4663   SDValue Cond = N->getOperand(0);
4664   SDValue LHS = N->getOperand(1);
4665   SDValue RHS = N->getOperand(2);
4666   MVT VT = N->getSimpleValueType(0);
4667   int NumElems = VT.getVectorNumElements();
4668   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4669          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4670          Cond.getOpcode() == ISD::BUILD_VECTOR);
4671
4672   // We're sure we have an even number of elements due to the
4673   // concat_vectors we have as arguments to vselect.
4674   // Skip BV elements until we find one that's not an UNDEF
4675   // After we find an UNDEF element, keep looping until we get to half the
4676   // length of the BV and see if all the non-undef nodes are the same.
4677   ConstantSDNode *BottomHalf = nullptr;
4678   for (int i = 0; i < NumElems / 2; ++i) {
4679     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4680       continue;
4681
4682     if (BottomHalf == nullptr)
4683       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4684     else if (Cond->getOperand(i).getNode() != BottomHalf)
4685       return SDValue();
4686   }
4687
4688   // Do the same for the second half of the BuildVector
4689   ConstantSDNode *TopHalf = nullptr;
4690   for (int i = NumElems / 2; i < NumElems; ++i) {
4691     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4692       continue;
4693
4694     if (TopHalf == nullptr)
4695       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4696     else if (Cond->getOperand(i).getNode() != TopHalf)
4697       return SDValue();
4698   }
4699
4700   assert(TopHalf && BottomHalf &&
4701          "One half of the selector was all UNDEFs and the other was all the "
4702          "same value. This should have been addressed before this function.");
4703   return DAG.getNode(
4704       ISD::CONCAT_VECTORS, dl, VT,
4705       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4706       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4707 }
4708
4709 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4710   SDValue N0 = N->getOperand(0);
4711   SDValue N1 = N->getOperand(1);
4712   SDValue N2 = N->getOperand(2);
4713   SDLoc DL(N);
4714
4715   // Canonicalize integer abs.
4716   // vselect (setg[te] X,  0),  X, -X ->
4717   // vselect (setgt    X, -1),  X, -X ->
4718   // vselect (setl[te] X,  0), -X,  X ->
4719   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4720   if (N0.getOpcode() == ISD::SETCC) {
4721     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4722     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4723     bool isAbs = false;
4724     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4725
4726     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4727          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4728         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4729       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4730     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4731              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4732       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4733
4734     if (isAbs) {
4735       EVT VT = LHS.getValueType();
4736       SDValue Shift = DAG.getNode(
4737           ISD::SRA, DL, VT, LHS,
4738           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4739       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4740       AddToWorklist(Shift.getNode());
4741       AddToWorklist(Add.getNode());
4742       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4743     }
4744   }
4745
4746   // If the VSELECT result requires splitting and the mask is provided by a
4747   // SETCC, then split both nodes and its operands before legalization. This
4748   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4749   // and enables future optimizations (e.g. min/max pattern matching on X86).
4750   if (N0.getOpcode() == ISD::SETCC) {
4751     EVT VT = N->getValueType(0);
4752
4753     // Check if any splitting is required.
4754     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4755         TargetLowering::TypeSplitVector)
4756       return SDValue();
4757
4758     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4759     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4760     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4761     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4762
4763     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4764     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4765
4766     // Add the new VSELECT nodes to the work list in case they need to be split
4767     // again.
4768     AddToWorklist(Lo.getNode());
4769     AddToWorklist(Hi.getNode());
4770
4771     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4772   }
4773
4774   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4775   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4776     return N1;
4777   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4778   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4779     return N2;
4780
4781   // The ConvertSelectToConcatVector function is assuming both the above
4782   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4783   // and addressed.
4784   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4785       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4786       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4787     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4788     if (CV.getNode())
4789       return CV;
4790   }
4791
4792   return SDValue();
4793 }
4794
4795 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4796   SDValue N0 = N->getOperand(0);
4797   SDValue N1 = N->getOperand(1);
4798   SDValue N2 = N->getOperand(2);
4799   SDValue N3 = N->getOperand(3);
4800   SDValue N4 = N->getOperand(4);
4801   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4802
4803   // fold select_cc lhs, rhs, x, x, cc -> x
4804   if (N2 == N3)
4805     return N2;
4806
4807   // Determine if the condition we're dealing with is constant
4808   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4809                               N0, N1, CC, SDLoc(N), false);
4810   if (SCC.getNode()) {
4811     AddToWorklist(SCC.getNode());
4812
4813     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4814       if (!SCCC->isNullValue())
4815         return N2;    // cond always true -> true val
4816       else
4817         return N3;    // cond always false -> false val
4818     }
4819
4820     // Fold to a simpler select_cc
4821     if (SCC.getOpcode() == ISD::SETCC)
4822       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4823                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4824                          SCC.getOperand(2));
4825   }
4826
4827   // If we can fold this based on the true/false value, do so.
4828   if (SimplifySelectOps(N, N2, N3))
4829     return SDValue(N, 0);  // Don't revisit N.
4830
4831   // fold select_cc into other things, such as min/max/abs
4832   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4833 }
4834
4835 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4836   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4837                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4838                        SDLoc(N));
4839 }
4840
4841 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4842 // dag node into a ConstantSDNode or a build_vector of constants.
4843 // This function is called by the DAGCombiner when visiting sext/zext/aext
4844 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4845 // Vector extends are not folded if operations are legal; this is to
4846 // avoid introducing illegal build_vector dag nodes.
4847 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4848                                          SelectionDAG &DAG, bool LegalTypes,
4849                                          bool LegalOperations) {
4850   unsigned Opcode = N->getOpcode();
4851   SDValue N0 = N->getOperand(0);
4852   EVT VT = N->getValueType(0);
4853
4854   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4855          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4856
4857   // fold (sext c1) -> c1
4858   // fold (zext c1) -> c1
4859   // fold (aext c1) -> c1
4860   if (isa<ConstantSDNode>(N0))
4861     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4862
4863   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4864   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4865   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4866   EVT SVT = VT.getScalarType();
4867   if (!(VT.isVector() &&
4868       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4869       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4870     return nullptr;
4871
4872   // We can fold this node into a build_vector.
4873   unsigned VTBits = SVT.getSizeInBits();
4874   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4875   unsigned ShAmt = VTBits - EVTBits;
4876   SmallVector<SDValue, 8> Elts;
4877   unsigned NumElts = N0->getNumOperands();
4878   SDLoc DL(N);
4879
4880   for (unsigned i=0; i != NumElts; ++i) {
4881     SDValue Op = N0->getOperand(i);
4882     if (Op->getOpcode() == ISD::UNDEF) {
4883       Elts.push_back(DAG.getUNDEF(SVT));
4884       continue;
4885     }
4886
4887     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4888     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4889     if (Opcode == ISD::SIGN_EXTEND)
4890       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4891                                      SVT));
4892     else
4893       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4894                                      SVT));
4895   }
4896
4897   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4898 }
4899
4900 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4901 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4902 // transformation. Returns true if extension are possible and the above
4903 // mentioned transformation is profitable.
4904 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4905                                     unsigned ExtOpc,
4906                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4907                                     const TargetLowering &TLI) {
4908   bool HasCopyToRegUses = false;
4909   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4910   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4911                             UE = N0.getNode()->use_end();
4912        UI != UE; ++UI) {
4913     SDNode *User = *UI;
4914     if (User == N)
4915       continue;
4916     if (UI.getUse().getResNo() != N0.getResNo())
4917       continue;
4918     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4919     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4920       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4921       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4922         // Sign bits will be lost after a zext.
4923         return false;
4924       bool Add = false;
4925       for (unsigned i = 0; i != 2; ++i) {
4926         SDValue UseOp = User->getOperand(i);
4927         if (UseOp == N0)
4928           continue;
4929         if (!isa<ConstantSDNode>(UseOp))
4930           return false;
4931         Add = true;
4932       }
4933       if (Add)
4934         ExtendNodes.push_back(User);
4935       continue;
4936     }
4937     // If truncates aren't free and there are users we can't
4938     // extend, it isn't worthwhile.
4939     if (!isTruncFree)
4940       return false;
4941     // Remember if this value is live-out.
4942     if (User->getOpcode() == ISD::CopyToReg)
4943       HasCopyToRegUses = true;
4944   }
4945
4946   if (HasCopyToRegUses) {
4947     bool BothLiveOut = false;
4948     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4949          UI != UE; ++UI) {
4950       SDUse &Use = UI.getUse();
4951       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4952         BothLiveOut = true;
4953         break;
4954       }
4955     }
4956     if (BothLiveOut)
4957       // Both unextended and extended values are live out. There had better be
4958       // a good reason for the transformation.
4959       return ExtendNodes.size();
4960   }
4961   return true;
4962 }
4963
4964 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4965                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4966                                   ISD::NodeType ExtType) {
4967   // Extend SetCC uses if necessary.
4968   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4969     SDNode *SetCC = SetCCs[i];
4970     SmallVector<SDValue, 4> Ops;
4971
4972     for (unsigned j = 0; j != 2; ++j) {
4973       SDValue SOp = SetCC->getOperand(j);
4974       if (SOp == Trunc)
4975         Ops.push_back(ExtLoad);
4976       else
4977         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4978     }
4979
4980     Ops.push_back(SetCC->getOperand(2));
4981     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4982   }
4983 }
4984
4985 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4986   SDValue N0 = N->getOperand(0);
4987   EVT VT = N->getValueType(0);
4988
4989   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4990                                               LegalOperations))
4991     return SDValue(Res, 0);
4992
4993   // fold (sext (sext x)) -> (sext x)
4994   // fold (sext (aext x)) -> (sext x)
4995   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4996     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4997                        N0.getOperand(0));
4998
4999   if (N0.getOpcode() == ISD::TRUNCATE) {
5000     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5001     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5002     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5003     if (NarrowLoad.getNode()) {
5004       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5005       if (NarrowLoad.getNode() != N0.getNode()) {
5006         CombineTo(N0.getNode(), NarrowLoad);
5007         // CombineTo deleted the truncate, if needed, but not what's under it.
5008         AddToWorklist(oye);
5009       }
5010       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5011     }
5012
5013     // See if the value being truncated is already sign extended.  If so, just
5014     // eliminate the trunc/sext pair.
5015     SDValue Op = N0.getOperand(0);
5016     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5017     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5018     unsigned DestBits = VT.getScalarType().getSizeInBits();
5019     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5020
5021     if (OpBits == DestBits) {
5022       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5023       // bits, it is already ready.
5024       if (NumSignBits > DestBits-MidBits)
5025         return Op;
5026     } else if (OpBits < DestBits) {
5027       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5028       // bits, just sext from i32.
5029       if (NumSignBits > OpBits-MidBits)
5030         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5031     } else {
5032       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5033       // bits, just truncate to i32.
5034       if (NumSignBits > OpBits-MidBits)
5035         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5036     }
5037
5038     // fold (sext (truncate x)) -> (sextinreg x).
5039     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5040                                                  N0.getValueType())) {
5041       if (OpBits < DestBits)
5042         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5043       else if (OpBits > DestBits)
5044         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5045       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5046                          DAG.getValueType(N0.getValueType()));
5047     }
5048   }
5049
5050   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5051   // None of the supported targets knows how to perform load and sign extend
5052   // on vectors in one instruction.  We only perform this transformation on
5053   // scalars.
5054   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5055       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5056       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5057        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5058     bool DoXform = true;
5059     SmallVector<SDNode*, 4> SetCCs;
5060     if (!N0.hasOneUse())
5061       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5062     if (DoXform) {
5063       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5064       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5065                                        LN0->getChain(),
5066                                        LN0->getBasePtr(), N0.getValueType(),
5067                                        LN0->getMemOperand());
5068       CombineTo(N, ExtLoad);
5069       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5070                                   N0.getValueType(), ExtLoad);
5071       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5072       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5073                       ISD::SIGN_EXTEND);
5074       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5075     }
5076   }
5077
5078   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5079   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5080   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5081       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5082     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5083     EVT MemVT = LN0->getMemoryVT();
5084     if ((!LegalOperations && !LN0->isVolatile()) ||
5085         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5086       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5087                                        LN0->getChain(),
5088                                        LN0->getBasePtr(), MemVT,
5089                                        LN0->getMemOperand());
5090       CombineTo(N, ExtLoad);
5091       CombineTo(N0.getNode(),
5092                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5093                             N0.getValueType(), ExtLoad),
5094                 ExtLoad.getValue(1));
5095       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5096     }
5097   }
5098
5099   // fold (sext (and/or/xor (load x), cst)) ->
5100   //      (and/or/xor (sextload x), (sext cst))
5101   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5102        N0.getOpcode() == ISD::XOR) &&
5103       isa<LoadSDNode>(N0.getOperand(0)) &&
5104       N0.getOperand(1).getOpcode() == ISD::Constant &&
5105       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5106       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5107     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5108     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5109       bool DoXform = true;
5110       SmallVector<SDNode*, 4> SetCCs;
5111       if (!N0.hasOneUse())
5112         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5113                                           SetCCs, TLI);
5114       if (DoXform) {
5115         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5116                                          LN0->getChain(), LN0->getBasePtr(),
5117                                          LN0->getMemoryVT(),
5118                                          LN0->getMemOperand());
5119         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5120         Mask = Mask.sext(VT.getSizeInBits());
5121         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5122                                   ExtLoad, DAG.getConstant(Mask, VT));
5123         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5124                                     SDLoc(N0.getOperand(0)),
5125                                     N0.getOperand(0).getValueType(), ExtLoad);
5126         CombineTo(N, And);
5127         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5128         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5129                         ISD::SIGN_EXTEND);
5130         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5131       }
5132     }
5133   }
5134
5135   if (N0.getOpcode() == ISD::SETCC) {
5136     EVT N0VT = N0.getOperand(0).getValueType();
5137     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5138     // Only do this before legalize for now.
5139     if (VT.isVector() && !LegalOperations &&
5140         TLI.getBooleanContents(N0VT) ==
5141             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5142       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5143       // of the same size as the compared operands. Only optimize sext(setcc())
5144       // if this is the case.
5145       EVT SVT = getSetCCResultType(N0VT);
5146
5147       // We know that the # elements of the results is the same as the
5148       // # elements of the compare (and the # elements of the compare result
5149       // for that matter).  Check to see that they are the same size.  If so,
5150       // we know that the element size of the sext'd result matches the
5151       // element size of the compare operands.
5152       if (VT.getSizeInBits() == SVT.getSizeInBits())
5153         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5154                              N0.getOperand(1),
5155                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5156
5157       // If the desired elements are smaller or larger than the source
5158       // elements we can use a matching integer vector type and then
5159       // truncate/sign extend
5160       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5161       if (SVT == MatchingVectorType) {
5162         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5163                                N0.getOperand(0), N0.getOperand(1),
5164                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5165         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5166       }
5167     }
5168
5169     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5170     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5171     SDValue NegOne =
5172       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5173     SDValue SCC =
5174       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5175                        NegOne, DAG.getConstant(0, VT),
5176                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5177     if (SCC.getNode()) return SCC;
5178
5179     if (!VT.isVector()) {
5180       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5181       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5182         SDLoc DL(N);
5183         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5184         SDValue SetCC = DAG.getSetCC(DL,
5185                                      SetCCVT,
5186                                      N0.getOperand(0), N0.getOperand(1), CC);
5187         EVT SelectVT = getSetCCResultType(VT);
5188         return DAG.getSelect(DL, VT,
5189                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5190                              NegOne, DAG.getConstant(0, VT));
5191
5192       }
5193     }
5194   }
5195
5196   // fold (sext x) -> (zext x) if the sign bit is known zero.
5197   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5198       DAG.SignBitIsZero(N0))
5199     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5200
5201   return SDValue();
5202 }
5203
5204 // isTruncateOf - If N is a truncate of some other value, return true, record
5205 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5206 // This function computes KnownZero to avoid a duplicated call to
5207 // computeKnownBits in the caller.
5208 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5209                          APInt &KnownZero) {
5210   APInt KnownOne;
5211   if (N->getOpcode() == ISD::TRUNCATE) {
5212     Op = N->getOperand(0);
5213     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5214     return true;
5215   }
5216
5217   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5218       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5219     return false;
5220
5221   SDValue Op0 = N->getOperand(0);
5222   SDValue Op1 = N->getOperand(1);
5223   assert(Op0.getValueType() == Op1.getValueType());
5224
5225   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5226   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5227   if (COp0 && COp0->isNullValue())
5228     Op = Op1;
5229   else if (COp1 && COp1->isNullValue())
5230     Op = Op0;
5231   else
5232     return false;
5233
5234   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5235
5236   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5237     return false;
5238
5239   return true;
5240 }
5241
5242 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5243   SDValue N0 = N->getOperand(0);
5244   EVT VT = N->getValueType(0);
5245
5246   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5247                                               LegalOperations))
5248     return SDValue(Res, 0);
5249
5250   // fold (zext (zext x)) -> (zext x)
5251   // fold (zext (aext x)) -> (zext x)
5252   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5253     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5254                        N0.getOperand(0));
5255
5256   // fold (zext (truncate x)) -> (zext x) or
5257   //      (zext (truncate x)) -> (truncate x)
5258   // This is valid when the truncated bits of x are already zero.
5259   // FIXME: We should extend this to work for vectors too.
5260   SDValue Op;
5261   APInt KnownZero;
5262   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5263     APInt TruncatedBits =
5264       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5265       APInt(Op.getValueSizeInBits(), 0) :
5266       APInt::getBitsSet(Op.getValueSizeInBits(),
5267                         N0.getValueSizeInBits(),
5268                         std::min(Op.getValueSizeInBits(),
5269                                  VT.getSizeInBits()));
5270     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5271       if (VT.bitsGT(Op.getValueType()))
5272         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5273       if (VT.bitsLT(Op.getValueType()))
5274         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5275
5276       return Op;
5277     }
5278   }
5279
5280   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5281   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5282   if (N0.getOpcode() == ISD::TRUNCATE) {
5283     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5284     if (NarrowLoad.getNode()) {
5285       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5286       if (NarrowLoad.getNode() != N0.getNode()) {
5287         CombineTo(N0.getNode(), NarrowLoad);
5288         // CombineTo deleted the truncate, if needed, but not what's under it.
5289         AddToWorklist(oye);
5290       }
5291       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5292     }
5293   }
5294
5295   // fold (zext (truncate x)) -> (and x, mask)
5296   if (N0.getOpcode() == ISD::TRUNCATE &&
5297       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5298
5299     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5300     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5301     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5302     if (NarrowLoad.getNode()) {
5303       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5304       if (NarrowLoad.getNode() != N0.getNode()) {
5305         CombineTo(N0.getNode(), NarrowLoad);
5306         // CombineTo deleted the truncate, if needed, but not what's under it.
5307         AddToWorklist(oye);
5308       }
5309       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5310     }
5311
5312     SDValue Op = N0.getOperand(0);
5313     if (Op.getValueType().bitsLT(VT)) {
5314       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5315       AddToWorklist(Op.getNode());
5316     } else if (Op.getValueType().bitsGT(VT)) {
5317       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5318       AddToWorklist(Op.getNode());
5319     }
5320     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5321                                   N0.getValueType().getScalarType());
5322   }
5323
5324   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5325   // if either of the casts is not free.
5326   if (N0.getOpcode() == ISD::AND &&
5327       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5328       N0.getOperand(1).getOpcode() == ISD::Constant &&
5329       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5330                            N0.getValueType()) ||
5331        !TLI.isZExtFree(N0.getValueType(), VT))) {
5332     SDValue X = N0.getOperand(0).getOperand(0);
5333     if (X.getValueType().bitsLT(VT)) {
5334       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5335     } else if (X.getValueType().bitsGT(VT)) {
5336       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5337     }
5338     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5339     Mask = Mask.zext(VT.getSizeInBits());
5340     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5341                        X, DAG.getConstant(Mask, VT));
5342   }
5343
5344   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5345   // None of the supported targets knows how to perform load and vector_zext
5346   // on vectors in one instruction.  We only perform this transformation on
5347   // scalars.
5348   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5349       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5350       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5351        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5352     bool DoXform = true;
5353     SmallVector<SDNode*, 4> SetCCs;
5354     if (!N0.hasOneUse())
5355       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5356     if (DoXform) {
5357       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5358       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5359                                        LN0->getChain(),
5360                                        LN0->getBasePtr(), N0.getValueType(),
5361                                        LN0->getMemOperand());
5362       CombineTo(N, ExtLoad);
5363       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5364                                   N0.getValueType(), ExtLoad);
5365       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5366
5367       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5368                       ISD::ZERO_EXTEND);
5369       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5370     }
5371   }
5372
5373   // fold (zext (and/or/xor (load x), cst)) ->
5374   //      (and/or/xor (zextload x), (zext cst))
5375   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5376        N0.getOpcode() == ISD::XOR) &&
5377       isa<LoadSDNode>(N0.getOperand(0)) &&
5378       N0.getOperand(1).getOpcode() == ISD::Constant &&
5379       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5380       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5381     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5382     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5383       bool DoXform = true;
5384       SmallVector<SDNode*, 4> SetCCs;
5385       if (!N0.hasOneUse())
5386         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5387                                           SetCCs, TLI);
5388       if (DoXform) {
5389         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5390                                          LN0->getChain(), LN0->getBasePtr(),
5391                                          LN0->getMemoryVT(),
5392                                          LN0->getMemOperand());
5393         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5394         Mask = Mask.zext(VT.getSizeInBits());
5395         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5396                                   ExtLoad, DAG.getConstant(Mask, VT));
5397         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5398                                     SDLoc(N0.getOperand(0)),
5399                                     N0.getOperand(0).getValueType(), ExtLoad);
5400         CombineTo(N, And);
5401         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5402         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5403                         ISD::ZERO_EXTEND);
5404         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5405       }
5406     }
5407   }
5408
5409   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5410   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5411   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5412       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5413     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5414     EVT MemVT = LN0->getMemoryVT();
5415     if ((!LegalOperations && !LN0->isVolatile()) ||
5416         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5417       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5418                                        LN0->getChain(),
5419                                        LN0->getBasePtr(), MemVT,
5420                                        LN0->getMemOperand());
5421       CombineTo(N, ExtLoad);
5422       CombineTo(N0.getNode(),
5423                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5424                             ExtLoad),
5425                 ExtLoad.getValue(1));
5426       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5427     }
5428   }
5429
5430   if (N0.getOpcode() == ISD::SETCC) {
5431     if (!LegalOperations && VT.isVector() &&
5432         N0.getValueType().getVectorElementType() == MVT::i1) {
5433       EVT N0VT = N0.getOperand(0).getValueType();
5434       if (getSetCCResultType(N0VT) == N0.getValueType())
5435         return SDValue();
5436
5437       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5438       // Only do this before legalize for now.
5439       EVT EltVT = VT.getVectorElementType();
5440       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5441                                     DAG.getConstant(1, EltVT));
5442       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5443         // We know that the # elements of the results is the same as the
5444         // # elements of the compare (and the # elements of the compare result
5445         // for that matter).  Check to see that they are the same size.  If so,
5446         // we know that the element size of the sext'd result matches the
5447         // element size of the compare operands.
5448         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5449                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5450                                          N0.getOperand(1),
5451                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5452                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5453                                        OneOps));
5454
5455       // If the desired elements are smaller or larger than the source
5456       // elements we can use a matching integer vector type and then
5457       // truncate/sign extend
5458       EVT MatchingElementType =
5459         EVT::getIntegerVT(*DAG.getContext(),
5460                           N0VT.getScalarType().getSizeInBits());
5461       EVT MatchingVectorType =
5462         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5463                          N0VT.getVectorNumElements());
5464       SDValue VsetCC =
5465         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5466                       N0.getOperand(1),
5467                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5468       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5469                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5470                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5471     }
5472
5473     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5474     SDValue SCC =
5475       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5476                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5477                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5478     if (SCC.getNode()) return SCC;
5479   }
5480
5481   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5482   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5483       isa<ConstantSDNode>(N0.getOperand(1)) &&
5484       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5485       N0.hasOneUse()) {
5486     SDValue ShAmt = N0.getOperand(1);
5487     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5488     if (N0.getOpcode() == ISD::SHL) {
5489       SDValue InnerZExt = N0.getOperand(0);
5490       // If the original shl may be shifting out bits, do not perform this
5491       // transformation.
5492       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5493         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5494       if (ShAmtVal > KnownZeroBits)
5495         return SDValue();
5496     }
5497
5498     SDLoc DL(N);
5499
5500     // Ensure that the shift amount is wide enough for the shifted value.
5501     if (VT.getSizeInBits() >= 256)
5502       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5503
5504     return DAG.getNode(N0.getOpcode(), DL, VT,
5505                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5506                        ShAmt);
5507   }
5508
5509   return SDValue();
5510 }
5511
5512 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5513   SDValue N0 = N->getOperand(0);
5514   EVT VT = N->getValueType(0);
5515
5516   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5517                                               LegalOperations))
5518     return SDValue(Res, 0);
5519
5520   // fold (aext (aext x)) -> (aext x)
5521   // fold (aext (zext x)) -> (zext x)
5522   // fold (aext (sext x)) -> (sext x)
5523   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5524       N0.getOpcode() == ISD::ZERO_EXTEND ||
5525       N0.getOpcode() == ISD::SIGN_EXTEND)
5526     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5527
5528   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5529   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5530   if (N0.getOpcode() == ISD::TRUNCATE) {
5531     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5532     if (NarrowLoad.getNode()) {
5533       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5534       if (NarrowLoad.getNode() != N0.getNode()) {
5535         CombineTo(N0.getNode(), NarrowLoad);
5536         // CombineTo deleted the truncate, if needed, but not what's under it.
5537         AddToWorklist(oye);
5538       }
5539       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5540     }
5541   }
5542
5543   // fold (aext (truncate x))
5544   if (N0.getOpcode() == ISD::TRUNCATE) {
5545     SDValue TruncOp = N0.getOperand(0);
5546     if (TruncOp.getValueType() == VT)
5547       return TruncOp; // x iff x size == zext size.
5548     if (TruncOp.getValueType().bitsGT(VT))
5549       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5550     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5551   }
5552
5553   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5554   // if the trunc is not free.
5555   if (N0.getOpcode() == ISD::AND &&
5556       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5557       N0.getOperand(1).getOpcode() == ISD::Constant &&
5558       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5559                           N0.getValueType())) {
5560     SDValue X = N0.getOperand(0).getOperand(0);
5561     if (X.getValueType().bitsLT(VT)) {
5562       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5563     } else if (X.getValueType().bitsGT(VT)) {
5564       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5565     }
5566     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5567     Mask = Mask.zext(VT.getSizeInBits());
5568     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5569                        X, DAG.getConstant(Mask, VT));
5570   }
5571
5572   // fold (aext (load x)) -> (aext (truncate (extload x)))
5573   // None of the supported targets knows how to perform load and any_ext
5574   // on vectors in one instruction.  We only perform this transformation on
5575   // scalars.
5576   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5577       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5578       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5579     bool DoXform = true;
5580     SmallVector<SDNode*, 4> SetCCs;
5581     if (!N0.hasOneUse())
5582       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5583     if (DoXform) {
5584       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5585       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5586                                        LN0->getChain(),
5587                                        LN0->getBasePtr(), N0.getValueType(),
5588                                        LN0->getMemOperand());
5589       CombineTo(N, ExtLoad);
5590       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5591                                   N0.getValueType(), ExtLoad);
5592       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5593       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5594                       ISD::ANY_EXTEND);
5595       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5596     }
5597   }
5598
5599   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5600   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5601   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5602   if (N0.getOpcode() == ISD::LOAD &&
5603       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5604       N0.hasOneUse()) {
5605     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5606     ISD::LoadExtType ExtType = LN0->getExtensionType();
5607     EVT MemVT = LN0->getMemoryVT();
5608     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5609       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5610                                        VT, LN0->getChain(), LN0->getBasePtr(),
5611                                        MemVT, LN0->getMemOperand());
5612       CombineTo(N, ExtLoad);
5613       CombineTo(N0.getNode(),
5614                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5615                             N0.getValueType(), ExtLoad),
5616                 ExtLoad.getValue(1));
5617       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5618     }
5619   }
5620
5621   if (N0.getOpcode() == ISD::SETCC) {
5622     // For vectors:
5623     // aext(setcc) -> vsetcc
5624     // aext(setcc) -> truncate(vsetcc)
5625     // aext(setcc) -> aext(vsetcc)
5626     // Only do this before legalize for now.
5627     if (VT.isVector() && !LegalOperations) {
5628       EVT N0VT = N0.getOperand(0).getValueType();
5629         // We know that the # elements of the results is the same as the
5630         // # elements of the compare (and the # elements of the compare result
5631         // for that matter).  Check to see that they are the same size.  If so,
5632         // we know that the element size of the sext'd result matches the
5633         // element size of the compare operands.
5634       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5635         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5636                              N0.getOperand(1),
5637                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5638       // If the desired elements are smaller or larger than the source
5639       // elements we can use a matching integer vector type and then
5640       // truncate/any extend
5641       else {
5642         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5643         SDValue VsetCC =
5644           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5645                         N0.getOperand(1),
5646                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5647         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5648       }
5649     }
5650
5651     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5652     SDValue SCC =
5653       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5654                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5655                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5656     if (SCC.getNode())
5657       return SCC;
5658   }
5659
5660   return SDValue();
5661 }
5662
5663 /// GetDemandedBits - See if the specified operand can be simplified with the
5664 /// knowledge that only the bits specified by Mask are used.  If so, return the
5665 /// simpler operand, otherwise return a null SDValue.
5666 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5667   switch (V.getOpcode()) {
5668   default: break;
5669   case ISD::Constant: {
5670     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5671     assert(CV && "Const value should be ConstSDNode.");
5672     const APInt &CVal = CV->getAPIntValue();
5673     APInt NewVal = CVal & Mask;
5674     if (NewVal != CVal)
5675       return DAG.getConstant(NewVal, V.getValueType());
5676     break;
5677   }
5678   case ISD::OR:
5679   case ISD::XOR:
5680     // If the LHS or RHS don't contribute bits to the or, drop them.
5681     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5682       return V.getOperand(1);
5683     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5684       return V.getOperand(0);
5685     break;
5686   case ISD::SRL:
5687     // Only look at single-use SRLs.
5688     if (!V.getNode()->hasOneUse())
5689       break;
5690     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5691       // See if we can recursively simplify the LHS.
5692       unsigned Amt = RHSC->getZExtValue();
5693
5694       // Watch out for shift count overflow though.
5695       if (Amt >= Mask.getBitWidth()) break;
5696       APInt NewMask = Mask << Amt;
5697       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5698       if (SimplifyLHS.getNode())
5699         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5700                            SimplifyLHS, V.getOperand(1));
5701     }
5702   }
5703   return SDValue();
5704 }
5705
5706 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5707 /// bits and then truncated to a narrower type and where N is a multiple
5708 /// of number of bits of the narrower type, transform it to a narrower load
5709 /// from address + N / num of bits of new type. If the result is to be
5710 /// extended, also fold the extension to form a extending load.
5711 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5712   unsigned Opc = N->getOpcode();
5713
5714   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5715   SDValue N0 = N->getOperand(0);
5716   EVT VT = N->getValueType(0);
5717   EVT ExtVT = VT;
5718
5719   // This transformation isn't valid for vector loads.
5720   if (VT.isVector())
5721     return SDValue();
5722
5723   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5724   // extended to VT.
5725   if (Opc == ISD::SIGN_EXTEND_INREG) {
5726     ExtType = ISD::SEXTLOAD;
5727     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5728   } else if (Opc == ISD::SRL) {
5729     // Another special-case: SRL is basically zero-extending a narrower value.
5730     ExtType = ISD::ZEXTLOAD;
5731     N0 = SDValue(N, 0);
5732     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5733     if (!N01) return SDValue();
5734     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5735                               VT.getSizeInBits() - N01->getZExtValue());
5736   }
5737   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5738     return SDValue();
5739
5740   unsigned EVTBits = ExtVT.getSizeInBits();
5741
5742   // Do not generate loads of non-round integer types since these can
5743   // be expensive (and would be wrong if the type is not byte sized).
5744   if (!ExtVT.isRound())
5745     return SDValue();
5746
5747   unsigned ShAmt = 0;
5748   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5749     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5750       ShAmt = N01->getZExtValue();
5751       // Is the shift amount a multiple of size of VT?
5752       if ((ShAmt & (EVTBits-1)) == 0) {
5753         N0 = N0.getOperand(0);
5754         // Is the load width a multiple of size of VT?
5755         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5756           return SDValue();
5757       }
5758
5759       // At this point, we must have a load or else we can't do the transform.
5760       if (!isa<LoadSDNode>(N0)) return SDValue();
5761
5762       // Because a SRL must be assumed to *need* to zero-extend the high bits
5763       // (as opposed to anyext the high bits), we can't combine the zextload
5764       // lowering of SRL and an sextload.
5765       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5766         return SDValue();
5767
5768       // If the shift amount is larger than the input type then we're not
5769       // accessing any of the loaded bytes.  If the load was a zextload/extload
5770       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5771       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5772         return SDValue();
5773     }
5774   }
5775
5776   // If the load is shifted left (and the result isn't shifted back right),
5777   // we can fold the truncate through the shift.
5778   unsigned ShLeftAmt = 0;
5779   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5780       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5781     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5782       ShLeftAmt = N01->getZExtValue();
5783       N0 = N0.getOperand(0);
5784     }
5785   }
5786
5787   // If we haven't found a load, we can't narrow it.  Don't transform one with
5788   // multiple uses, this would require adding a new load.
5789   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5790     return SDValue();
5791
5792   // Don't change the width of a volatile load.
5793   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5794   if (LN0->isVolatile())
5795     return SDValue();
5796
5797   // Verify that we are actually reducing a load width here.
5798   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5799     return SDValue();
5800
5801   // For the transform to be legal, the load must produce only two values
5802   // (the value loaded and the chain).  Don't transform a pre-increment
5803   // load, for example, which produces an extra value.  Otherwise the
5804   // transformation is not equivalent, and the downstream logic to replace
5805   // uses gets things wrong.
5806   if (LN0->getNumValues() > 2)
5807     return SDValue();
5808
5809   // If the load that we're shrinking is an extload and we're not just
5810   // discarding the extension we can't simply shrink the load. Bail.
5811   // TODO: It would be possible to merge the extensions in some cases.
5812   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5813       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5814     return SDValue();
5815
5816   EVT PtrType = N0.getOperand(1).getValueType();
5817
5818   if (PtrType == MVT::Untyped || PtrType.isExtended())
5819     // It's not possible to generate a constant of extended or untyped type.
5820     return SDValue();
5821
5822   // For big endian targets, we need to adjust the offset to the pointer to
5823   // load the correct bytes.
5824   if (TLI.isBigEndian()) {
5825     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5826     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5827     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5828   }
5829
5830   uint64_t PtrOff = ShAmt / 8;
5831   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5832   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5833                                PtrType, LN0->getBasePtr(),
5834                                DAG.getConstant(PtrOff, PtrType));
5835   AddToWorklist(NewPtr.getNode());
5836
5837   SDValue Load;
5838   if (ExtType == ISD::NON_EXTLOAD)
5839     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5840                         LN0->getPointerInfo().getWithOffset(PtrOff),
5841                         LN0->isVolatile(), LN0->isNonTemporal(),
5842                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5843   else
5844     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5845                           LN0->getPointerInfo().getWithOffset(PtrOff),
5846                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5847                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5848
5849   // Replace the old load's chain with the new load's chain.
5850   WorklistRemover DeadNodes(*this);
5851   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5852
5853   // Shift the result left, if we've swallowed a left shift.
5854   SDValue Result = Load;
5855   if (ShLeftAmt != 0) {
5856     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5857     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5858       ShImmTy = VT;
5859     // If the shift amount is as large as the result size (but, presumably,
5860     // no larger than the source) then the useful bits of the result are
5861     // zero; we can't simply return the shortened shift, because the result
5862     // of that operation is undefined.
5863     if (ShLeftAmt >= VT.getSizeInBits())
5864       Result = DAG.getConstant(0, VT);
5865     else
5866       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5867                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5868   }
5869
5870   // Return the new loaded value.
5871   return Result;
5872 }
5873
5874 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5875   SDValue N0 = N->getOperand(0);
5876   SDValue N1 = N->getOperand(1);
5877   EVT VT = N->getValueType(0);
5878   EVT EVT = cast<VTSDNode>(N1)->getVT();
5879   unsigned VTBits = VT.getScalarType().getSizeInBits();
5880   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5881
5882   // fold (sext_in_reg c1) -> c1
5883   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5884     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5885
5886   // If the input is already sign extended, just drop the extension.
5887   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5888     return N0;
5889
5890   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5891   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5892       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5893     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5894                        N0.getOperand(0), N1);
5895
5896   // fold (sext_in_reg (sext x)) -> (sext x)
5897   // fold (sext_in_reg (aext x)) -> (sext x)
5898   // if x is small enough.
5899   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5900     SDValue N00 = N0.getOperand(0);
5901     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5902         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5903       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5904   }
5905
5906   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5907   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5908     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5909
5910   // fold operands of sext_in_reg based on knowledge that the top bits are not
5911   // demanded.
5912   if (SimplifyDemandedBits(SDValue(N, 0)))
5913     return SDValue(N, 0);
5914
5915   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5916   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5917   SDValue NarrowLoad = ReduceLoadWidth(N);
5918   if (NarrowLoad.getNode())
5919     return NarrowLoad;
5920
5921   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5922   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5923   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5924   if (N0.getOpcode() == ISD::SRL) {
5925     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5926       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5927         // We can turn this into an SRA iff the input to the SRL is already sign
5928         // extended enough.
5929         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5930         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5931           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5932                              N0.getOperand(0), N0.getOperand(1));
5933       }
5934   }
5935
5936   // fold (sext_inreg (extload x)) -> (sextload x)
5937   if (ISD::isEXTLoad(N0.getNode()) &&
5938       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5939       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5940       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5941        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5942     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5943     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5944                                      LN0->getChain(),
5945                                      LN0->getBasePtr(), EVT,
5946                                      LN0->getMemOperand());
5947     CombineTo(N, ExtLoad);
5948     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5949     AddToWorklist(ExtLoad.getNode());
5950     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5951   }
5952   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5953   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5954       N0.hasOneUse() &&
5955       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5956       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5957        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5958     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5959     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5960                                      LN0->getChain(),
5961                                      LN0->getBasePtr(), EVT,
5962                                      LN0->getMemOperand());
5963     CombineTo(N, ExtLoad);
5964     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5965     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5966   }
5967
5968   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5969   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5970     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5971                                        N0.getOperand(1), false);
5972     if (BSwap.getNode())
5973       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5974                          BSwap, N1);
5975   }
5976
5977   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5978   // into a build_vector.
5979   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5980     SmallVector<SDValue, 8> Elts;
5981     unsigned NumElts = N0->getNumOperands();
5982     unsigned ShAmt = VTBits - EVTBits;
5983
5984     for (unsigned i = 0; i != NumElts; ++i) {
5985       SDValue Op = N0->getOperand(i);
5986       if (Op->getOpcode() == ISD::UNDEF) {
5987         Elts.push_back(Op);
5988         continue;
5989       }
5990
5991       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5992       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5993       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5994                                      Op.getValueType()));
5995     }
5996
5997     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5998   }
5999
6000   return SDValue();
6001 }
6002
6003 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6004   SDValue N0 = N->getOperand(0);
6005   EVT VT = N->getValueType(0);
6006   bool isLE = TLI.isLittleEndian();
6007
6008   // noop truncate
6009   if (N0.getValueType() == N->getValueType(0))
6010     return N0;
6011   // fold (truncate c1) -> c1
6012   if (isa<ConstantSDNode>(N0))
6013     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6014   // fold (truncate (truncate x)) -> (truncate x)
6015   if (N0.getOpcode() == ISD::TRUNCATE)
6016     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6017   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6018   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6019       N0.getOpcode() == ISD::SIGN_EXTEND ||
6020       N0.getOpcode() == ISD::ANY_EXTEND) {
6021     if (N0.getOperand(0).getValueType().bitsLT(VT))
6022       // if the source is smaller than the dest, we still need an extend
6023       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6024                          N0.getOperand(0));
6025     if (N0.getOperand(0).getValueType().bitsGT(VT))
6026       // if the source is larger than the dest, than we just need the truncate
6027       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6028     // if the source and dest are the same type, we can drop both the extend
6029     // and the truncate.
6030     return N0.getOperand(0);
6031   }
6032
6033   // Fold extract-and-trunc into a narrow extract. For example:
6034   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6035   //   i32 y = TRUNCATE(i64 x)
6036   //        -- becomes --
6037   //   v16i8 b = BITCAST (v2i64 val)
6038   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6039   //
6040   // Note: We only run this optimization after type legalization (which often
6041   // creates this pattern) and before operation legalization after which
6042   // we need to be more careful about the vector instructions that we generate.
6043   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6044       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6045
6046     EVT VecTy = N0.getOperand(0).getValueType();
6047     EVT ExTy = N0.getValueType();
6048     EVT TrTy = N->getValueType(0);
6049
6050     unsigned NumElem = VecTy.getVectorNumElements();
6051     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6052
6053     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6054     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6055
6056     SDValue EltNo = N0->getOperand(1);
6057     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6058       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6059       EVT IndexTy = TLI.getVectorIdxTy();
6060       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6061
6062       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6063                               NVT, N0.getOperand(0));
6064
6065       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6066                          SDLoc(N), TrTy, V,
6067                          DAG.getConstant(Index, IndexTy));
6068     }
6069   }
6070
6071   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6072   if (N0.getOpcode() == ISD::SELECT) {
6073     EVT SrcVT = N0.getValueType();
6074     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6075         TLI.isTruncateFree(SrcVT, VT)) {
6076       SDLoc SL(N0);
6077       SDValue Cond = N0.getOperand(0);
6078       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6079       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6080       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6081     }
6082   }
6083
6084   // Fold a series of buildvector, bitcast, and truncate if possible.
6085   // For example fold
6086   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6087   //   (2xi32 (buildvector x, y)).
6088   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6089       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6090       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6091       N0.getOperand(0).hasOneUse()) {
6092
6093     SDValue BuildVect = N0.getOperand(0);
6094     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6095     EVT TruncVecEltTy = VT.getVectorElementType();
6096
6097     // Check that the element types match.
6098     if (BuildVectEltTy == TruncVecEltTy) {
6099       // Now we only need to compute the offset of the truncated elements.
6100       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6101       unsigned TruncVecNumElts = VT.getVectorNumElements();
6102       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6103
6104       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6105              "Invalid number of elements");
6106
6107       SmallVector<SDValue, 8> Opnds;
6108       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6109         Opnds.push_back(BuildVect.getOperand(i));
6110
6111       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6112     }
6113   }
6114
6115   // See if we can simplify the input to this truncate through knowledge that
6116   // only the low bits are being used.
6117   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6118   // Currently we only perform this optimization on scalars because vectors
6119   // may have different active low bits.
6120   if (!VT.isVector()) {
6121     SDValue Shorter =
6122       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6123                                                VT.getSizeInBits()));
6124     if (Shorter.getNode())
6125       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6126   }
6127   // fold (truncate (load x)) -> (smaller load x)
6128   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6129   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6130     SDValue Reduced = ReduceLoadWidth(N);
6131     if (Reduced.getNode())
6132       return Reduced;
6133     // Handle the case where the load remains an extending load even
6134     // after truncation.
6135     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6136       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6137       if (!LN0->isVolatile() &&
6138           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6139         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6140                                          VT, LN0->getChain(), LN0->getBasePtr(),
6141                                          LN0->getMemoryVT(),
6142                                          LN0->getMemOperand());
6143         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6144         return NewLoad;
6145       }
6146     }
6147   }
6148   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6149   // where ... are all 'undef'.
6150   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6151     SmallVector<EVT, 8> VTs;
6152     SDValue V;
6153     unsigned Idx = 0;
6154     unsigned NumDefs = 0;
6155
6156     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6157       SDValue X = N0.getOperand(i);
6158       if (X.getOpcode() != ISD::UNDEF) {
6159         V = X;
6160         Idx = i;
6161         NumDefs++;
6162       }
6163       // Stop if more than one members are non-undef.
6164       if (NumDefs > 1)
6165         break;
6166       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6167                                      VT.getVectorElementType(),
6168                                      X.getValueType().getVectorNumElements()));
6169     }
6170
6171     if (NumDefs == 0)
6172       return DAG.getUNDEF(VT);
6173
6174     if (NumDefs == 1) {
6175       assert(V.getNode() && "The single defined operand is empty!");
6176       SmallVector<SDValue, 8> Opnds;
6177       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6178         if (i != Idx) {
6179           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6180           continue;
6181         }
6182         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6183         AddToWorklist(NV.getNode());
6184         Opnds.push_back(NV);
6185       }
6186       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6187     }
6188   }
6189
6190   // Simplify the operands using demanded-bits information.
6191   if (!VT.isVector() &&
6192       SimplifyDemandedBits(SDValue(N, 0)))
6193     return SDValue(N, 0);
6194
6195   return SDValue();
6196 }
6197
6198 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6199   SDValue Elt = N->getOperand(i);
6200   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6201     return Elt.getNode();
6202   return Elt.getOperand(Elt.getResNo()).getNode();
6203 }
6204
6205 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6206 /// if load locations are consecutive.
6207 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6208   assert(N->getOpcode() == ISD::BUILD_PAIR);
6209
6210   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6211   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6212   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6213       LD1->getAddressSpace() != LD2->getAddressSpace())
6214     return SDValue();
6215   EVT LD1VT = LD1->getValueType(0);
6216
6217   if (ISD::isNON_EXTLoad(LD2) &&
6218       LD2->hasOneUse() &&
6219       // If both are volatile this would reduce the number of volatile loads.
6220       // If one is volatile it might be ok, but play conservative and bail out.
6221       !LD1->isVolatile() &&
6222       !LD2->isVolatile() &&
6223       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6224     unsigned Align = LD1->getAlignment();
6225     unsigned NewAlign = TLI.getDataLayout()->
6226       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6227
6228     if (NewAlign <= Align &&
6229         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6230       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6231                          LD1->getBasePtr(), LD1->getPointerInfo(),
6232                          false, false, false, Align);
6233   }
6234
6235   return SDValue();
6236 }
6237
6238 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6239   SDValue N0 = N->getOperand(0);
6240   EVT VT = N->getValueType(0);
6241
6242   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6243   // Only do this before legalize, since afterward the target may be depending
6244   // on the bitconvert.
6245   // First check to see if this is all constant.
6246   if (!LegalTypes &&
6247       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6248       VT.isVector()) {
6249     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6250
6251     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6252     assert(!DestEltVT.isVector() &&
6253            "Element type of vector ValueType must not be vector!");
6254     if (isSimple)
6255       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6256   }
6257
6258   // If the input is a constant, let getNode fold it.
6259   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6260     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6261     if (Res.getNode() != N) {
6262       if (!LegalOperations ||
6263           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6264         return Res;
6265
6266       // Folding it resulted in an illegal node, and it's too late to
6267       // do that. Clean up the old node and forego the transformation.
6268       // Ideally this won't happen very often, because instcombine
6269       // and the earlier dagcombine runs (where illegal nodes are
6270       // permitted) should have folded most of them already.
6271       DAG.DeleteNode(Res.getNode());
6272     }
6273   }
6274
6275   // (conv (conv x, t1), t2) -> (conv x, t2)
6276   if (N0.getOpcode() == ISD::BITCAST)
6277     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6278                        N0.getOperand(0));
6279
6280   // fold (conv (load x)) -> (load (conv*)x)
6281   // If the resultant load doesn't need a higher alignment than the original!
6282   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6283       // Do not change the width of a volatile load.
6284       !cast<LoadSDNode>(N0)->isVolatile() &&
6285       // Do not remove the cast if the types differ in endian layout.
6286       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6287       TLI.hasBigEndianPartOrdering(VT) &&
6288       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6289       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6290     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6291     unsigned Align = TLI.getDataLayout()->
6292       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6293     unsigned OrigAlign = LN0->getAlignment();
6294
6295     if (Align <= OrigAlign) {
6296       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6297                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6298                                  LN0->isVolatile(), LN0->isNonTemporal(),
6299                                  LN0->isInvariant(), OrigAlign,
6300                                  LN0->getAAInfo());
6301       AddToWorklist(N);
6302       CombineTo(N0.getNode(),
6303                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6304                             N0.getValueType(), Load),
6305                 Load.getValue(1));
6306       return Load;
6307     }
6308   }
6309
6310   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6311   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6312   // This often reduces constant pool loads.
6313   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6314        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6315       N0.getNode()->hasOneUse() && VT.isInteger() &&
6316       !VT.isVector() && !N0.getValueType().isVector()) {
6317     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6318                                   N0.getOperand(0));
6319     AddToWorklist(NewConv.getNode());
6320
6321     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6322     if (N0.getOpcode() == ISD::FNEG)
6323       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6324                          NewConv, DAG.getConstant(SignBit, VT));
6325     assert(N0.getOpcode() == ISD::FABS);
6326     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6327                        NewConv, DAG.getConstant(~SignBit, VT));
6328   }
6329
6330   // fold (bitconvert (fcopysign cst, x)) ->
6331   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6332   // Note that we don't handle (copysign x, cst) because this can always be
6333   // folded to an fneg or fabs.
6334   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6335       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6336       VT.isInteger() && !VT.isVector()) {
6337     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6338     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6339     if (isTypeLegal(IntXVT)) {
6340       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6341                               IntXVT, N0.getOperand(1));
6342       AddToWorklist(X.getNode());
6343
6344       // If X has a different width than the result/lhs, sext it or truncate it.
6345       unsigned VTWidth = VT.getSizeInBits();
6346       if (OrigXWidth < VTWidth) {
6347         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6348         AddToWorklist(X.getNode());
6349       } else if (OrigXWidth > VTWidth) {
6350         // To get the sign bit in the right place, we have to shift it right
6351         // before truncating.
6352         X = DAG.getNode(ISD::SRL, SDLoc(X),
6353                         X.getValueType(), X,
6354                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6355         AddToWorklist(X.getNode());
6356         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6357         AddToWorklist(X.getNode());
6358       }
6359
6360       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6361       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6362                       X, DAG.getConstant(SignBit, VT));
6363       AddToWorklist(X.getNode());
6364
6365       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6366                                 VT, N0.getOperand(0));
6367       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6368                         Cst, DAG.getConstant(~SignBit, VT));
6369       AddToWorklist(Cst.getNode());
6370
6371       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6372     }
6373   }
6374
6375   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6376   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6377     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6378     if (CombineLD.getNode())
6379       return CombineLD;
6380   }
6381
6382   return SDValue();
6383 }
6384
6385 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6386   EVT VT = N->getValueType(0);
6387   return CombineConsecutiveLoads(N, VT);
6388 }
6389
6390 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6391 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6392 /// destination element value type.
6393 SDValue DAGCombiner::
6394 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6395   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6396
6397   // If this is already the right type, we're done.
6398   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6399
6400   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6401   unsigned DstBitSize = DstEltVT.getSizeInBits();
6402
6403   // If this is a conversion of N elements of one type to N elements of another
6404   // type, convert each element.  This handles FP<->INT cases.
6405   if (SrcBitSize == DstBitSize) {
6406     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6407                               BV->getValueType(0).getVectorNumElements());
6408
6409     // Due to the FP element handling below calling this routine recursively,
6410     // we can end up with a scalar-to-vector node here.
6411     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6412       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6413                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6414                                      DstEltVT, BV->getOperand(0)));
6415
6416     SmallVector<SDValue, 8> Ops;
6417     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6418       SDValue Op = BV->getOperand(i);
6419       // If the vector element type is not legal, the BUILD_VECTOR operands
6420       // are promoted and implicitly truncated.  Make that explicit here.
6421       if (Op.getValueType() != SrcEltVT)
6422         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6423       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6424                                 DstEltVT, Op));
6425       AddToWorklist(Ops.back().getNode());
6426     }
6427     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6428   }
6429
6430   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6431   // handle annoying details of growing/shrinking FP values, we convert them to
6432   // int first.
6433   if (SrcEltVT.isFloatingPoint()) {
6434     // Convert the input float vector to a int vector where the elements are the
6435     // same sizes.
6436     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6437     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6438     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6439     SrcEltVT = IntVT;
6440   }
6441
6442   // Now we know the input is an integer vector.  If the output is a FP type,
6443   // convert to integer first, then to FP of the right size.
6444   if (DstEltVT.isFloatingPoint()) {
6445     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6446     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6447     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6448
6449     // Next, convert to FP elements of the same size.
6450     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6451   }
6452
6453   // Okay, we know the src/dst types are both integers of differing types.
6454   // Handling growing first.
6455   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6456   if (SrcBitSize < DstBitSize) {
6457     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6458
6459     SmallVector<SDValue, 8> Ops;
6460     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6461          i += NumInputsPerOutput) {
6462       bool isLE = TLI.isLittleEndian();
6463       APInt NewBits = APInt(DstBitSize, 0);
6464       bool EltIsUndef = true;
6465       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6466         // Shift the previously computed bits over.
6467         NewBits <<= SrcBitSize;
6468         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6469         if (Op.getOpcode() == ISD::UNDEF) continue;
6470         EltIsUndef = false;
6471
6472         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6473                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6474       }
6475
6476       if (EltIsUndef)
6477         Ops.push_back(DAG.getUNDEF(DstEltVT));
6478       else
6479         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6480     }
6481
6482     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6483     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6484   }
6485
6486   // Finally, this must be the case where we are shrinking elements: each input
6487   // turns into multiple outputs.
6488   bool isS2V = ISD::isScalarToVector(BV);
6489   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6490   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6491                             NumOutputsPerInput*BV->getNumOperands());
6492   SmallVector<SDValue, 8> Ops;
6493
6494   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6495     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6496       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6497         Ops.push_back(DAG.getUNDEF(DstEltVT));
6498       continue;
6499     }
6500
6501     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6502                   getAPIntValue().zextOrTrunc(SrcBitSize);
6503
6504     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6505       APInt ThisVal = OpVal.trunc(DstBitSize);
6506       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6507       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6508         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6509         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6510                            Ops[0]);
6511       OpVal = OpVal.lshr(DstBitSize);
6512     }
6513
6514     // For big endian targets, swap the order of the pieces of each element.
6515     if (TLI.isBigEndian())
6516       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6517   }
6518
6519   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6520 }
6521
6522 SDValue DAGCombiner::visitFADD(SDNode *N) {
6523   SDValue N0 = N->getOperand(0);
6524   SDValue N1 = N->getOperand(1);
6525   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6526   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6527   EVT VT = N->getValueType(0);
6528
6529   // fold vector ops
6530   if (VT.isVector()) {
6531     SDValue FoldedVOp = SimplifyVBinOp(N);
6532     if (FoldedVOp.getNode()) return FoldedVOp;
6533   }
6534
6535   // fold (fadd c1, c2) -> c1 + c2
6536   if (N0CFP && N1CFP)
6537     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6538   // canonicalize constant to RHS
6539   if (N0CFP && !N1CFP)
6540     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6541   // fold (fadd A, 0) -> A
6542   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6543       N1CFP->getValueAPF().isZero())
6544     return N0;
6545   // fold (fadd A, (fneg B)) -> (fsub A, B)
6546   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6547     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6548     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6549                        GetNegatedExpression(N1, DAG, LegalOperations));
6550   // fold (fadd (fneg A), B) -> (fsub B, A)
6551   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6552     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6553     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6554                        GetNegatedExpression(N0, DAG, LegalOperations));
6555
6556   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6557   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6558       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6559       isa<ConstantFPSDNode>(N0.getOperand(1)))
6560     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6561                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6562                                    N0.getOperand(1), N1));
6563
6564   // No FP constant should be created after legalization as Instruction
6565   // Selection pass has hard time in dealing with FP constant.
6566   //
6567   // We don't need test this condition for transformation like following, as
6568   // the DAG being transformed implies it is legal to take FP constant as
6569   // operand.
6570   //
6571   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6572   //
6573   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6574
6575   // If allow, fold (fadd (fneg x), x) -> 0.0
6576   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6577       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6578     return DAG.getConstantFP(0.0, VT);
6579
6580     // If allow, fold (fadd x, (fneg x)) -> 0.0
6581   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6582       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6583     return DAG.getConstantFP(0.0, VT);
6584
6585   // In unsafe math mode, we can fold chains of FADD's of the same value
6586   // into multiplications.  This transform is not safe in general because
6587   // we are reducing the number of rounding steps.
6588   if (DAG.getTarget().Options.UnsafeFPMath &&
6589       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6590       !N0CFP && !N1CFP) {
6591     if (N0.getOpcode() == ISD::FMUL) {
6592       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6593       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6594
6595       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6596       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6597         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6598                                      SDValue(CFP00, 0),
6599                                      DAG.getConstantFP(1.0, VT));
6600         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6601                            N1, NewCFP);
6602       }
6603
6604       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6605       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6606         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6607                                      SDValue(CFP01, 0),
6608                                      DAG.getConstantFP(1.0, VT));
6609         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6610                            N1, NewCFP);
6611       }
6612
6613       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6614       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6615           N1.getOperand(0) == N1.getOperand(1) &&
6616           N0.getOperand(1) == N1.getOperand(0)) {
6617         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6618                                      SDValue(CFP00, 0),
6619                                      DAG.getConstantFP(2.0, VT));
6620         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6621                            N0.getOperand(1), NewCFP);
6622       }
6623
6624       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6625       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6626           N1.getOperand(0) == N1.getOperand(1) &&
6627           N0.getOperand(0) == N1.getOperand(0)) {
6628         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6629                                      SDValue(CFP01, 0),
6630                                      DAG.getConstantFP(2.0, VT));
6631         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6632                            N0.getOperand(0), NewCFP);
6633       }
6634     }
6635
6636     if (N1.getOpcode() == ISD::FMUL) {
6637       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6638       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6639
6640       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6641       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6642         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6643                                      SDValue(CFP10, 0),
6644                                      DAG.getConstantFP(1.0, VT));
6645         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6646                            N0, NewCFP);
6647       }
6648
6649       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6650       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6651         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6652                                      SDValue(CFP11, 0),
6653                                      DAG.getConstantFP(1.0, VT));
6654         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6655                            N0, NewCFP);
6656       }
6657
6658
6659       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6660       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6661           N0.getOperand(0) == N0.getOperand(1) &&
6662           N1.getOperand(1) == N0.getOperand(0)) {
6663         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6664                                      SDValue(CFP10, 0),
6665                                      DAG.getConstantFP(2.0, VT));
6666         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6667                            N1.getOperand(1), NewCFP);
6668       }
6669
6670       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6671       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6672           N0.getOperand(0) == N0.getOperand(1) &&
6673           N1.getOperand(0) == N0.getOperand(0)) {
6674         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6675                                      SDValue(CFP11, 0),
6676                                      DAG.getConstantFP(2.0, VT));
6677         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6678                            N1.getOperand(0), NewCFP);
6679       }
6680     }
6681
6682     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6683       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6684       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6685       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6686           (N0.getOperand(0) == N1))
6687         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6688                            N1, DAG.getConstantFP(3.0, VT));
6689     }
6690
6691     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6692       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6693       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6694       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6695           N1.getOperand(0) == N0)
6696         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6697                            N0, DAG.getConstantFP(3.0, VT));
6698     }
6699
6700     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6701     if (AllowNewFpConst &&
6702         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6703         N0.getOperand(0) == N0.getOperand(1) &&
6704         N1.getOperand(0) == N1.getOperand(1) &&
6705         N0.getOperand(0) == N1.getOperand(0))
6706       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6707                          N0.getOperand(0),
6708                          DAG.getConstantFP(4.0, VT));
6709   }
6710
6711   // FADD -> FMA combines:
6712   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6713        DAG.getTarget().Options.UnsafeFPMath) &&
6714       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6715       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6716
6717     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6718     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6719       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6720                          N0.getOperand(0), N0.getOperand(1), N1);
6721
6722     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6723     // Note: Commutes FADD operands.
6724     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6725       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6726                          N1.getOperand(0), N1.getOperand(1), N0);
6727   }
6728
6729   return SDValue();
6730 }
6731
6732 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6733   SDValue N0 = N->getOperand(0);
6734   SDValue N1 = N->getOperand(1);
6735   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6736   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6737   EVT VT = N->getValueType(0);
6738   SDLoc dl(N);
6739
6740   // fold vector ops
6741   if (VT.isVector()) {
6742     SDValue FoldedVOp = SimplifyVBinOp(N);
6743     if (FoldedVOp.getNode()) return FoldedVOp;
6744   }
6745
6746   // fold (fsub c1, c2) -> c1-c2
6747   if (N0CFP && N1CFP)
6748     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6749   // fold (fsub A, 0) -> A
6750   if (DAG.getTarget().Options.UnsafeFPMath &&
6751       N1CFP && N1CFP->getValueAPF().isZero())
6752     return N0;
6753   // fold (fsub 0, B) -> -B
6754   if (DAG.getTarget().Options.UnsafeFPMath &&
6755       N0CFP && N0CFP->getValueAPF().isZero()) {
6756     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6757       return GetNegatedExpression(N1, DAG, LegalOperations);
6758     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6759       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6760   }
6761   // fold (fsub A, (fneg B)) -> (fadd A, B)
6762   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6763     return DAG.getNode(ISD::FADD, dl, VT, N0,
6764                        GetNegatedExpression(N1, DAG, LegalOperations));
6765
6766   // If 'unsafe math' is enabled, fold
6767   //    (fsub x, x) -> 0.0 &
6768   //    (fsub x, (fadd x, y)) -> (fneg y) &
6769   //    (fsub x, (fadd y, x)) -> (fneg y)
6770   if (DAG.getTarget().Options.UnsafeFPMath) {
6771     if (N0 == N1)
6772       return DAG.getConstantFP(0.0f, VT);
6773
6774     if (N1.getOpcode() == ISD::FADD) {
6775       SDValue N10 = N1->getOperand(0);
6776       SDValue N11 = N1->getOperand(1);
6777
6778       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6779                                           &DAG.getTarget().Options))
6780         return GetNegatedExpression(N11, DAG, LegalOperations);
6781
6782       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6783                                           &DAG.getTarget().Options))
6784         return GetNegatedExpression(N10, DAG, LegalOperations);
6785     }
6786   }
6787
6788   // FSUB -> FMA combines:
6789   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6790        DAG.getTarget().Options.UnsafeFPMath) &&
6791       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6792       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6793
6794     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6795     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6796       return DAG.getNode(ISD::FMA, dl, VT,
6797                          N0.getOperand(0), N0.getOperand(1),
6798                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6799
6800     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6801     // Note: Commutes FSUB operands.
6802     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6803       return DAG.getNode(ISD::FMA, dl, VT,
6804                          DAG.getNode(ISD::FNEG, dl, VT,
6805                          N1.getOperand(0)),
6806                          N1.getOperand(1), N0);
6807
6808     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6809     if (N0.getOpcode() == ISD::FNEG &&
6810         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6811         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6812       SDValue N00 = N0.getOperand(0).getOperand(0);
6813       SDValue N01 = N0.getOperand(0).getOperand(1);
6814       return DAG.getNode(ISD::FMA, dl, VT,
6815                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6816                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6817     }
6818   }
6819
6820   return SDValue();
6821 }
6822
6823 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6824   SDValue N0 = N->getOperand(0);
6825   SDValue N1 = N->getOperand(1);
6826   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6827   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6828   EVT VT = N->getValueType(0);
6829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6830
6831   // fold vector ops
6832   if (VT.isVector()) {
6833     SDValue FoldedVOp = SimplifyVBinOp(N);
6834     if (FoldedVOp.getNode()) return FoldedVOp;
6835   }
6836
6837   // fold (fmul c1, c2) -> c1*c2
6838   if (N0CFP && N1CFP)
6839     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6840   // canonicalize constant to RHS
6841   if (N0CFP && !N1CFP)
6842     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6843   // fold (fmul A, 0) -> 0
6844   if (DAG.getTarget().Options.UnsafeFPMath &&
6845       N1CFP && N1CFP->getValueAPF().isZero())
6846     return N1;
6847   // fold (fmul A, 0) -> 0, vector edition.
6848   if (DAG.getTarget().Options.UnsafeFPMath &&
6849       ISD::isBuildVectorAllZeros(N1.getNode()))
6850     return N1;
6851   // fold (fmul A, 1.0) -> A
6852   if (N1CFP && N1CFP->isExactlyValue(1.0))
6853     return N0;
6854   // fold (fmul X, 2.0) -> (fadd X, X)
6855   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6856     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6857   // fold (fmul X, -1.0) -> (fneg X)
6858   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6859     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6860       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6861
6862   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6863   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6864                                        &DAG.getTarget().Options)) {
6865     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6866                                          &DAG.getTarget().Options)) {
6867       // Both can be negated for free, check to see if at least one is cheaper
6868       // negated.
6869       if (LHSNeg == 2 || RHSNeg == 2)
6870         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6871                            GetNegatedExpression(N0, DAG, LegalOperations),
6872                            GetNegatedExpression(N1, DAG, LegalOperations));
6873     }
6874   }
6875
6876   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6877   if (DAG.getTarget().Options.UnsafeFPMath &&
6878       N1CFP && N0.getOpcode() == ISD::FMUL &&
6879       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6880     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6881                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6882                                    N0.getOperand(1), N1));
6883
6884   return SDValue();
6885 }
6886
6887 SDValue DAGCombiner::visitFMA(SDNode *N) {
6888   SDValue N0 = N->getOperand(0);
6889   SDValue N1 = N->getOperand(1);
6890   SDValue N2 = N->getOperand(2);
6891   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6892   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6893   EVT VT = N->getValueType(0);
6894   SDLoc dl(N);
6895
6896   if (DAG.getTarget().Options.UnsafeFPMath) {
6897     if (N0CFP && N0CFP->isZero())
6898       return N2;
6899     if (N1CFP && N1CFP->isZero())
6900       return N2;
6901   }
6902   if (N0CFP && N0CFP->isExactlyValue(1.0))
6903     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6904   if (N1CFP && N1CFP->isExactlyValue(1.0))
6905     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6906
6907   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6908   if (N0CFP && !N1CFP)
6909     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6910
6911   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6912   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6913       N2.getOpcode() == ISD::FMUL &&
6914       N0 == N2.getOperand(0) &&
6915       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6916     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6917                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6918   }
6919
6920
6921   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6922   if (DAG.getTarget().Options.UnsafeFPMath &&
6923       N0.getOpcode() == ISD::FMUL && N1CFP &&
6924       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6925     return DAG.getNode(ISD::FMA, dl, VT,
6926                        N0.getOperand(0),
6927                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6928                        N2);
6929   }
6930
6931   // (fma x, 1, y) -> (fadd x, y)
6932   // (fma x, -1, y) -> (fadd (fneg x), y)
6933   if (N1CFP) {
6934     if (N1CFP->isExactlyValue(1.0))
6935       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6936
6937     if (N1CFP->isExactlyValue(-1.0) &&
6938         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6939       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6940       AddToWorklist(RHSNeg.getNode());
6941       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6942     }
6943   }
6944
6945   // (fma x, c, x) -> (fmul x, (c+1))
6946   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6947     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6948                        DAG.getNode(ISD::FADD, dl, VT,
6949                                    N1, DAG.getConstantFP(1.0, VT)));
6950
6951   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6952   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6953       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6954     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6955                        DAG.getNode(ISD::FADD, dl, VT,
6956                                    N1, DAG.getConstantFP(-1.0, VT)));
6957
6958
6959   return SDValue();
6960 }
6961
6962 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6963   SDValue N0 = N->getOperand(0);
6964   SDValue N1 = N->getOperand(1);
6965   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6966   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6967   EVT VT = N->getValueType(0);
6968   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6969
6970   // fold vector ops
6971   if (VT.isVector()) {
6972     SDValue FoldedVOp = SimplifyVBinOp(N);
6973     if (FoldedVOp.getNode()) return FoldedVOp;
6974   }
6975
6976   // fold (fdiv c1, c2) -> c1/c2
6977   if (N0CFP && N1CFP)
6978     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6979
6980   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6981   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6982     // Compute the reciprocal 1.0 / c2.
6983     APFloat N1APF = N1CFP->getValueAPF();
6984     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6985     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6986     // Only do the transform if the reciprocal is a legal fp immediate that
6987     // isn't too nasty (eg NaN, denormal, ...).
6988     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6989         (!LegalOperations ||
6990          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6991          // backend)... we should handle this gracefully after Legalize.
6992          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6993          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6994          TLI.isFPImmLegal(Recip, VT)))
6995       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6996                          DAG.getConstantFP(Recip, VT));
6997   }
6998
6999   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7000   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7001                                        &DAG.getTarget().Options)) {
7002     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7003                                          &DAG.getTarget().Options)) {
7004       // Both can be negated for free, check to see if at least one is cheaper
7005       // negated.
7006       if (LHSNeg == 2 || RHSNeg == 2)
7007         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7008                            GetNegatedExpression(N0, DAG, LegalOperations),
7009                            GetNegatedExpression(N1, DAG, LegalOperations));
7010     }
7011   }
7012
7013   return SDValue();
7014 }
7015
7016 SDValue DAGCombiner::visitFREM(SDNode *N) {
7017   SDValue N0 = N->getOperand(0);
7018   SDValue N1 = N->getOperand(1);
7019   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7020   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7021   EVT VT = N->getValueType(0);
7022
7023   // fold (frem c1, c2) -> fmod(c1,c2)
7024   if (N0CFP && N1CFP)
7025     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7026
7027   return SDValue();
7028 }
7029
7030 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7031   SDValue N0 = N->getOperand(0);
7032   SDValue N1 = N->getOperand(1);
7033   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7034   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7035   EVT VT = N->getValueType(0);
7036
7037   if (N0CFP && N1CFP)  // Constant fold
7038     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7039
7040   if (N1CFP) {
7041     const APFloat& V = N1CFP->getValueAPF();
7042     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7043     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7044     if (!V.isNegative()) {
7045       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7046         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7047     } else {
7048       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7049         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7050                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7051     }
7052   }
7053
7054   // copysign(fabs(x), y) -> copysign(x, y)
7055   // copysign(fneg(x), y) -> copysign(x, y)
7056   // copysign(copysign(x,z), y) -> copysign(x, y)
7057   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7058       N0.getOpcode() == ISD::FCOPYSIGN)
7059     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7060                        N0.getOperand(0), N1);
7061
7062   // copysign(x, abs(y)) -> abs(x)
7063   if (N1.getOpcode() == ISD::FABS)
7064     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7065
7066   // copysign(x, copysign(y,z)) -> copysign(x, z)
7067   if (N1.getOpcode() == ISD::FCOPYSIGN)
7068     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7069                        N0, N1.getOperand(1));
7070
7071   // copysign(x, fp_extend(y)) -> copysign(x, y)
7072   // copysign(x, fp_round(y)) -> copysign(x, y)
7073   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7074     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7075                        N0, N1.getOperand(0));
7076
7077   return SDValue();
7078 }
7079
7080 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7081   SDValue N0 = N->getOperand(0);
7082   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7083   EVT VT = N->getValueType(0);
7084   EVT OpVT = N0.getValueType();
7085
7086   // fold (sint_to_fp c1) -> c1fp
7087   if (N0C &&
7088       // ...but only if the target supports immediate floating-point values
7089       (!LegalOperations ||
7090        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7091     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7092
7093   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7094   // but UINT_TO_FP is legal on this target, try to convert.
7095   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7096       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7097     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7098     if (DAG.SignBitIsZero(N0))
7099       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7100   }
7101
7102   // The next optimizations are desirable only if SELECT_CC can be lowered.
7103   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7104     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7105     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7106         !VT.isVector() &&
7107         (!LegalOperations ||
7108          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7109       SDValue Ops[] =
7110         { N0.getOperand(0), N0.getOperand(1),
7111           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7112           N0.getOperand(2) };
7113       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7114     }
7115
7116     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7117     //      (select_cc x, y, 1.0, 0.0,, cc)
7118     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7119         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7120         (!LegalOperations ||
7121          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7122       SDValue Ops[] =
7123         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7124           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7125           N0.getOperand(0).getOperand(2) };
7126       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7127     }
7128   }
7129
7130   return SDValue();
7131 }
7132
7133 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7134   SDValue N0 = N->getOperand(0);
7135   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7136   EVT VT = N->getValueType(0);
7137   EVT OpVT = N0.getValueType();
7138
7139   // fold (uint_to_fp c1) -> c1fp
7140   if (N0C &&
7141       // ...but only if the target supports immediate floating-point values
7142       (!LegalOperations ||
7143        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7144     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7145
7146   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7147   // but SINT_TO_FP is legal on this target, try to convert.
7148   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7149       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7150     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7151     if (DAG.SignBitIsZero(N0))
7152       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7153   }
7154
7155   // The next optimizations are desirable only if SELECT_CC can be lowered.
7156   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7157     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7158
7159     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7160         (!LegalOperations ||
7161          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7162       SDValue Ops[] =
7163         { N0.getOperand(0), N0.getOperand(1),
7164           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7165           N0.getOperand(2) };
7166       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7167     }
7168   }
7169
7170   return SDValue();
7171 }
7172
7173 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7174   SDValue N0 = N->getOperand(0);
7175   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7176   EVT VT = N->getValueType(0);
7177
7178   // fold (fp_to_sint c1fp) -> c1
7179   if (N0CFP)
7180     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7181
7182   return SDValue();
7183 }
7184
7185 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7186   SDValue N0 = N->getOperand(0);
7187   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7188   EVT VT = N->getValueType(0);
7189
7190   // fold (fp_to_uint c1fp) -> c1
7191   if (N0CFP)
7192     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7193
7194   return SDValue();
7195 }
7196
7197 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7198   SDValue N0 = N->getOperand(0);
7199   SDValue N1 = N->getOperand(1);
7200   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7201   EVT VT = N->getValueType(0);
7202
7203   // fold (fp_round c1fp) -> c1fp
7204   if (N0CFP)
7205     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7206
7207   // fold (fp_round (fp_extend x)) -> x
7208   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7209     return N0.getOperand(0);
7210
7211   // fold (fp_round (fp_round x)) -> (fp_round x)
7212   if (N0.getOpcode() == ISD::FP_ROUND) {
7213     // This is a value preserving truncation if both round's are.
7214     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7215                    N0.getNode()->getConstantOperandVal(1) == 1;
7216     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7217                        DAG.getIntPtrConstant(IsTrunc));
7218   }
7219
7220   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7221   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7222     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7223                               N0.getOperand(0), N1);
7224     AddToWorklist(Tmp.getNode());
7225     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7226                        Tmp, N0.getOperand(1));
7227   }
7228
7229   return SDValue();
7230 }
7231
7232 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7233   SDValue N0 = N->getOperand(0);
7234   EVT VT = N->getValueType(0);
7235   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7236   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7237
7238   // fold (fp_round_inreg c1fp) -> c1fp
7239   if (N0CFP && isTypeLegal(EVT)) {
7240     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7241     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7242   }
7243
7244   return SDValue();
7245 }
7246
7247 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7248   SDValue N0 = N->getOperand(0);
7249   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7250   EVT VT = N->getValueType(0);
7251
7252   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7253   if (N->hasOneUse() &&
7254       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7255     return SDValue();
7256
7257   // fold (fp_extend c1fp) -> c1fp
7258   if (N0CFP)
7259     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7260
7261   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7262   // value of X.
7263   if (N0.getOpcode() == ISD::FP_ROUND
7264       && N0.getNode()->getConstantOperandVal(1) == 1) {
7265     SDValue In = N0.getOperand(0);
7266     if (In.getValueType() == VT) return In;
7267     if (VT.bitsLT(In.getValueType()))
7268       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7269                          In, N0.getOperand(1));
7270     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7271   }
7272
7273   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7274   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7275        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7276     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7277     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7278                                      LN0->getChain(),
7279                                      LN0->getBasePtr(), N0.getValueType(),
7280                                      LN0->getMemOperand());
7281     CombineTo(N, ExtLoad);
7282     CombineTo(N0.getNode(),
7283               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7284                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7285               ExtLoad.getValue(1));
7286     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7287   }
7288
7289   return SDValue();
7290 }
7291
7292 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7293   SDValue N0 = N->getOperand(0);
7294   EVT VT = N->getValueType(0);
7295
7296   if (VT.isVector()) {
7297     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7298     if (FoldedVOp.getNode()) return FoldedVOp;
7299   }
7300
7301   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7302                          &DAG.getTarget().Options))
7303     return GetNegatedExpression(N0, DAG, LegalOperations);
7304
7305   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7306   // constant pool values.
7307   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7308       !VT.isVector() &&
7309       N0.getNode()->hasOneUse() &&
7310       N0.getOperand(0).getValueType().isInteger()) {
7311     SDValue Int = N0.getOperand(0);
7312     EVT IntVT = Int.getValueType();
7313     if (IntVT.isInteger() && !IntVT.isVector()) {
7314       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7315               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7316       AddToWorklist(Int.getNode());
7317       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7318                          VT, Int);
7319     }
7320   }
7321
7322   // (fneg (fmul c, x)) -> (fmul -c, x)
7323   if (N0.getOpcode() == ISD::FMUL) {
7324     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7325     if (CFP1) {
7326       APFloat CVal = CFP1->getValueAPF();
7327       CVal.changeSign();
7328       if (Level >= AfterLegalizeDAG &&
7329           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7330            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7331         return DAG.getNode(
7332             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7333             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7334     }
7335   }
7336
7337   return SDValue();
7338 }
7339
7340 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7341   SDValue N0 = N->getOperand(0);
7342   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7343   EVT VT = N->getValueType(0);
7344
7345   // fold (fceil c1) -> fceil(c1)
7346   if (N0CFP)
7347     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7348
7349   return SDValue();
7350 }
7351
7352 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7353   SDValue N0 = N->getOperand(0);
7354   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7355   EVT VT = N->getValueType(0);
7356
7357   // fold (ftrunc c1) -> ftrunc(c1)
7358   if (N0CFP)
7359     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7360
7361   return SDValue();
7362 }
7363
7364 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7365   SDValue N0 = N->getOperand(0);
7366   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7367   EVT VT = N->getValueType(0);
7368
7369   // fold (ffloor c1) -> ffloor(c1)
7370   if (N0CFP)
7371     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7372
7373   return SDValue();
7374 }
7375
7376 SDValue DAGCombiner::visitFABS(SDNode *N) {
7377   SDValue N0 = N->getOperand(0);
7378   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7379   EVT VT = N->getValueType(0);
7380
7381   if (VT.isVector()) {
7382     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7383     if (FoldedVOp.getNode()) return FoldedVOp;
7384   }
7385
7386   // fold (fabs c1) -> fabs(c1)
7387   if (N0CFP)
7388     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7389   // fold (fabs (fabs x)) -> (fabs x)
7390   if (N0.getOpcode() == ISD::FABS)
7391     return N->getOperand(0);
7392   // fold (fabs (fneg x)) -> (fabs x)
7393   // fold (fabs (fcopysign x, y)) -> (fabs x)
7394   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7395     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7396
7397   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7398   // constant pool values.
7399   if (!TLI.isFAbsFree(VT) &&
7400       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7401       N0.getOperand(0).getValueType().isInteger() &&
7402       !N0.getOperand(0).getValueType().isVector()) {
7403     SDValue Int = N0.getOperand(0);
7404     EVT IntVT = Int.getValueType();
7405     if (IntVT.isInteger() && !IntVT.isVector()) {
7406       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7407              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7408       AddToWorklist(Int.getNode());
7409       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7410                          N->getValueType(0), Int);
7411     }
7412   }
7413
7414   return SDValue();
7415 }
7416
7417 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7418   SDValue Chain = N->getOperand(0);
7419   SDValue N1 = N->getOperand(1);
7420   SDValue N2 = N->getOperand(2);
7421
7422   // If N is a constant we could fold this into a fallthrough or unconditional
7423   // branch. However that doesn't happen very often in normal code, because
7424   // Instcombine/SimplifyCFG should have handled the available opportunities.
7425   // If we did this folding here, it would be necessary to update the
7426   // MachineBasicBlock CFG, which is awkward.
7427
7428   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7429   // on the target.
7430   if (N1.getOpcode() == ISD::SETCC &&
7431       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7432                                    N1.getOperand(0).getValueType())) {
7433     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7434                        Chain, N1.getOperand(2),
7435                        N1.getOperand(0), N1.getOperand(1), N2);
7436   }
7437
7438   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7439       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7440        (N1.getOperand(0).hasOneUse() &&
7441         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7442     SDNode *Trunc = nullptr;
7443     if (N1.getOpcode() == ISD::TRUNCATE) {
7444       // Look pass the truncate.
7445       Trunc = N1.getNode();
7446       N1 = N1.getOperand(0);
7447     }
7448
7449     // Match this pattern so that we can generate simpler code:
7450     //
7451     //   %a = ...
7452     //   %b = and i32 %a, 2
7453     //   %c = srl i32 %b, 1
7454     //   brcond i32 %c ...
7455     //
7456     // into
7457     //
7458     //   %a = ...
7459     //   %b = and i32 %a, 2
7460     //   %c = setcc eq %b, 0
7461     //   brcond %c ...
7462     //
7463     // This applies only when the AND constant value has one bit set and the
7464     // SRL constant is equal to the log2 of the AND constant. The back-end is
7465     // smart enough to convert the result into a TEST/JMP sequence.
7466     SDValue Op0 = N1.getOperand(0);
7467     SDValue Op1 = N1.getOperand(1);
7468
7469     if (Op0.getOpcode() == ISD::AND &&
7470         Op1.getOpcode() == ISD::Constant) {
7471       SDValue AndOp1 = Op0.getOperand(1);
7472
7473       if (AndOp1.getOpcode() == ISD::Constant) {
7474         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7475
7476         if (AndConst.isPowerOf2() &&
7477             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7478           SDValue SetCC =
7479             DAG.getSetCC(SDLoc(N),
7480                          getSetCCResultType(Op0.getValueType()),
7481                          Op0, DAG.getConstant(0, Op0.getValueType()),
7482                          ISD::SETNE);
7483
7484           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7485                                           MVT::Other, Chain, SetCC, N2);
7486           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7487           // will convert it back to (X & C1) >> C2.
7488           CombineTo(N, NewBRCond, false);
7489           // Truncate is dead.
7490           if (Trunc) {
7491             removeFromWorklist(Trunc);
7492             DAG.DeleteNode(Trunc);
7493           }
7494           // Replace the uses of SRL with SETCC
7495           WorklistRemover DeadNodes(*this);
7496           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7497           removeFromWorklist(N1.getNode());
7498           DAG.DeleteNode(N1.getNode());
7499           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7500         }
7501       }
7502     }
7503
7504     if (Trunc)
7505       // Restore N1 if the above transformation doesn't match.
7506       N1 = N->getOperand(1);
7507   }
7508
7509   // Transform br(xor(x, y)) -> br(x != y)
7510   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7511   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7512     SDNode *TheXor = N1.getNode();
7513     SDValue Op0 = TheXor->getOperand(0);
7514     SDValue Op1 = TheXor->getOperand(1);
7515     if (Op0.getOpcode() == Op1.getOpcode()) {
7516       // Avoid missing important xor optimizations.
7517       SDValue Tmp = visitXOR(TheXor);
7518       if (Tmp.getNode()) {
7519         if (Tmp.getNode() != TheXor) {
7520           DEBUG(dbgs() << "\nReplacing.8 ";
7521                 TheXor->dump(&DAG);
7522                 dbgs() << "\nWith: ";
7523                 Tmp.getNode()->dump(&DAG);
7524                 dbgs() << '\n');
7525           WorklistRemover DeadNodes(*this);
7526           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7527           removeFromWorklist(TheXor);
7528           DAG.DeleteNode(TheXor);
7529           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7530                              MVT::Other, Chain, Tmp, N2);
7531         }
7532
7533         // visitXOR has changed XOR's operands or replaced the XOR completely,
7534         // bail out.
7535         return SDValue(N, 0);
7536       }
7537     }
7538
7539     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7540       bool Equal = false;
7541       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7542         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7543             Op0.getOpcode() == ISD::XOR) {
7544           TheXor = Op0.getNode();
7545           Equal = true;
7546         }
7547
7548       EVT SetCCVT = N1.getValueType();
7549       if (LegalTypes)
7550         SetCCVT = getSetCCResultType(SetCCVT);
7551       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7552                                    SetCCVT,
7553                                    Op0, Op1,
7554                                    Equal ? ISD::SETEQ : ISD::SETNE);
7555       // Replace the uses of XOR with SETCC
7556       WorklistRemover DeadNodes(*this);
7557       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7558       removeFromWorklist(N1.getNode());
7559       DAG.DeleteNode(N1.getNode());
7560       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7561                          MVT::Other, Chain, SetCC, N2);
7562     }
7563   }
7564
7565   return SDValue();
7566 }
7567
7568 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7569 //
7570 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7571   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7572   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7573
7574   // If N is a constant we could fold this into a fallthrough or unconditional
7575   // branch. However that doesn't happen very often in normal code, because
7576   // Instcombine/SimplifyCFG should have handled the available opportunities.
7577   // If we did this folding here, it would be necessary to update the
7578   // MachineBasicBlock CFG, which is awkward.
7579
7580   // Use SimplifySetCC to simplify SETCC's.
7581   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7582                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7583                                false);
7584   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7585
7586   // fold to a simpler setcc
7587   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7588     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7589                        N->getOperand(0), Simp.getOperand(2),
7590                        Simp.getOperand(0), Simp.getOperand(1),
7591                        N->getOperand(4));
7592
7593   return SDValue();
7594 }
7595
7596 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7597 /// uses N as its base pointer and that N may be folded in the load / store
7598 /// addressing mode.
7599 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7600                                     SelectionDAG &DAG,
7601                                     const TargetLowering &TLI) {
7602   EVT VT;
7603   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7604     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7605       return false;
7606     VT = Use->getValueType(0);
7607   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7608     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7609       return false;
7610     VT = ST->getValue().getValueType();
7611   } else
7612     return false;
7613
7614   TargetLowering::AddrMode AM;
7615   if (N->getOpcode() == ISD::ADD) {
7616     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7617     if (Offset)
7618       // [reg +/- imm]
7619       AM.BaseOffs = Offset->getSExtValue();
7620     else
7621       // [reg +/- reg]
7622       AM.Scale = 1;
7623   } else if (N->getOpcode() == ISD::SUB) {
7624     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7625     if (Offset)
7626       // [reg +/- imm]
7627       AM.BaseOffs = -Offset->getSExtValue();
7628     else
7629       // [reg +/- reg]
7630       AM.Scale = 1;
7631   } else
7632     return false;
7633
7634   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7635 }
7636
7637 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7638 /// pre-indexed load / store when the base pointer is an add or subtract
7639 /// and it has other uses besides the load / store. After the
7640 /// transformation, the new indexed load / store has effectively folded
7641 /// the add / subtract in and all of its other uses are redirected to the
7642 /// new load / store.
7643 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7644   if (Level < AfterLegalizeDAG)
7645     return false;
7646
7647   bool isLoad = true;
7648   SDValue Ptr;
7649   EVT VT;
7650   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7651     if (LD->isIndexed())
7652       return false;
7653     VT = LD->getMemoryVT();
7654     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7655         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7656       return false;
7657     Ptr = LD->getBasePtr();
7658   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7659     if (ST->isIndexed())
7660       return false;
7661     VT = ST->getMemoryVT();
7662     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7663         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7664       return false;
7665     Ptr = ST->getBasePtr();
7666     isLoad = false;
7667   } else {
7668     return false;
7669   }
7670
7671   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7672   // out.  There is no reason to make this a preinc/predec.
7673   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7674       Ptr.getNode()->hasOneUse())
7675     return false;
7676
7677   // Ask the target to do addressing mode selection.
7678   SDValue BasePtr;
7679   SDValue Offset;
7680   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7681   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7682     return false;
7683
7684   // Backends without true r+i pre-indexed forms may need to pass a
7685   // constant base with a variable offset so that constant coercion
7686   // will work with the patterns in canonical form.
7687   bool Swapped = false;
7688   if (isa<ConstantSDNode>(BasePtr)) {
7689     std::swap(BasePtr, Offset);
7690     Swapped = true;
7691   }
7692
7693   // Don't create a indexed load / store with zero offset.
7694   if (isa<ConstantSDNode>(Offset) &&
7695       cast<ConstantSDNode>(Offset)->isNullValue())
7696     return false;
7697
7698   // Try turning it into a pre-indexed load / store except when:
7699   // 1) The new base ptr is a frame index.
7700   // 2) If N is a store and the new base ptr is either the same as or is a
7701   //    predecessor of the value being stored.
7702   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7703   //    that would create a cycle.
7704   // 4) All uses are load / store ops that use it as old base ptr.
7705
7706   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7707   // (plus the implicit offset) to a register to preinc anyway.
7708   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7709     return false;
7710
7711   // Check #2.
7712   if (!isLoad) {
7713     SDValue Val = cast<StoreSDNode>(N)->getValue();
7714     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7715       return false;
7716   }
7717
7718   // If the offset is a constant, there may be other adds of constants that
7719   // can be folded with this one. We should do this to avoid having to keep
7720   // a copy of the original base pointer.
7721   SmallVector<SDNode *, 16> OtherUses;
7722   if (isa<ConstantSDNode>(Offset))
7723     for (SDNode *Use : BasePtr.getNode()->uses()) {
7724       if (Use == Ptr.getNode())
7725         continue;
7726
7727       if (Use->isPredecessorOf(N))
7728         continue;
7729
7730       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7731         OtherUses.clear();
7732         break;
7733       }
7734
7735       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7736       if (Op1.getNode() == BasePtr.getNode())
7737         std::swap(Op0, Op1);
7738       assert(Op0.getNode() == BasePtr.getNode() &&
7739              "Use of ADD/SUB but not an operand");
7740
7741       if (!isa<ConstantSDNode>(Op1)) {
7742         OtherUses.clear();
7743         break;
7744       }
7745
7746       // FIXME: In some cases, we can be smarter about this.
7747       if (Op1.getValueType() != Offset.getValueType()) {
7748         OtherUses.clear();
7749         break;
7750       }
7751
7752       OtherUses.push_back(Use);
7753     }
7754
7755   if (Swapped)
7756     std::swap(BasePtr, Offset);
7757
7758   // Now check for #3 and #4.
7759   bool RealUse = false;
7760
7761   // Caches for hasPredecessorHelper
7762   SmallPtrSet<const SDNode *, 32> Visited;
7763   SmallVector<const SDNode *, 16> Worklist;
7764
7765   for (SDNode *Use : Ptr.getNode()->uses()) {
7766     if (Use == N)
7767       continue;
7768     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7769       return false;
7770
7771     // If Ptr may be folded in addressing mode of other use, then it's
7772     // not profitable to do this transformation.
7773     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7774       RealUse = true;
7775   }
7776
7777   if (!RealUse)
7778     return false;
7779
7780   SDValue Result;
7781   if (isLoad)
7782     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7783                                 BasePtr, Offset, AM);
7784   else
7785     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7786                                  BasePtr, Offset, AM);
7787   ++PreIndexedNodes;
7788   ++NodesCombined;
7789   DEBUG(dbgs() << "\nReplacing.4 ";
7790         N->dump(&DAG);
7791         dbgs() << "\nWith: ";
7792         Result.getNode()->dump(&DAG);
7793         dbgs() << '\n');
7794   WorklistRemover DeadNodes(*this);
7795   if (isLoad) {
7796     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7797     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7798   } else {
7799     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7800   }
7801
7802   // Finally, since the node is now dead, remove it from the graph.
7803   DAG.DeleteNode(N);
7804
7805   if (Swapped)
7806     std::swap(BasePtr, Offset);
7807
7808   // Replace other uses of BasePtr that can be updated to use Ptr
7809   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7810     unsigned OffsetIdx = 1;
7811     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7812       OffsetIdx = 0;
7813     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7814            BasePtr.getNode() && "Expected BasePtr operand");
7815
7816     // We need to replace ptr0 in the following expression:
7817     //   x0 * offset0 + y0 * ptr0 = t0
7818     // knowing that
7819     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7820     //
7821     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7822     // indexed load/store and the expresion that needs to be re-written.
7823     //
7824     // Therefore, we have:
7825     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7826
7827     ConstantSDNode *CN =
7828       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7829     int X0, X1, Y0, Y1;
7830     APInt Offset0 = CN->getAPIntValue();
7831     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7832
7833     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7834     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7835     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7836     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7837
7838     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7839
7840     APInt CNV = Offset0;
7841     if (X0 < 0) CNV = -CNV;
7842     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7843     else CNV = CNV - Offset1;
7844
7845     // We can now generate the new expression.
7846     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7847     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7848
7849     SDValue NewUse = DAG.getNode(Opcode,
7850                                  SDLoc(OtherUses[i]),
7851                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7852     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7853     removeFromWorklist(OtherUses[i]);
7854     DAG.DeleteNode(OtherUses[i]);
7855   }
7856
7857   // Replace the uses of Ptr with uses of the updated base value.
7858   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7859   removeFromWorklist(Ptr.getNode());
7860   DAG.DeleteNode(Ptr.getNode());
7861
7862   return true;
7863 }
7864
7865 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7866 /// add / sub of the base pointer node into a post-indexed load / store.
7867 /// The transformation folded the add / subtract into the new indexed
7868 /// load / store effectively and all of its uses are redirected to the
7869 /// new load / store.
7870 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7871   if (Level < AfterLegalizeDAG)
7872     return false;
7873
7874   bool isLoad = true;
7875   SDValue Ptr;
7876   EVT VT;
7877   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7878     if (LD->isIndexed())
7879       return false;
7880     VT = LD->getMemoryVT();
7881     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7882         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7883       return false;
7884     Ptr = LD->getBasePtr();
7885   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7886     if (ST->isIndexed())
7887       return false;
7888     VT = ST->getMemoryVT();
7889     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7890         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7891       return false;
7892     Ptr = ST->getBasePtr();
7893     isLoad = false;
7894   } else {
7895     return false;
7896   }
7897
7898   if (Ptr.getNode()->hasOneUse())
7899     return false;
7900
7901   for (SDNode *Op : Ptr.getNode()->uses()) {
7902     if (Op == N ||
7903         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7904       continue;
7905
7906     SDValue BasePtr;
7907     SDValue Offset;
7908     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7909     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7910       // Don't create a indexed load / store with zero offset.
7911       if (isa<ConstantSDNode>(Offset) &&
7912           cast<ConstantSDNode>(Offset)->isNullValue())
7913         continue;
7914
7915       // Try turning it into a post-indexed load / store except when
7916       // 1) All uses are load / store ops that use it as base ptr (and
7917       //    it may be folded as addressing mmode).
7918       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7919       //    nor a successor of N. Otherwise, if Op is folded that would
7920       //    create a cycle.
7921
7922       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7923         continue;
7924
7925       // Check for #1.
7926       bool TryNext = false;
7927       for (SDNode *Use : BasePtr.getNode()->uses()) {
7928         if (Use == Ptr.getNode())
7929           continue;
7930
7931         // If all the uses are load / store addresses, then don't do the
7932         // transformation.
7933         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7934           bool RealUse = false;
7935           for (SDNode *UseUse : Use->uses()) {
7936             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7937               RealUse = true;
7938           }
7939
7940           if (!RealUse) {
7941             TryNext = true;
7942             break;
7943           }
7944         }
7945       }
7946
7947       if (TryNext)
7948         continue;
7949
7950       // Check for #2
7951       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7952         SDValue Result = isLoad
7953           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7954                                BasePtr, Offset, AM)
7955           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7956                                 BasePtr, Offset, AM);
7957         ++PostIndexedNodes;
7958         ++NodesCombined;
7959         DEBUG(dbgs() << "\nReplacing.5 ";
7960               N->dump(&DAG);
7961               dbgs() << "\nWith: ";
7962               Result.getNode()->dump(&DAG);
7963               dbgs() << '\n');
7964         WorklistRemover DeadNodes(*this);
7965         if (isLoad) {
7966           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7967           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7968         } else {
7969           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7970         }
7971
7972         // Finally, since the node is now dead, remove it from the graph.
7973         DAG.DeleteNode(N);
7974
7975         // Replace the uses of Use with uses of the updated base value.
7976         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7977                                       Result.getValue(isLoad ? 1 : 0));
7978         removeFromWorklist(Op);
7979         DAG.DeleteNode(Op);
7980         return true;
7981       }
7982     }
7983   }
7984
7985   return false;
7986 }
7987
7988 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7989   LoadSDNode *LD  = cast<LoadSDNode>(N);
7990   SDValue Chain = LD->getChain();
7991   SDValue Ptr   = LD->getBasePtr();
7992
7993   // If load is not volatile and there are no uses of the loaded value (and
7994   // the updated indexed value in case of indexed loads), change uses of the
7995   // chain value into uses of the chain input (i.e. delete the dead load).
7996   if (!LD->isVolatile()) {
7997     if (N->getValueType(1) == MVT::Other) {
7998       // Unindexed loads.
7999       if (!N->hasAnyUseOfValue(0)) {
8000         // It's not safe to use the two value CombineTo variant here. e.g.
8001         // v1, chain2 = load chain1, loc
8002         // v2, chain3 = load chain2, loc
8003         // v3         = add v2, c
8004         // Now we replace use of chain2 with chain1.  This makes the second load
8005         // isomorphic to the one we are deleting, and thus makes this load live.
8006         DEBUG(dbgs() << "\nReplacing.6 ";
8007               N->dump(&DAG);
8008               dbgs() << "\nWith chain: ";
8009               Chain.getNode()->dump(&DAG);
8010               dbgs() << "\n");
8011         WorklistRemover DeadNodes(*this);
8012         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8013
8014         if (N->use_empty()) {
8015           removeFromWorklist(N);
8016           DAG.DeleteNode(N);
8017         }
8018
8019         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8020       }
8021     } else {
8022       // Indexed loads.
8023       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8024       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8025         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8026         DEBUG(dbgs() << "\nReplacing.7 ";
8027               N->dump(&DAG);
8028               dbgs() << "\nWith: ";
8029               Undef.getNode()->dump(&DAG);
8030               dbgs() << " and 2 other values\n");
8031         WorklistRemover DeadNodes(*this);
8032         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8033         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8034                                       DAG.getUNDEF(N->getValueType(1)));
8035         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8036         removeFromWorklist(N);
8037         DAG.DeleteNode(N);
8038         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8039       }
8040     }
8041   }
8042
8043   // If this load is directly stored, replace the load value with the stored
8044   // value.
8045   // TODO: Handle store large -> read small portion.
8046   // TODO: Handle TRUNCSTORE/LOADEXT
8047   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8048     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8049       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8050       if (PrevST->getBasePtr() == Ptr &&
8051           PrevST->getValue().getValueType() == N->getValueType(0))
8052       return CombineTo(N, Chain.getOperand(1), Chain);
8053     }
8054   }
8055
8056   // Try to infer better alignment information than the load already has.
8057   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8058     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8059       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8060         SDValue NewLoad =
8061                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8062                               LD->getValueType(0),
8063                               Chain, Ptr, LD->getPointerInfo(),
8064                               LD->getMemoryVT(),
8065                               LD->isVolatile(), LD->isNonTemporal(),
8066                               LD->isInvariant(), Align, LD->getAAInfo());
8067         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8068       }
8069     }
8070   }
8071
8072   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8073     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8074 #ifndef NDEBUG
8075   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8076       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8077     UseAA = false;
8078 #endif
8079   if (UseAA && LD->isUnindexed()) {
8080     // Walk up chain skipping non-aliasing memory nodes.
8081     SDValue BetterChain = FindBetterChain(N, Chain);
8082
8083     // If there is a better chain.
8084     if (Chain != BetterChain) {
8085       SDValue ReplLoad;
8086
8087       // Replace the chain to void dependency.
8088       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8089         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8090                                BetterChain, Ptr, LD->getMemOperand());
8091       } else {
8092         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8093                                   LD->getValueType(0),
8094                                   BetterChain, Ptr, LD->getMemoryVT(),
8095                                   LD->getMemOperand());
8096       }
8097
8098       // Create token factor to keep old chain connected.
8099       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8100                                   MVT::Other, Chain, ReplLoad.getValue(1));
8101
8102       // Make sure the new and old chains are cleaned up.
8103       AddToWorklist(Token.getNode());
8104
8105       // Replace uses with load result and token factor. Don't add users
8106       // to work list.
8107       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8108     }
8109   }
8110
8111   // Try transforming N to an indexed load.
8112   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8113     return SDValue(N, 0);
8114
8115   // Try to slice up N to more direct loads if the slices are mapped to
8116   // different register banks or pairing can take place.
8117   if (SliceUpLoad(N))
8118     return SDValue(N, 0);
8119
8120   return SDValue();
8121 }
8122
8123 namespace {
8124 /// \brief Helper structure used to slice a load in smaller loads.
8125 /// Basically a slice is obtained from the following sequence:
8126 /// Origin = load Ty1, Base
8127 /// Shift = srl Ty1 Origin, CstTy Amount
8128 /// Inst = trunc Shift to Ty2
8129 ///
8130 /// Then, it will be rewriten into:
8131 /// Slice = load SliceTy, Base + SliceOffset
8132 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8133 ///
8134 /// SliceTy is deduced from the number of bits that are actually used to
8135 /// build Inst.
8136 struct LoadedSlice {
8137   /// \brief Helper structure used to compute the cost of a slice.
8138   struct Cost {
8139     /// Are we optimizing for code size.
8140     bool ForCodeSize;
8141     /// Various cost.
8142     unsigned Loads;
8143     unsigned Truncates;
8144     unsigned CrossRegisterBanksCopies;
8145     unsigned ZExts;
8146     unsigned Shift;
8147
8148     Cost(bool ForCodeSize = false)
8149         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8150           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8151
8152     /// \brief Get the cost of one isolated slice.
8153     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8154         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8155           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8156       EVT TruncType = LS.Inst->getValueType(0);
8157       EVT LoadedType = LS.getLoadedType();
8158       if (TruncType != LoadedType &&
8159           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8160         ZExts = 1;
8161     }
8162
8163     /// \brief Account for slicing gain in the current cost.
8164     /// Slicing provide a few gains like removing a shift or a
8165     /// truncate. This method allows to grow the cost of the original
8166     /// load with the gain from this slice.
8167     void addSliceGain(const LoadedSlice &LS) {
8168       // Each slice saves a truncate.
8169       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8170       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8171                               LS.Inst->getOperand(0).getValueType()))
8172         ++Truncates;
8173       // If there is a shift amount, this slice gets rid of it.
8174       if (LS.Shift)
8175         ++Shift;
8176       // If this slice can merge a cross register bank copy, account for it.
8177       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8178         ++CrossRegisterBanksCopies;
8179     }
8180
8181     Cost &operator+=(const Cost &RHS) {
8182       Loads += RHS.Loads;
8183       Truncates += RHS.Truncates;
8184       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8185       ZExts += RHS.ZExts;
8186       Shift += RHS.Shift;
8187       return *this;
8188     }
8189
8190     bool operator==(const Cost &RHS) const {
8191       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8192              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8193              ZExts == RHS.ZExts && Shift == RHS.Shift;
8194     }
8195
8196     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8197
8198     bool operator<(const Cost &RHS) const {
8199       // Assume cross register banks copies are as expensive as loads.
8200       // FIXME: Do we want some more target hooks?
8201       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8202       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8203       // Unless we are optimizing for code size, consider the
8204       // expensive operation first.
8205       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8206         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8207       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8208              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8209     }
8210
8211     bool operator>(const Cost &RHS) const { return RHS < *this; }
8212
8213     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8214
8215     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8216   };
8217   // The last instruction that represent the slice. This should be a
8218   // truncate instruction.
8219   SDNode *Inst;
8220   // The original load instruction.
8221   LoadSDNode *Origin;
8222   // The right shift amount in bits from the original load.
8223   unsigned Shift;
8224   // The DAG from which Origin came from.
8225   // This is used to get some contextual information about legal types, etc.
8226   SelectionDAG *DAG;
8227
8228   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8229               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8230       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8231
8232   LoadedSlice(const LoadedSlice &LS)
8233       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8234
8235   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8236   /// \return Result is \p BitWidth and has used bits set to 1 and
8237   ///         not used bits set to 0.
8238   APInt getUsedBits() const {
8239     // Reproduce the trunc(lshr) sequence:
8240     // - Start from the truncated value.
8241     // - Zero extend to the desired bit width.
8242     // - Shift left.
8243     assert(Origin && "No original load to compare against.");
8244     unsigned BitWidth = Origin->getValueSizeInBits(0);
8245     assert(Inst && "This slice is not bound to an instruction");
8246     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8247            "Extracted slice is bigger than the whole type!");
8248     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8249     UsedBits.setAllBits();
8250     UsedBits = UsedBits.zext(BitWidth);
8251     UsedBits <<= Shift;
8252     return UsedBits;
8253   }
8254
8255   /// \brief Get the size of the slice to be loaded in bytes.
8256   unsigned getLoadedSize() const {
8257     unsigned SliceSize = getUsedBits().countPopulation();
8258     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8259     return SliceSize / 8;
8260   }
8261
8262   /// \brief Get the type that will be loaded for this slice.
8263   /// Note: This may not be the final type for the slice.
8264   EVT getLoadedType() const {
8265     assert(DAG && "Missing context");
8266     LLVMContext &Ctxt = *DAG->getContext();
8267     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8268   }
8269
8270   /// \brief Get the alignment of the load used for this slice.
8271   unsigned getAlignment() const {
8272     unsigned Alignment = Origin->getAlignment();
8273     unsigned Offset = getOffsetFromBase();
8274     if (Offset != 0)
8275       Alignment = MinAlign(Alignment, Alignment + Offset);
8276     return Alignment;
8277   }
8278
8279   /// \brief Check if this slice can be rewritten with legal operations.
8280   bool isLegal() const {
8281     // An invalid slice is not legal.
8282     if (!Origin || !Inst || !DAG)
8283       return false;
8284
8285     // Offsets are for indexed load only, we do not handle that.
8286     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8287       return false;
8288
8289     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8290
8291     // Check that the type is legal.
8292     EVT SliceType = getLoadedType();
8293     if (!TLI.isTypeLegal(SliceType))
8294       return false;
8295
8296     // Check that the load is legal for this type.
8297     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8298       return false;
8299
8300     // Check that the offset can be computed.
8301     // 1. Check its type.
8302     EVT PtrType = Origin->getBasePtr().getValueType();
8303     if (PtrType == MVT::Untyped || PtrType.isExtended())
8304       return false;
8305
8306     // 2. Check that it fits in the immediate.
8307     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8308       return false;
8309
8310     // 3. Check that the computation is legal.
8311     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8312       return false;
8313
8314     // Check that the zext is legal if it needs one.
8315     EVT TruncateType = Inst->getValueType(0);
8316     if (TruncateType != SliceType &&
8317         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8318       return false;
8319
8320     return true;
8321   }
8322
8323   /// \brief Get the offset in bytes of this slice in the original chunk of
8324   /// bits.
8325   /// \pre DAG != nullptr.
8326   uint64_t getOffsetFromBase() const {
8327     assert(DAG && "Missing context.");
8328     bool IsBigEndian =
8329         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8330     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8331     uint64_t Offset = Shift / 8;
8332     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8333     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8334            "The size of the original loaded type is not a multiple of a"
8335            " byte.");
8336     // If Offset is bigger than TySizeInBytes, it means we are loading all
8337     // zeros. This should have been optimized before in the process.
8338     assert(TySizeInBytes > Offset &&
8339            "Invalid shift amount for given loaded size");
8340     if (IsBigEndian)
8341       Offset = TySizeInBytes - Offset - getLoadedSize();
8342     return Offset;
8343   }
8344
8345   /// \brief Generate the sequence of instructions to load the slice
8346   /// represented by this object and redirect the uses of this slice to
8347   /// this new sequence of instructions.
8348   /// \pre this->Inst && this->Origin are valid Instructions and this
8349   /// object passed the legal check: LoadedSlice::isLegal returned true.
8350   /// \return The last instruction of the sequence used to load the slice.
8351   SDValue loadSlice() const {
8352     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8353     const SDValue &OldBaseAddr = Origin->getBasePtr();
8354     SDValue BaseAddr = OldBaseAddr;
8355     // Get the offset in that chunk of bytes w.r.t. the endianess.
8356     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8357     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8358     if (Offset) {
8359       // BaseAddr = BaseAddr + Offset.
8360       EVT ArithType = BaseAddr.getValueType();
8361       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8362                               DAG->getConstant(Offset, ArithType));
8363     }
8364
8365     // Create the type of the loaded slice according to its size.
8366     EVT SliceType = getLoadedType();
8367
8368     // Create the load for the slice.
8369     SDValue LastInst = DAG->getLoad(
8370         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8371         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8372         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8373     // If the final type is not the same as the loaded type, this means that
8374     // we have to pad with zero. Create a zero extend for that.
8375     EVT FinalType = Inst->getValueType(0);
8376     if (SliceType != FinalType)
8377       LastInst =
8378           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8379     return LastInst;
8380   }
8381
8382   /// \brief Check if this slice can be merged with an expensive cross register
8383   /// bank copy. E.g.,
8384   /// i = load i32
8385   /// f = bitcast i32 i to float
8386   bool canMergeExpensiveCrossRegisterBankCopy() const {
8387     if (!Inst || !Inst->hasOneUse())
8388       return false;
8389     SDNode *Use = *Inst->use_begin();
8390     if (Use->getOpcode() != ISD::BITCAST)
8391       return false;
8392     assert(DAG && "Missing context");
8393     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8394     EVT ResVT = Use->getValueType(0);
8395     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8396     const TargetRegisterClass *ArgRC =
8397         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8398     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8399       return false;
8400
8401     // At this point, we know that we perform a cross-register-bank copy.
8402     // Check if it is expensive.
8403     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8404     // Assume bitcasts are cheap, unless both register classes do not
8405     // explicitly share a common sub class.
8406     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8407       return false;
8408
8409     // Check if it will be merged with the load.
8410     // 1. Check the alignment constraint.
8411     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8412         ResVT.getTypeForEVT(*DAG->getContext()));
8413
8414     if (RequiredAlignment > getAlignment())
8415       return false;
8416
8417     // 2. Check that the load is a legal operation for that type.
8418     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8419       return false;
8420
8421     // 3. Check that we do not have a zext in the way.
8422     if (Inst->getValueType(0) != getLoadedType())
8423       return false;
8424
8425     return true;
8426   }
8427 };
8428 }
8429
8430 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8431 /// \p UsedBits looks like 0..0 1..1 0..0.
8432 static bool areUsedBitsDense(const APInt &UsedBits) {
8433   // If all the bits are one, this is dense!
8434   if (UsedBits.isAllOnesValue())
8435     return true;
8436
8437   // Get rid of the unused bits on the right.
8438   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8439   // Get rid of the unused bits on the left.
8440   if (NarrowedUsedBits.countLeadingZeros())
8441     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8442   // Check that the chunk of bits is completely used.
8443   return NarrowedUsedBits.isAllOnesValue();
8444 }
8445
8446 /// \brief Check whether or not \p First and \p Second are next to each other
8447 /// in memory. This means that there is no hole between the bits loaded
8448 /// by \p First and the bits loaded by \p Second.
8449 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8450                                      const LoadedSlice &Second) {
8451   assert(First.Origin == Second.Origin && First.Origin &&
8452          "Unable to match different memory origins.");
8453   APInt UsedBits = First.getUsedBits();
8454   assert((UsedBits & Second.getUsedBits()) == 0 &&
8455          "Slices are not supposed to overlap.");
8456   UsedBits |= Second.getUsedBits();
8457   return areUsedBitsDense(UsedBits);
8458 }
8459
8460 /// \brief Adjust the \p GlobalLSCost according to the target
8461 /// paring capabilities and the layout of the slices.
8462 /// \pre \p GlobalLSCost should account for at least as many loads as
8463 /// there is in the slices in \p LoadedSlices.
8464 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8465                                  LoadedSlice::Cost &GlobalLSCost) {
8466   unsigned NumberOfSlices = LoadedSlices.size();
8467   // If there is less than 2 elements, no pairing is possible.
8468   if (NumberOfSlices < 2)
8469     return;
8470
8471   // Sort the slices so that elements that are likely to be next to each
8472   // other in memory are next to each other in the list.
8473   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8474             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8475     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8476     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8477   });
8478   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8479   // First (resp. Second) is the first (resp. Second) potentially candidate
8480   // to be placed in a paired load.
8481   const LoadedSlice *First = nullptr;
8482   const LoadedSlice *Second = nullptr;
8483   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8484                 // Set the beginning of the pair.
8485                                                            First = Second) {
8486
8487     Second = &LoadedSlices[CurrSlice];
8488
8489     // If First is NULL, it means we start a new pair.
8490     // Get to the next slice.
8491     if (!First)
8492       continue;
8493
8494     EVT LoadedType = First->getLoadedType();
8495
8496     // If the types of the slices are different, we cannot pair them.
8497     if (LoadedType != Second->getLoadedType())
8498       continue;
8499
8500     // Check if the target supplies paired loads for this type.
8501     unsigned RequiredAlignment = 0;
8502     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8503       // move to the next pair, this type is hopeless.
8504       Second = nullptr;
8505       continue;
8506     }
8507     // Check if we meet the alignment requirement.
8508     if (RequiredAlignment > First->getAlignment())
8509       continue;
8510
8511     // Check that both loads are next to each other in memory.
8512     if (!areSlicesNextToEachOther(*First, *Second))
8513       continue;
8514
8515     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8516     --GlobalLSCost.Loads;
8517     // Move to the next pair.
8518     Second = nullptr;
8519   }
8520 }
8521
8522 /// \brief Check the profitability of all involved LoadedSlice.
8523 /// Currently, it is considered profitable if there is exactly two
8524 /// involved slices (1) which are (2) next to each other in memory, and
8525 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8526 ///
8527 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8528 /// the elements themselves.
8529 ///
8530 /// FIXME: When the cost model will be mature enough, we can relax
8531 /// constraints (1) and (2).
8532 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8533                                 const APInt &UsedBits, bool ForCodeSize) {
8534   unsigned NumberOfSlices = LoadedSlices.size();
8535   if (StressLoadSlicing)
8536     return NumberOfSlices > 1;
8537
8538   // Check (1).
8539   if (NumberOfSlices != 2)
8540     return false;
8541
8542   // Check (2).
8543   if (!areUsedBitsDense(UsedBits))
8544     return false;
8545
8546   // Check (3).
8547   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8548   // The original code has one big load.
8549   OrigCost.Loads = 1;
8550   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8551     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8552     // Accumulate the cost of all the slices.
8553     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8554     GlobalSlicingCost += SliceCost;
8555
8556     // Account as cost in the original configuration the gain obtained
8557     // with the current slices.
8558     OrigCost.addSliceGain(LS);
8559   }
8560
8561   // If the target supports paired load, adjust the cost accordingly.
8562   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8563   return OrigCost > GlobalSlicingCost;
8564 }
8565
8566 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8567 /// operations, split it in the various pieces being extracted.
8568 ///
8569 /// This sort of thing is introduced by SROA.
8570 /// This slicing takes care not to insert overlapping loads.
8571 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8572 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8573   if (Level < AfterLegalizeDAG)
8574     return false;
8575
8576   LoadSDNode *LD = cast<LoadSDNode>(N);
8577   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8578       !LD->getValueType(0).isInteger())
8579     return false;
8580
8581   // Keep track of already used bits to detect overlapping values.
8582   // In that case, we will just abort the transformation.
8583   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8584
8585   SmallVector<LoadedSlice, 4> LoadedSlices;
8586
8587   // Check if this load is used as several smaller chunks of bits.
8588   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8589   // of computation for each trunc.
8590   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8591        UI != UIEnd; ++UI) {
8592     // Skip the uses of the chain.
8593     if (UI.getUse().getResNo() != 0)
8594       continue;
8595
8596     SDNode *User = *UI;
8597     unsigned Shift = 0;
8598
8599     // Check if this is a trunc(lshr).
8600     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8601         isa<ConstantSDNode>(User->getOperand(1))) {
8602       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8603       User = *User->use_begin();
8604     }
8605
8606     // At this point, User is a Truncate, iff we encountered, trunc or
8607     // trunc(lshr).
8608     if (User->getOpcode() != ISD::TRUNCATE)
8609       return false;
8610
8611     // The width of the type must be a power of 2 and greater than 8-bits.
8612     // Otherwise the load cannot be represented in LLVM IR.
8613     // Moreover, if we shifted with a non-8-bits multiple, the slice
8614     // will be across several bytes. We do not support that.
8615     unsigned Width = User->getValueSizeInBits(0);
8616     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8617       return 0;
8618
8619     // Build the slice for this chain of computations.
8620     LoadedSlice LS(User, LD, Shift, &DAG);
8621     APInt CurrentUsedBits = LS.getUsedBits();
8622
8623     // Check if this slice overlaps with another.
8624     if ((CurrentUsedBits & UsedBits) != 0)
8625       return false;
8626     // Update the bits used globally.
8627     UsedBits |= CurrentUsedBits;
8628
8629     // Check if the new slice would be legal.
8630     if (!LS.isLegal())
8631       return false;
8632
8633     // Record the slice.
8634     LoadedSlices.push_back(LS);
8635   }
8636
8637   // Abort slicing if it does not seem to be profitable.
8638   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8639     return false;
8640
8641   ++SlicedLoads;
8642
8643   // Rewrite each chain to use an independent load.
8644   // By construction, each chain can be represented by a unique load.
8645
8646   // Prepare the argument for the new token factor for all the slices.
8647   SmallVector<SDValue, 8> ArgChains;
8648   for (SmallVectorImpl<LoadedSlice>::const_iterator
8649            LSIt = LoadedSlices.begin(),
8650            LSItEnd = LoadedSlices.end();
8651        LSIt != LSItEnd; ++LSIt) {
8652     SDValue SliceInst = LSIt->loadSlice();
8653     CombineTo(LSIt->Inst, SliceInst, true);
8654     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8655       SliceInst = SliceInst.getOperand(0);
8656     assert(SliceInst->getOpcode() == ISD::LOAD &&
8657            "It takes more than a zext to get to the loaded slice!!");
8658     ArgChains.push_back(SliceInst.getValue(1));
8659   }
8660
8661   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8662                               ArgChains);
8663   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8664   return true;
8665 }
8666
8667 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8668 /// load is having specific bytes cleared out.  If so, return the byte size
8669 /// being masked out and the shift amount.
8670 static std::pair<unsigned, unsigned>
8671 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8672   std::pair<unsigned, unsigned> Result(0, 0);
8673
8674   // Check for the structure we're looking for.
8675   if (V->getOpcode() != ISD::AND ||
8676       !isa<ConstantSDNode>(V->getOperand(1)) ||
8677       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8678     return Result;
8679
8680   // Check the chain and pointer.
8681   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8682   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8683
8684   // The store should be chained directly to the load or be an operand of a
8685   // tokenfactor.
8686   if (LD == Chain.getNode())
8687     ; // ok.
8688   else if (Chain->getOpcode() != ISD::TokenFactor)
8689     return Result; // Fail.
8690   else {
8691     bool isOk = false;
8692     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8693       if (Chain->getOperand(i).getNode() == LD) {
8694         isOk = true;
8695         break;
8696       }
8697     if (!isOk) return Result;
8698   }
8699
8700   // This only handles simple types.
8701   if (V.getValueType() != MVT::i16 &&
8702       V.getValueType() != MVT::i32 &&
8703       V.getValueType() != MVT::i64)
8704     return Result;
8705
8706   // Check the constant mask.  Invert it so that the bits being masked out are
8707   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8708   // follow the sign bit for uniformity.
8709   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8710   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8711   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8712   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8713   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8714   if (NotMaskLZ == 64) return Result;  // All zero mask.
8715
8716   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8717   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8718     return Result;
8719
8720   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8721   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8722     NotMaskLZ -= 64-V.getValueSizeInBits();
8723
8724   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8725   switch (MaskedBytes) {
8726   case 1:
8727   case 2:
8728   case 4: break;
8729   default: return Result; // All one mask, or 5-byte mask.
8730   }
8731
8732   // Verify that the first bit starts at a multiple of mask so that the access
8733   // is aligned the same as the access width.
8734   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8735
8736   Result.first = MaskedBytes;
8737   Result.second = NotMaskTZ/8;
8738   return Result;
8739 }
8740
8741
8742 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8743 /// provides a value as specified by MaskInfo.  If so, replace the specified
8744 /// store with a narrower store of truncated IVal.
8745 static SDNode *
8746 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8747                                 SDValue IVal, StoreSDNode *St,
8748                                 DAGCombiner *DC) {
8749   unsigned NumBytes = MaskInfo.first;
8750   unsigned ByteShift = MaskInfo.second;
8751   SelectionDAG &DAG = DC->getDAG();
8752
8753   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8754   // that uses this.  If not, this is not a replacement.
8755   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8756                                   ByteShift*8, (ByteShift+NumBytes)*8);
8757   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8758
8759   // Check that it is legal on the target to do this.  It is legal if the new
8760   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8761   // legalization.
8762   MVT VT = MVT::getIntegerVT(NumBytes*8);
8763   if (!DC->isTypeLegal(VT))
8764     return nullptr;
8765
8766   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8767   // shifted by ByteShift and truncated down to NumBytes.
8768   if (ByteShift)
8769     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8770                        DAG.getConstant(ByteShift*8,
8771                                     DC->getShiftAmountTy(IVal.getValueType())));
8772
8773   // Figure out the offset for the store and the alignment of the access.
8774   unsigned StOffset;
8775   unsigned NewAlign = St->getAlignment();
8776
8777   if (DAG.getTargetLoweringInfo().isLittleEndian())
8778     StOffset = ByteShift;
8779   else
8780     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8781
8782   SDValue Ptr = St->getBasePtr();
8783   if (StOffset) {
8784     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8785                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8786     NewAlign = MinAlign(NewAlign, StOffset);
8787   }
8788
8789   // Truncate down to the new size.
8790   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8791
8792   ++OpsNarrowed;
8793   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8794                       St->getPointerInfo().getWithOffset(StOffset),
8795                       false, false, NewAlign).getNode();
8796 }
8797
8798
8799 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8800 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8801 /// of the loaded bits, try narrowing the load and store if it would end up
8802 /// being a win for performance or code size.
8803 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8804   StoreSDNode *ST  = cast<StoreSDNode>(N);
8805   if (ST->isVolatile())
8806     return SDValue();
8807
8808   SDValue Chain = ST->getChain();
8809   SDValue Value = ST->getValue();
8810   SDValue Ptr   = ST->getBasePtr();
8811   EVT VT = Value.getValueType();
8812
8813   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8814     return SDValue();
8815
8816   unsigned Opc = Value.getOpcode();
8817
8818   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8819   // is a byte mask indicating a consecutive number of bytes, check to see if
8820   // Y is known to provide just those bytes.  If so, we try to replace the
8821   // load + replace + store sequence with a single (narrower) store, which makes
8822   // the load dead.
8823   if (Opc == ISD::OR) {
8824     std::pair<unsigned, unsigned> MaskedLoad;
8825     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8826     if (MaskedLoad.first)
8827       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8828                                                   Value.getOperand(1), ST,this))
8829         return SDValue(NewST, 0);
8830
8831     // Or is commutative, so try swapping X and Y.
8832     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8833     if (MaskedLoad.first)
8834       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8835                                                   Value.getOperand(0), ST,this))
8836         return SDValue(NewST, 0);
8837   }
8838
8839   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8840       Value.getOperand(1).getOpcode() != ISD::Constant)
8841     return SDValue();
8842
8843   SDValue N0 = Value.getOperand(0);
8844   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8845       Chain == SDValue(N0.getNode(), 1)) {
8846     LoadSDNode *LD = cast<LoadSDNode>(N0);
8847     if (LD->getBasePtr() != Ptr ||
8848         LD->getPointerInfo().getAddrSpace() !=
8849         ST->getPointerInfo().getAddrSpace())
8850       return SDValue();
8851
8852     // Find the type to narrow it the load / op / store to.
8853     SDValue N1 = Value.getOperand(1);
8854     unsigned BitWidth = N1.getValueSizeInBits();
8855     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8856     if (Opc == ISD::AND)
8857       Imm ^= APInt::getAllOnesValue(BitWidth);
8858     if (Imm == 0 || Imm.isAllOnesValue())
8859       return SDValue();
8860     unsigned ShAmt = Imm.countTrailingZeros();
8861     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8862     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8863     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8864     while (NewBW < BitWidth &&
8865            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8866              TLI.isNarrowingProfitable(VT, NewVT))) {
8867       NewBW = NextPowerOf2(NewBW);
8868       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8869     }
8870     if (NewBW >= BitWidth)
8871       return SDValue();
8872
8873     // If the lsb changed does not start at the type bitwidth boundary,
8874     // start at the previous one.
8875     if (ShAmt % NewBW)
8876       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8877     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8878                                    std::min(BitWidth, ShAmt + NewBW));
8879     if ((Imm & Mask) == Imm) {
8880       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8881       if (Opc == ISD::AND)
8882         NewImm ^= APInt::getAllOnesValue(NewBW);
8883       uint64_t PtrOff = ShAmt / 8;
8884       // For big endian targets, we need to adjust the offset to the pointer to
8885       // load the correct bytes.
8886       if (TLI.isBigEndian())
8887         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8888
8889       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8890       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8891       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8892         return SDValue();
8893
8894       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8895                                    Ptr.getValueType(), Ptr,
8896                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8897       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8898                                   LD->getChain(), NewPtr,
8899                                   LD->getPointerInfo().getWithOffset(PtrOff),
8900                                   LD->isVolatile(), LD->isNonTemporal(),
8901                                   LD->isInvariant(), NewAlign,
8902                                   LD->getAAInfo());
8903       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8904                                    DAG.getConstant(NewImm, NewVT));
8905       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8906                                    NewVal, NewPtr,
8907                                    ST->getPointerInfo().getWithOffset(PtrOff),
8908                                    false, false, NewAlign);
8909
8910       AddToWorklist(NewPtr.getNode());
8911       AddToWorklist(NewLD.getNode());
8912       AddToWorklist(NewVal.getNode());
8913       WorklistRemover DeadNodes(*this);
8914       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8915       ++OpsNarrowed;
8916       return NewST;
8917     }
8918   }
8919
8920   return SDValue();
8921 }
8922
8923 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8924 /// if the load value isn't used by any other operations, then consider
8925 /// transforming the pair to integer load / store operations if the target
8926 /// deems the transformation profitable.
8927 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8928   StoreSDNode *ST  = cast<StoreSDNode>(N);
8929   SDValue Chain = ST->getChain();
8930   SDValue Value = ST->getValue();
8931   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8932       Value.hasOneUse() &&
8933       Chain == SDValue(Value.getNode(), 1)) {
8934     LoadSDNode *LD = cast<LoadSDNode>(Value);
8935     EVT VT = LD->getMemoryVT();
8936     if (!VT.isFloatingPoint() ||
8937         VT != ST->getMemoryVT() ||
8938         LD->isNonTemporal() ||
8939         ST->isNonTemporal() ||
8940         LD->getPointerInfo().getAddrSpace() != 0 ||
8941         ST->getPointerInfo().getAddrSpace() != 0)
8942       return SDValue();
8943
8944     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8945     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8946         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8947         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8948         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8949       return SDValue();
8950
8951     unsigned LDAlign = LD->getAlignment();
8952     unsigned STAlign = ST->getAlignment();
8953     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8954     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8955     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8956       return SDValue();
8957
8958     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8959                                 LD->getChain(), LD->getBasePtr(),
8960                                 LD->getPointerInfo(),
8961                                 false, false, false, LDAlign);
8962
8963     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8964                                  NewLD, ST->getBasePtr(),
8965                                  ST->getPointerInfo(),
8966                                  false, false, STAlign);
8967
8968     AddToWorklist(NewLD.getNode());
8969     AddToWorklist(NewST.getNode());
8970     WorklistRemover DeadNodes(*this);
8971     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8972     ++LdStFP2Int;
8973     return NewST;
8974   }
8975
8976   return SDValue();
8977 }
8978
8979 /// Helper struct to parse and store a memory address as base + index + offset.
8980 /// We ignore sign extensions when it is safe to do so.
8981 /// The following two expressions are not equivalent. To differentiate we need
8982 /// to store whether there was a sign extension involved in the index
8983 /// computation.
8984 ///  (load (i64 add (i64 copyfromreg %c)
8985 ///                 (i64 signextend (add (i8 load %index)
8986 ///                                      (i8 1))))
8987 /// vs
8988 ///
8989 /// (load (i64 add (i64 copyfromreg %c)
8990 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8991 ///                                         (i32 1)))))
8992 struct BaseIndexOffset {
8993   SDValue Base;
8994   SDValue Index;
8995   int64_t Offset;
8996   bool IsIndexSignExt;
8997
8998   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8999
9000   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9001                   bool IsIndexSignExt) :
9002     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9003
9004   bool equalBaseIndex(const BaseIndexOffset &Other) {
9005     return Other.Base == Base && Other.Index == Index &&
9006       Other.IsIndexSignExt == IsIndexSignExt;
9007   }
9008
9009   /// Parses tree in Ptr for base, index, offset addresses.
9010   static BaseIndexOffset match(SDValue Ptr) {
9011     bool IsIndexSignExt = false;
9012
9013     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9014     // instruction, then it could be just the BASE or everything else we don't
9015     // know how to handle. Just use Ptr as BASE and give up.
9016     if (Ptr->getOpcode() != ISD::ADD)
9017       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9018
9019     // We know that we have at least an ADD instruction. Try to pattern match
9020     // the simple case of BASE + OFFSET.
9021     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9022       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9023       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9024                               IsIndexSignExt);
9025     }
9026
9027     // Inside a loop the current BASE pointer is calculated using an ADD and a
9028     // MUL instruction. In this case Ptr is the actual BASE pointer.
9029     // (i64 add (i64 %array_ptr)
9030     //          (i64 mul (i64 %induction_var)
9031     //                   (i64 %element_size)))
9032     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9033       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9034
9035     // Look at Base + Index + Offset cases.
9036     SDValue Base = Ptr->getOperand(0);
9037     SDValue IndexOffset = Ptr->getOperand(1);
9038
9039     // Skip signextends.
9040     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9041       IndexOffset = IndexOffset->getOperand(0);
9042       IsIndexSignExt = true;
9043     }
9044
9045     // Either the case of Base + Index (no offset) or something else.
9046     if (IndexOffset->getOpcode() != ISD::ADD)
9047       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9048
9049     // Now we have the case of Base + Index + offset.
9050     SDValue Index = IndexOffset->getOperand(0);
9051     SDValue Offset = IndexOffset->getOperand(1);
9052
9053     if (!isa<ConstantSDNode>(Offset))
9054       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9055
9056     // Ignore signextends.
9057     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9058       Index = Index->getOperand(0);
9059       IsIndexSignExt = true;
9060     } else IsIndexSignExt = false;
9061
9062     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9063     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9064   }
9065 };
9066
9067 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9068 /// is located in a sequence of memory operations connected by a chain.
9069 struct MemOpLink {
9070   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9071     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9072   // Ptr to the mem node.
9073   LSBaseSDNode *MemNode;
9074   // Offset from the base ptr.
9075   int64_t OffsetFromBase;
9076   // What is the sequence number of this mem node.
9077   // Lowest mem operand in the DAG starts at zero.
9078   unsigned SequenceNum;
9079 };
9080
9081 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9082   EVT MemVT = St->getMemoryVT();
9083   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9084   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9085     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9086
9087   // Don't merge vectors into wider inputs.
9088   if (MemVT.isVector() || !MemVT.isSimple())
9089     return false;
9090
9091   // Perform an early exit check. Do not bother looking at stored values that
9092   // are not constants or loads.
9093   SDValue StoredVal = St->getValue();
9094   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9095   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9096       !IsLoadSrc)
9097     return false;
9098
9099   // Only look at ends of store sequences.
9100   SDValue Chain = SDValue(St, 0);
9101   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9102     return false;
9103
9104   // This holds the base pointer, index, and the offset in bytes from the base
9105   // pointer.
9106   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9107
9108   // We must have a base and an offset.
9109   if (!BasePtr.Base.getNode())
9110     return false;
9111
9112   // Do not handle stores to undef base pointers.
9113   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9114     return false;
9115
9116   // Save the LoadSDNodes that we find in the chain.
9117   // We need to make sure that these nodes do not interfere with
9118   // any of the store nodes.
9119   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9120
9121   // Save the StoreSDNodes that we find in the chain.
9122   SmallVector<MemOpLink, 8> StoreNodes;
9123
9124   // Walk up the chain and look for nodes with offsets from the same
9125   // base pointer. Stop when reaching an instruction with a different kind
9126   // or instruction which has a different base pointer.
9127   unsigned Seq = 0;
9128   StoreSDNode *Index = St;
9129   while (Index) {
9130     // If the chain has more than one use, then we can't reorder the mem ops.
9131     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9132       break;
9133
9134     // Find the base pointer and offset for this memory node.
9135     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9136
9137     // Check that the base pointer is the same as the original one.
9138     if (!Ptr.equalBaseIndex(BasePtr))
9139       break;
9140
9141     // Check that the alignment is the same.
9142     if (Index->getAlignment() != St->getAlignment())
9143       break;
9144
9145     // The memory operands must not be volatile.
9146     if (Index->isVolatile() || Index->isIndexed())
9147       break;
9148
9149     // No truncation.
9150     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9151       if (St->isTruncatingStore())
9152         break;
9153
9154     // The stored memory type must be the same.
9155     if (Index->getMemoryVT() != MemVT)
9156       break;
9157
9158     // We do not allow unaligned stores because we want to prevent overriding
9159     // stores.
9160     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9161       break;
9162
9163     // We found a potential memory operand to merge.
9164     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9165
9166     // Find the next memory operand in the chain. If the next operand in the
9167     // chain is a store then move up and continue the scan with the next
9168     // memory operand. If the next operand is a load save it and use alias
9169     // information to check if it interferes with anything.
9170     SDNode *NextInChain = Index->getChain().getNode();
9171     while (1) {
9172       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9173         // We found a store node. Use it for the next iteration.
9174         Index = STn;
9175         break;
9176       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9177         if (Ldn->isVolatile()) {
9178           Index = nullptr;
9179           break;
9180         }
9181
9182         // Save the load node for later. Continue the scan.
9183         AliasLoadNodes.push_back(Ldn);
9184         NextInChain = Ldn->getChain().getNode();
9185         continue;
9186       } else {
9187         Index = nullptr;
9188         break;
9189       }
9190     }
9191   }
9192
9193   // Check if there is anything to merge.
9194   if (StoreNodes.size() < 2)
9195     return false;
9196
9197   // Sort the memory operands according to their distance from the base pointer.
9198   std::sort(StoreNodes.begin(), StoreNodes.end(),
9199             [](MemOpLink LHS, MemOpLink RHS) {
9200     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9201            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9202             LHS.SequenceNum > RHS.SequenceNum);
9203   });
9204
9205   // Scan the memory operations on the chain and find the first non-consecutive
9206   // store memory address.
9207   unsigned LastConsecutiveStore = 0;
9208   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9209   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9210
9211     // Check that the addresses are consecutive starting from the second
9212     // element in the list of stores.
9213     if (i > 0) {
9214       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9215       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9216         break;
9217     }
9218
9219     bool Alias = false;
9220     // Check if this store interferes with any of the loads that we found.
9221     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9222       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9223         Alias = true;
9224         break;
9225       }
9226     // We found a load that alias with this store. Stop the sequence.
9227     if (Alias)
9228       break;
9229
9230     // Mark this node as useful.
9231     LastConsecutiveStore = i;
9232   }
9233
9234   // The node with the lowest store address.
9235   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9236
9237   // Store the constants into memory as one consecutive store.
9238   if (!IsLoadSrc) {
9239     unsigned LastLegalType = 0;
9240     unsigned LastLegalVectorType = 0;
9241     bool NonZero = false;
9242     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9243       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9244       SDValue StoredVal = St->getValue();
9245
9246       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9247         NonZero |= !C->isNullValue();
9248       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9249         NonZero |= !C->getConstantFPValue()->isNullValue();
9250       } else {
9251         // Non-constant.
9252         break;
9253       }
9254
9255       // Find a legal type for the constant store.
9256       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9257       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9258       if (TLI.isTypeLegal(StoreTy))
9259         LastLegalType = i+1;
9260       // Or check whether a truncstore is legal.
9261       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9262                TargetLowering::TypePromoteInteger) {
9263         EVT LegalizedStoredValueTy =
9264           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9265         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9266           LastLegalType = i+1;
9267       }
9268
9269       // Find a legal type for the vector store.
9270       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9271       if (TLI.isTypeLegal(Ty))
9272         LastLegalVectorType = i + 1;
9273     }
9274
9275     // We only use vectors if the constant is known to be zero and the
9276     // function is not marked with the noimplicitfloat attribute.
9277     if (NonZero || NoVectors)
9278       LastLegalVectorType = 0;
9279
9280     // Check if we found a legal integer type to store.
9281     if (LastLegalType == 0 && LastLegalVectorType == 0)
9282       return false;
9283
9284     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9285     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9286
9287     // Make sure we have something to merge.
9288     if (NumElem < 2)
9289       return false;
9290
9291     unsigned EarliestNodeUsed = 0;
9292     for (unsigned i=0; i < NumElem; ++i) {
9293       // Find a chain for the new wide-store operand. Notice that some
9294       // of the store nodes that we found may not be selected for inclusion
9295       // in the wide store. The chain we use needs to be the chain of the
9296       // earliest store node which is *used* and replaced by the wide store.
9297       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9298         EarliestNodeUsed = i;
9299     }
9300
9301     // The earliest Node in the DAG.
9302     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9303     SDLoc DL(StoreNodes[0].MemNode);
9304
9305     SDValue StoredVal;
9306     if (UseVector) {
9307       // Find a legal type for the vector store.
9308       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9309       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9310       StoredVal = DAG.getConstant(0, Ty);
9311     } else {
9312       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9313       APInt StoreInt(StoreBW, 0);
9314
9315       // Construct a single integer constant which is made of the smaller
9316       // constant inputs.
9317       bool IsLE = TLI.isLittleEndian();
9318       for (unsigned i = 0; i < NumElem ; ++i) {
9319         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9320         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9321         SDValue Val = St->getValue();
9322         StoreInt<<=ElementSizeBytes*8;
9323         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9324           StoreInt|=C->getAPIntValue().zext(StoreBW);
9325         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9326           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9327         } else {
9328           assert(false && "Invalid constant element type");
9329         }
9330       }
9331
9332       // Create the new Load and Store operations.
9333       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9334       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9335     }
9336
9337     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9338                                     FirstInChain->getBasePtr(),
9339                                     FirstInChain->getPointerInfo(),
9340                                     false, false,
9341                                     FirstInChain->getAlignment());
9342
9343     // Replace the first store with the new store
9344     CombineTo(EarliestOp, NewStore);
9345     // Erase all other stores.
9346     for (unsigned i = 0; i < NumElem ; ++i) {
9347       if (StoreNodes[i].MemNode == EarliestOp)
9348         continue;
9349       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9350       // ReplaceAllUsesWith will replace all uses that existed when it was
9351       // called, but graph optimizations may cause new ones to appear. For
9352       // example, the case in pr14333 looks like
9353       //
9354       //  St's chain -> St -> another store -> X
9355       //
9356       // And the only difference from St to the other store is the chain.
9357       // When we change it's chain to be St's chain they become identical,
9358       // get CSEed and the net result is that X is now a use of St.
9359       // Since we know that St is redundant, just iterate.
9360       while (!St->use_empty())
9361         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9362       removeFromWorklist(St);
9363       DAG.DeleteNode(St);
9364     }
9365
9366     return true;
9367   }
9368
9369   // Below we handle the case of multiple consecutive stores that
9370   // come from multiple consecutive loads. We merge them into a single
9371   // wide load and a single wide store.
9372
9373   // Look for load nodes which are used by the stored values.
9374   SmallVector<MemOpLink, 8> LoadNodes;
9375
9376   // Find acceptable loads. Loads need to have the same chain (token factor),
9377   // must not be zext, volatile, indexed, and they must be consecutive.
9378   BaseIndexOffset LdBasePtr;
9379   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9380     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9381     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9382     if (!Ld) break;
9383
9384     // Loads must only have one use.
9385     if (!Ld->hasNUsesOfValue(1, 0))
9386       break;
9387
9388     // Check that the alignment is the same as the stores.
9389     if (Ld->getAlignment() != St->getAlignment())
9390       break;
9391
9392     // The memory operands must not be volatile.
9393     if (Ld->isVolatile() || Ld->isIndexed())
9394       break;
9395
9396     // We do not accept ext loads.
9397     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9398       break;
9399
9400     // The stored memory type must be the same.
9401     if (Ld->getMemoryVT() != MemVT)
9402       break;
9403
9404     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9405     // If this is not the first ptr that we check.
9406     if (LdBasePtr.Base.getNode()) {
9407       // The base ptr must be the same.
9408       if (!LdPtr.equalBaseIndex(LdBasePtr))
9409         break;
9410     } else {
9411       // Check that all other base pointers are the same as this one.
9412       LdBasePtr = LdPtr;
9413     }
9414
9415     // We found a potential memory operand to merge.
9416     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9417   }
9418
9419   if (LoadNodes.size() < 2)
9420     return false;
9421
9422   // Scan the memory operations on the chain and find the first non-consecutive
9423   // load memory address. These variables hold the index in the store node
9424   // array.
9425   unsigned LastConsecutiveLoad = 0;
9426   // This variable refers to the size and not index in the array.
9427   unsigned LastLegalVectorType = 0;
9428   unsigned LastLegalIntegerType = 0;
9429   StartAddress = LoadNodes[0].OffsetFromBase;
9430   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9431   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9432     // All loads much share the same chain.
9433     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9434       break;
9435
9436     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9437     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9438       break;
9439     LastConsecutiveLoad = i;
9440
9441     // Find a legal type for the vector store.
9442     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9443     if (TLI.isTypeLegal(StoreTy))
9444       LastLegalVectorType = i + 1;
9445
9446     // Find a legal type for the integer store.
9447     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9448     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9449     if (TLI.isTypeLegal(StoreTy))
9450       LastLegalIntegerType = i + 1;
9451     // Or check whether a truncstore and extload is legal.
9452     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9453              TargetLowering::TypePromoteInteger) {
9454       EVT LegalizedStoredValueTy =
9455         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9456       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9457           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9458           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9459           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9460         LastLegalIntegerType = i+1;
9461     }
9462   }
9463
9464   // Only use vector types if the vector type is larger than the integer type.
9465   // If they are the same, use integers.
9466   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9467   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9468
9469   // We add +1 here because the LastXXX variables refer to location while
9470   // the NumElem refers to array/index size.
9471   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9472   NumElem = std::min(LastLegalType, NumElem);
9473
9474   if (NumElem < 2)
9475     return false;
9476
9477   // The earliest Node in the DAG.
9478   unsigned EarliestNodeUsed = 0;
9479   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9480   for (unsigned i=1; i<NumElem; ++i) {
9481     // Find a chain for the new wide-store operand. Notice that some
9482     // of the store nodes that we found may not be selected for inclusion
9483     // in the wide store. The chain we use needs to be the chain of the
9484     // earliest store node which is *used* and replaced by the wide store.
9485     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9486       EarliestNodeUsed = i;
9487   }
9488
9489   // Find if it is better to use vectors or integers to load and store
9490   // to memory.
9491   EVT JointMemOpVT;
9492   if (UseVectorTy) {
9493     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9494   } else {
9495     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9496     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9497   }
9498
9499   SDLoc LoadDL(LoadNodes[0].MemNode);
9500   SDLoc StoreDL(StoreNodes[0].MemNode);
9501
9502   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9503   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9504                                 FirstLoad->getChain(),
9505                                 FirstLoad->getBasePtr(),
9506                                 FirstLoad->getPointerInfo(),
9507                                 false, false, false,
9508                                 FirstLoad->getAlignment());
9509
9510   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9511                                   FirstInChain->getBasePtr(),
9512                                   FirstInChain->getPointerInfo(), false, false,
9513                                   FirstInChain->getAlignment());
9514
9515   // Replace one of the loads with the new load.
9516   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9517   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9518                                 SDValue(NewLoad.getNode(), 1));
9519
9520   // Remove the rest of the load chains.
9521   for (unsigned i = 1; i < NumElem ; ++i) {
9522     // Replace all chain users of the old load nodes with the chain of the new
9523     // load node.
9524     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9525     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9526   }
9527
9528   // Replace the first store with the new store.
9529   CombineTo(EarliestOp, NewStore);
9530   // Erase all other stores.
9531   for (unsigned i = 0; i < NumElem ; ++i) {
9532     // Remove all Store nodes.
9533     if (StoreNodes[i].MemNode == EarliestOp)
9534       continue;
9535     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9536     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9537     removeFromWorklist(St);
9538     DAG.DeleteNode(St);
9539   }
9540
9541   return true;
9542 }
9543
9544 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9545   StoreSDNode *ST  = cast<StoreSDNode>(N);
9546   SDValue Chain = ST->getChain();
9547   SDValue Value = ST->getValue();
9548   SDValue Ptr   = ST->getBasePtr();
9549
9550   // If this is a store of a bit convert, store the input value if the
9551   // resultant store does not need a higher alignment than the original.
9552   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9553       ST->isUnindexed()) {
9554     unsigned OrigAlign = ST->getAlignment();
9555     EVT SVT = Value.getOperand(0).getValueType();
9556     unsigned Align = TLI.getDataLayout()->
9557       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9558     if (Align <= OrigAlign &&
9559         ((!LegalOperations && !ST->isVolatile()) ||
9560          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9561       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9562                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9563                           ST->isNonTemporal(), OrigAlign,
9564                           ST->getAAInfo());
9565   }
9566
9567   // Turn 'store undef, Ptr' -> nothing.
9568   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9569     return Chain;
9570
9571   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9572   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9573     // NOTE: If the original store is volatile, this transform must not increase
9574     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9575     // processor operation but an i64 (which is not legal) requires two.  So the
9576     // transform should not be done in this case.
9577     if (Value.getOpcode() != ISD::TargetConstantFP) {
9578       SDValue Tmp;
9579       switch (CFP->getSimpleValueType(0).SimpleTy) {
9580       default: llvm_unreachable("Unknown FP type");
9581       case MVT::f16:    // We don't do this for these yet.
9582       case MVT::f80:
9583       case MVT::f128:
9584       case MVT::ppcf128:
9585         break;
9586       case MVT::f32:
9587         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9588             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9589           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9590                               bitcastToAPInt().getZExtValue(), MVT::i32);
9591           return DAG.getStore(Chain, SDLoc(N), Tmp,
9592                               Ptr, ST->getMemOperand());
9593         }
9594         break;
9595       case MVT::f64:
9596         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9597              !ST->isVolatile()) ||
9598             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9599           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9600                                 getZExtValue(), MVT::i64);
9601           return DAG.getStore(Chain, SDLoc(N), Tmp,
9602                               Ptr, ST->getMemOperand());
9603         }
9604
9605         if (!ST->isVolatile() &&
9606             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9607           // Many FP stores are not made apparent until after legalize, e.g. for
9608           // argument passing.  Since this is so common, custom legalize the
9609           // 64-bit integer store into two 32-bit stores.
9610           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9611           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9612           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9613           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9614
9615           unsigned Alignment = ST->getAlignment();
9616           bool isVolatile = ST->isVolatile();
9617           bool isNonTemporal = ST->isNonTemporal();
9618           AAMDNodes AAInfo = ST->getAAInfo();
9619
9620           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9621                                      Ptr, ST->getPointerInfo(),
9622                                      isVolatile, isNonTemporal,
9623                                      ST->getAlignment(), AAInfo);
9624           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9625                             DAG.getConstant(4, Ptr.getValueType()));
9626           Alignment = MinAlign(Alignment, 4U);
9627           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9628                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9629                                      isVolatile, isNonTemporal,
9630                                      Alignment, AAInfo);
9631           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9632                              St0, St1);
9633         }
9634
9635         break;
9636       }
9637     }
9638   }
9639
9640   // Try to infer better alignment information than the store already has.
9641   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9642     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9643       if (Align > ST->getAlignment())
9644         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9645                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9646                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9647                                  ST->getAAInfo());
9648     }
9649   }
9650
9651   // Try transforming a pair floating point load / store ops to integer
9652   // load / store ops.
9653   SDValue NewST = TransformFPLoadStorePair(N);
9654   if (NewST.getNode())
9655     return NewST;
9656
9657   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9658     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9659 #ifndef NDEBUG
9660   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9661       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9662     UseAA = false;
9663 #endif
9664   if (UseAA && ST->isUnindexed()) {
9665     // Walk up chain skipping non-aliasing memory nodes.
9666     SDValue BetterChain = FindBetterChain(N, Chain);
9667
9668     // If there is a better chain.
9669     if (Chain != BetterChain) {
9670       SDValue ReplStore;
9671
9672       // Replace the chain to avoid dependency.
9673       if (ST->isTruncatingStore()) {
9674         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9675                                       ST->getMemoryVT(), ST->getMemOperand());
9676       } else {
9677         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9678                                  ST->getMemOperand());
9679       }
9680
9681       // Create token to keep both nodes around.
9682       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9683                                   MVT::Other, Chain, ReplStore);
9684
9685       // Make sure the new and old chains are cleaned up.
9686       AddToWorklist(Token.getNode());
9687
9688       // Don't add users to work list.
9689       return CombineTo(N, Token, false);
9690     }
9691   }
9692
9693   // Try transforming N to an indexed store.
9694   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9695     return SDValue(N, 0);
9696
9697   // FIXME: is there such a thing as a truncating indexed store?
9698   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9699       Value.getValueType().isInteger()) {
9700     // See if we can simplify the input to this truncstore with knowledge that
9701     // only the low bits are being used.  For example:
9702     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9703     SDValue Shorter =
9704       GetDemandedBits(Value,
9705                       APInt::getLowBitsSet(
9706                         Value.getValueType().getScalarType().getSizeInBits(),
9707                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9708     AddToWorklist(Value.getNode());
9709     if (Shorter.getNode())
9710       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9711                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9712
9713     // Otherwise, see if we can simplify the operation with
9714     // SimplifyDemandedBits, which only works if the value has a single use.
9715     if (SimplifyDemandedBits(Value,
9716                         APInt::getLowBitsSet(
9717                           Value.getValueType().getScalarType().getSizeInBits(),
9718                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9719       return SDValue(N, 0);
9720   }
9721
9722   // If this is a load followed by a store to the same location, then the store
9723   // is dead/noop.
9724   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9725     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9726         ST->isUnindexed() && !ST->isVolatile() &&
9727         // There can't be any side effects between the load and store, such as
9728         // a call or store.
9729         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9730       // The store is dead, remove it.
9731       return Chain;
9732     }
9733   }
9734
9735   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9736   // truncating store.  We can do this even if this is already a truncstore.
9737   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9738       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9739       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9740                             ST->getMemoryVT())) {
9741     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9742                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9743   }
9744
9745   // Only perform this optimization before the types are legal, because we
9746   // don't want to perform this optimization on every DAGCombine invocation.
9747   if (!LegalTypes) {
9748     bool EverChanged = false;
9749
9750     do {
9751       // There can be multiple store sequences on the same chain.
9752       // Keep trying to merge store sequences until we are unable to do so
9753       // or until we merge the last store on the chain.
9754       bool Changed = MergeConsecutiveStores(ST);
9755       EverChanged |= Changed;
9756       if (!Changed) break;
9757     } while (ST->getOpcode() != ISD::DELETED_NODE);
9758
9759     if (EverChanged)
9760       return SDValue(N, 0);
9761   }
9762
9763   return ReduceLoadOpStoreWidth(N);
9764 }
9765
9766 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9767   SDValue InVec = N->getOperand(0);
9768   SDValue InVal = N->getOperand(1);
9769   SDValue EltNo = N->getOperand(2);
9770   SDLoc dl(N);
9771
9772   // If the inserted element is an UNDEF, just use the input vector.
9773   if (InVal.getOpcode() == ISD::UNDEF)
9774     return InVec;
9775
9776   EVT VT = InVec.getValueType();
9777
9778   // If we can't generate a legal BUILD_VECTOR, exit
9779   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9780     return SDValue();
9781
9782   // Check that we know which element is being inserted
9783   if (!isa<ConstantSDNode>(EltNo))
9784     return SDValue();
9785   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9786
9787   // Canonicalize insert_vector_elt dag nodes.
9788   // Example:
9789   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9790   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9791   //
9792   // Do this only if the child insert_vector node has one use; also
9793   // do this only if indices are both constants and Idx1 < Idx0.
9794   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9795       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9796     unsigned OtherElt =
9797       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9798     if (Elt < OtherElt) {
9799       // Swap nodes.
9800       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9801                                   InVec.getOperand(0), InVal, EltNo);
9802       AddToWorklist(NewOp.getNode());
9803       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9804                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9805     }
9806   }
9807
9808   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9809   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9810   // vector elements.
9811   SmallVector<SDValue, 8> Ops;
9812   // Do not combine these two vectors if the output vector will not replace
9813   // the input vector.
9814   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9815     Ops.append(InVec.getNode()->op_begin(),
9816                InVec.getNode()->op_end());
9817   } else if (InVec.getOpcode() == ISD::UNDEF) {
9818     unsigned NElts = VT.getVectorNumElements();
9819     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9820   } else {
9821     return SDValue();
9822   }
9823
9824   // Insert the element
9825   if (Elt < Ops.size()) {
9826     // All the operands of BUILD_VECTOR must have the same type;
9827     // we enforce that here.
9828     EVT OpVT = Ops[0].getValueType();
9829     if (InVal.getValueType() != OpVT)
9830       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9831                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9832                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9833     Ops[Elt] = InVal;
9834   }
9835
9836   // Return the new vector
9837   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9838 }
9839
9840 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9841   // (vextract (scalar_to_vector val, 0) -> val
9842   SDValue InVec = N->getOperand(0);
9843   EVT VT = InVec.getValueType();
9844   EVT NVT = N->getValueType(0);
9845
9846   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9847     // Check if the result type doesn't match the inserted element type. A
9848     // SCALAR_TO_VECTOR may truncate the inserted element and the
9849     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9850     SDValue InOp = InVec.getOperand(0);
9851     if (InOp.getValueType() != NVT) {
9852       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9853       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9854     }
9855     return InOp;
9856   }
9857
9858   SDValue EltNo = N->getOperand(1);
9859   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9860
9861   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9862   // We only perform this optimization before the op legalization phase because
9863   // we may introduce new vector instructions which are not backed by TD
9864   // patterns. For example on AVX, extracting elements from a wide vector
9865   // without using extract_subvector. However, if we can find an underlying
9866   // scalar value, then we can always use that.
9867   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9868       && ConstEltNo) {
9869     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9870     int NumElem = VT.getVectorNumElements();
9871     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9872     // Find the new index to extract from.
9873     int OrigElt = SVOp->getMaskElt(Elt);
9874
9875     // Extracting an undef index is undef.
9876     if (OrigElt == -1)
9877       return DAG.getUNDEF(NVT);
9878
9879     // Select the right vector half to extract from.
9880     SDValue SVInVec;
9881     if (OrigElt < NumElem) {
9882       SVInVec = InVec->getOperand(0);
9883     } else {
9884       SVInVec = InVec->getOperand(1);
9885       OrigElt -= NumElem;
9886     }
9887
9888     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9889       SDValue InOp = SVInVec.getOperand(OrigElt);
9890       if (InOp.getValueType() != NVT) {
9891         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9892         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9893       }
9894
9895       return InOp;
9896     }
9897
9898     // FIXME: We should handle recursing on other vector shuffles and
9899     // scalar_to_vector here as well.
9900
9901     if (!LegalOperations) {
9902       EVT IndexTy = TLI.getVectorIdxTy();
9903       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9904                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9905     }
9906   }
9907
9908   // Perform only after legalization to ensure build_vector / vector_shuffle
9909   // optimizations have already been done.
9910   if (!LegalOperations) return SDValue();
9911
9912   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9913   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9914   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9915
9916   if (ConstEltNo) {
9917     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9918     bool NewLoad = false;
9919     bool BCNumEltsChanged = false;
9920     EVT ExtVT = VT.getVectorElementType();
9921     EVT LVT = ExtVT;
9922
9923     // If the result of load has to be truncated, then it's not necessarily
9924     // profitable.
9925     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9926       return SDValue();
9927
9928     if (InVec.getOpcode() == ISD::BITCAST) {
9929       // Don't duplicate a load with other uses.
9930       if (!InVec.hasOneUse())
9931         return SDValue();
9932
9933       EVT BCVT = InVec.getOperand(0).getValueType();
9934       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9935         return SDValue();
9936       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9937         BCNumEltsChanged = true;
9938       InVec = InVec.getOperand(0);
9939       ExtVT = BCVT.getVectorElementType();
9940       NewLoad = true;
9941     }
9942
9943     LoadSDNode *LN0 = nullptr;
9944     const ShuffleVectorSDNode *SVN = nullptr;
9945     if (ISD::isNormalLoad(InVec.getNode())) {
9946       LN0 = cast<LoadSDNode>(InVec);
9947     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9948                InVec.getOperand(0).getValueType() == ExtVT &&
9949                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9950       // Don't duplicate a load with other uses.
9951       if (!InVec.hasOneUse())
9952         return SDValue();
9953
9954       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9955     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9956       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9957       // =>
9958       // (load $addr+1*size)
9959
9960       // Don't duplicate a load with other uses.
9961       if (!InVec.hasOneUse())
9962         return SDValue();
9963
9964       // If the bit convert changed the number of elements, it is unsafe
9965       // to examine the mask.
9966       if (BCNumEltsChanged)
9967         return SDValue();
9968
9969       // Select the input vector, guarding against out of range extract vector.
9970       unsigned NumElems = VT.getVectorNumElements();
9971       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9972       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9973
9974       if (InVec.getOpcode() == ISD::BITCAST) {
9975         // Don't duplicate a load with other uses.
9976         if (!InVec.hasOneUse())
9977           return SDValue();
9978
9979         InVec = InVec.getOperand(0);
9980       }
9981       if (ISD::isNormalLoad(InVec.getNode())) {
9982         LN0 = cast<LoadSDNode>(InVec);
9983         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9984       }
9985     }
9986
9987     // Make sure we found a non-volatile load and the extractelement is
9988     // the only use.
9989     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9990       return SDValue();
9991
9992     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9993     if (Elt == -1)
9994       return DAG.getUNDEF(LVT);
9995
9996     unsigned Align = LN0->getAlignment();
9997     if (NewLoad) {
9998       // Check the resultant load doesn't need a higher alignment than the
9999       // original load.
10000       unsigned NewAlign =
10001         TLI.getDataLayout()
10002             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
10003
10004       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10005         return SDValue();
10006
10007       Align = NewAlign;
10008     }
10009
10010     SDValue NewPtr = LN0->getBasePtr();
10011     unsigned PtrOff = 0;
10012
10013     if (Elt) {
10014       PtrOff = LVT.getSizeInBits() * Elt / 8;
10015       EVT PtrType = NewPtr.getValueType();
10016       if (TLI.isBigEndian())
10017         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10018       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10019                            DAG.getConstant(PtrOff, PtrType));
10020     }
10021
10022     // The replacement we need to do here is a little tricky: we need to
10023     // replace an extractelement of a load with a load.
10024     // Use ReplaceAllUsesOfValuesWith to do the replacement.
10025     // Note that this replacement assumes that the extractvalue is the only
10026     // use of the load; that's okay because we don't want to perform this
10027     // transformation in other cases anyway.
10028     SDValue Load;
10029     SDValue Chain;
10030     if (NVT.bitsGT(LVT)) {
10031       // If the result type of vextract is wider than the load, then issue an
10032       // extending load instead.
10033       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10034         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10035       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10036                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10037                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10038                             LN0->isInvariant(), Align, LN0->getAAInfo());
10039       Chain = Load.getValue(1);
10040     } else {
10041       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10042                          LN0->getPointerInfo().getWithOffset(PtrOff),
10043                          LN0->isVolatile(), LN0->isNonTemporal(),
10044                          LN0->isInvariant(), Align, LN0->getAAInfo());
10045       Chain = Load.getValue(1);
10046       if (NVT.bitsLT(LVT))
10047         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10048       else
10049         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10050     }
10051     WorklistRemover DeadNodes(*this);
10052     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10053     SDValue To[] = { Load, Chain };
10054     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10055     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10056     // worklist explicitly as well.
10057     AddToWorklist(Load.getNode());
10058     AddUsersToWorklist(Load.getNode()); // Add users too
10059     // Make sure to revisit this node to clean it up; it will usually be dead.
10060     AddToWorklist(N);
10061     return SDValue(N, 0);
10062   }
10063
10064   return SDValue();
10065 }
10066
10067 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10068 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10069   // We perform this optimization post type-legalization because
10070   // the type-legalizer often scalarizes integer-promoted vectors.
10071   // Performing this optimization before may create bit-casts which
10072   // will be type-legalized to complex code sequences.
10073   // We perform this optimization only before the operation legalizer because we
10074   // may introduce illegal operations.
10075   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10076     return SDValue();
10077
10078   unsigned NumInScalars = N->getNumOperands();
10079   SDLoc dl(N);
10080   EVT VT = N->getValueType(0);
10081
10082   // Check to see if this is a BUILD_VECTOR of a bunch of values
10083   // which come from any_extend or zero_extend nodes. If so, we can create
10084   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10085   // optimizations. We do not handle sign-extend because we can't fill the sign
10086   // using shuffles.
10087   EVT SourceType = MVT::Other;
10088   bool AllAnyExt = true;
10089
10090   for (unsigned i = 0; i != NumInScalars; ++i) {
10091     SDValue In = N->getOperand(i);
10092     // Ignore undef inputs.
10093     if (In.getOpcode() == ISD::UNDEF) continue;
10094
10095     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10096     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10097
10098     // Abort if the element is not an extension.
10099     if (!ZeroExt && !AnyExt) {
10100       SourceType = MVT::Other;
10101       break;
10102     }
10103
10104     // The input is a ZeroExt or AnyExt. Check the original type.
10105     EVT InTy = In.getOperand(0).getValueType();
10106
10107     // Check that all of the widened source types are the same.
10108     if (SourceType == MVT::Other)
10109       // First time.
10110       SourceType = InTy;
10111     else if (InTy != SourceType) {
10112       // Multiple income types. Abort.
10113       SourceType = MVT::Other;
10114       break;
10115     }
10116
10117     // Check if all of the extends are ANY_EXTENDs.
10118     AllAnyExt &= AnyExt;
10119   }
10120
10121   // In order to have valid types, all of the inputs must be extended from the
10122   // same source type and all of the inputs must be any or zero extend.
10123   // Scalar sizes must be a power of two.
10124   EVT OutScalarTy = VT.getScalarType();
10125   bool ValidTypes = SourceType != MVT::Other &&
10126                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10127                  isPowerOf2_32(SourceType.getSizeInBits());
10128
10129   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10130   // turn into a single shuffle instruction.
10131   if (!ValidTypes)
10132     return SDValue();
10133
10134   bool isLE = TLI.isLittleEndian();
10135   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10136   assert(ElemRatio > 1 && "Invalid element size ratio");
10137   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10138                                DAG.getConstant(0, SourceType);
10139
10140   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10141   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10142
10143   // Populate the new build_vector
10144   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10145     SDValue Cast = N->getOperand(i);
10146     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10147             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10148             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10149     SDValue In;
10150     if (Cast.getOpcode() == ISD::UNDEF)
10151       In = DAG.getUNDEF(SourceType);
10152     else
10153       In = Cast->getOperand(0);
10154     unsigned Index = isLE ? (i * ElemRatio) :
10155                             (i * ElemRatio + (ElemRatio - 1));
10156
10157     assert(Index < Ops.size() && "Invalid index");
10158     Ops[Index] = In;
10159   }
10160
10161   // The type of the new BUILD_VECTOR node.
10162   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10163   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10164          "Invalid vector size");
10165   // Check if the new vector type is legal.
10166   if (!isTypeLegal(VecVT)) return SDValue();
10167
10168   // Make the new BUILD_VECTOR.
10169   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10170
10171   // The new BUILD_VECTOR node has the potential to be further optimized.
10172   AddToWorklist(BV.getNode());
10173   // Bitcast to the desired type.
10174   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10175 }
10176
10177 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10178   EVT VT = N->getValueType(0);
10179
10180   unsigned NumInScalars = N->getNumOperands();
10181   SDLoc dl(N);
10182
10183   EVT SrcVT = MVT::Other;
10184   unsigned Opcode = ISD::DELETED_NODE;
10185   unsigned NumDefs = 0;
10186
10187   for (unsigned i = 0; i != NumInScalars; ++i) {
10188     SDValue In = N->getOperand(i);
10189     unsigned Opc = In.getOpcode();
10190
10191     if (Opc == ISD::UNDEF)
10192       continue;
10193
10194     // If all scalar values are floats and converted from integers.
10195     if (Opcode == ISD::DELETED_NODE &&
10196         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10197       Opcode = Opc;
10198     }
10199
10200     if (Opc != Opcode)
10201       return SDValue();
10202
10203     EVT InVT = In.getOperand(0).getValueType();
10204
10205     // If all scalar values are typed differently, bail out. It's chosen to
10206     // simplify BUILD_VECTOR of integer types.
10207     if (SrcVT == MVT::Other)
10208       SrcVT = InVT;
10209     if (SrcVT != InVT)
10210       return SDValue();
10211     NumDefs++;
10212   }
10213
10214   // If the vector has just one element defined, it's not worth to fold it into
10215   // a vectorized one.
10216   if (NumDefs < 2)
10217     return SDValue();
10218
10219   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10220          && "Should only handle conversion from integer to float.");
10221   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10222
10223   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10224
10225   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10226     return SDValue();
10227
10228   SmallVector<SDValue, 8> Opnds;
10229   for (unsigned i = 0; i != NumInScalars; ++i) {
10230     SDValue In = N->getOperand(i);
10231
10232     if (In.getOpcode() == ISD::UNDEF)
10233       Opnds.push_back(DAG.getUNDEF(SrcVT));
10234     else
10235       Opnds.push_back(In.getOperand(0));
10236   }
10237   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10238   AddToWorklist(BV.getNode());
10239
10240   return DAG.getNode(Opcode, dl, VT, BV);
10241 }
10242
10243 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10244   unsigned NumInScalars = N->getNumOperands();
10245   SDLoc dl(N);
10246   EVT VT = N->getValueType(0);
10247
10248   // A vector built entirely of undefs is undef.
10249   if (ISD::allOperandsUndef(N))
10250     return DAG.getUNDEF(VT);
10251
10252   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10253   if (V.getNode())
10254     return V;
10255
10256   V = reduceBuildVecConvertToConvertBuildVec(N);
10257   if (V.getNode())
10258     return V;
10259
10260   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10261   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10262   // at most two distinct vectors, turn this into a shuffle node.
10263
10264   // May only combine to shuffle after legalize if shuffle is legal.
10265   if (LegalOperations &&
10266       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10267     return SDValue();
10268
10269   SDValue VecIn1, VecIn2;
10270   for (unsigned i = 0; i != NumInScalars; ++i) {
10271     // Ignore undef inputs.
10272     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10273
10274     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10275     // constant index, bail out.
10276     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10277         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10278       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10279       break;
10280     }
10281
10282     // We allow up to two distinct input vectors.
10283     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10284     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10285       continue;
10286
10287     if (!VecIn1.getNode()) {
10288       VecIn1 = ExtractedFromVec;
10289     } else if (!VecIn2.getNode()) {
10290       VecIn2 = ExtractedFromVec;
10291     } else {
10292       // Too many inputs.
10293       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10294       break;
10295     }
10296   }
10297
10298   // If everything is good, we can make a shuffle operation.
10299   if (VecIn1.getNode()) {
10300     SmallVector<int, 8> Mask;
10301     for (unsigned i = 0; i != NumInScalars; ++i) {
10302       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10303         Mask.push_back(-1);
10304         continue;
10305       }
10306
10307       // If extracting from the first vector, just use the index directly.
10308       SDValue Extract = N->getOperand(i);
10309       SDValue ExtVal = Extract.getOperand(1);
10310       if (Extract.getOperand(0) == VecIn1) {
10311         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10312         if (ExtIndex > VT.getVectorNumElements())
10313           return SDValue();
10314
10315         Mask.push_back(ExtIndex);
10316         continue;
10317       }
10318
10319       // Otherwise, use InIdx + VecSize
10320       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10321       Mask.push_back(Idx+NumInScalars);
10322     }
10323
10324     // We can't generate a shuffle node with mismatched input and output types.
10325     // Attempt to transform a single input vector to the correct type.
10326     if ((VT != VecIn1.getValueType())) {
10327       // We don't support shuffeling between TWO values of different types.
10328       if (VecIn2.getNode())
10329         return SDValue();
10330
10331       // We only support widening of vectors which are half the size of the
10332       // output registers. For example XMM->YMM widening on X86 with AVX.
10333       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10334         return SDValue();
10335
10336       // If the input vector type has a different base type to the output
10337       // vector type, bail out.
10338       if (VecIn1.getValueType().getVectorElementType() !=
10339           VT.getVectorElementType())
10340         return SDValue();
10341
10342       // Widen the input vector by adding undef values.
10343       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10344                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10345     }
10346
10347     // If VecIn2 is unused then change it to undef.
10348     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10349
10350     // Check that we were able to transform all incoming values to the same
10351     // type.
10352     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10353         VecIn1.getValueType() != VT)
10354           return SDValue();
10355
10356     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10357     if (!isTypeLegal(VT))
10358       return SDValue();
10359
10360     // Return the new VECTOR_SHUFFLE node.
10361     SDValue Ops[2];
10362     Ops[0] = VecIn1;
10363     Ops[1] = VecIn2;
10364     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10365   }
10366
10367   return SDValue();
10368 }
10369
10370 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10371   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10372   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10373   // inputs come from at most two distinct vectors, turn this into a shuffle
10374   // node.
10375
10376   // If we only have one input vector, we don't need to do any concatenation.
10377   if (N->getNumOperands() == 1)
10378     return N->getOperand(0);
10379
10380   // Check if all of the operands are undefs.
10381   EVT VT = N->getValueType(0);
10382   if (ISD::allOperandsUndef(N))
10383     return DAG.getUNDEF(VT);
10384
10385   // Optimize concat_vectors where one of the vectors is undef.
10386   if (N->getNumOperands() == 2 &&
10387       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10388     SDValue In = N->getOperand(0);
10389     assert(In.getValueType().isVector() && "Must concat vectors");
10390
10391     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10392     if (In->getOpcode() == ISD::BITCAST &&
10393         !In->getOperand(0)->getValueType(0).isVector()) {
10394       SDValue Scalar = In->getOperand(0);
10395       EVT SclTy = Scalar->getValueType(0);
10396
10397       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10398         return SDValue();
10399
10400       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10401                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10402       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10403         return SDValue();
10404
10405       SDLoc dl = SDLoc(N);
10406       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10407       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10408     }
10409   }
10410
10411   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10412   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10413   if (N->getNumOperands() == 2 &&
10414       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10415       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10416     EVT VT = N->getValueType(0);
10417     SDValue N0 = N->getOperand(0);
10418     SDValue N1 = N->getOperand(1);
10419     SmallVector<SDValue, 8> Opnds;
10420     unsigned BuildVecNumElts =  N0.getNumOperands();
10421
10422     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10423     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10424     if (SclTy0.isFloatingPoint()) {
10425       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10426         Opnds.push_back(N0.getOperand(i));
10427       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10428         Opnds.push_back(N1.getOperand(i));
10429     } else {
10430       // If BUILD_VECTOR are from built from integer, they may have different
10431       // operand types. Get the smaller type and truncate all operands to it.
10432       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10433       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10434         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10435                         N0.getOperand(i)));
10436       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10437         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10438                         N1.getOperand(i)));
10439     }
10440
10441     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10442   }
10443
10444   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10445   // nodes often generate nop CONCAT_VECTOR nodes.
10446   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10447   // place the incoming vectors at the exact same location.
10448   SDValue SingleSource = SDValue();
10449   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10450
10451   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10452     SDValue Op = N->getOperand(i);
10453
10454     if (Op.getOpcode() == ISD::UNDEF)
10455       continue;
10456
10457     // Check if this is the identity extract:
10458     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10459       return SDValue();
10460
10461     // Find the single incoming vector for the extract_subvector.
10462     if (SingleSource.getNode()) {
10463       if (Op.getOperand(0) != SingleSource)
10464         return SDValue();
10465     } else {
10466       SingleSource = Op.getOperand(0);
10467
10468       // Check the source type is the same as the type of the result.
10469       // If not, this concat may extend the vector, so we can not
10470       // optimize it away.
10471       if (SingleSource.getValueType() != N->getValueType(0))
10472         return SDValue();
10473     }
10474
10475     unsigned IdentityIndex = i * PartNumElem;
10476     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10477     // The extract index must be constant.
10478     if (!CS)
10479       return SDValue();
10480
10481     // Check that we are reading from the identity index.
10482     if (CS->getZExtValue() != IdentityIndex)
10483       return SDValue();
10484   }
10485
10486   if (SingleSource.getNode())
10487     return SingleSource;
10488
10489   return SDValue();
10490 }
10491
10492 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10493   EVT NVT = N->getValueType(0);
10494   SDValue V = N->getOperand(0);
10495
10496   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10497     // Combine:
10498     //    (extract_subvec (concat V1, V2, ...), i)
10499     // Into:
10500     //    Vi if possible
10501     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10502     // type.
10503     if (V->getOperand(0).getValueType() != NVT)
10504       return SDValue();
10505     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10506     unsigned NumElems = NVT.getVectorNumElements();
10507     assert((Idx % NumElems) == 0 &&
10508            "IDX in concat is not a multiple of the result vector length.");
10509     return V->getOperand(Idx / NumElems);
10510   }
10511
10512   // Skip bitcasting
10513   if (V->getOpcode() == ISD::BITCAST)
10514     V = V.getOperand(0);
10515
10516   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10517     SDLoc dl(N);
10518     // Handle only simple case where vector being inserted and vector
10519     // being extracted are of same type, and are half size of larger vectors.
10520     EVT BigVT = V->getOperand(0).getValueType();
10521     EVT SmallVT = V->getOperand(1).getValueType();
10522     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10523       return SDValue();
10524
10525     // Only handle cases where both indexes are constants with the same type.
10526     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10527     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10528
10529     if (InsIdx && ExtIdx &&
10530         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10531         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10532       // Combine:
10533       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10534       // Into:
10535       //    indices are equal or bit offsets are equal => V1
10536       //    otherwise => (extract_subvec V1, ExtIdx)
10537       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10538           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10539         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10540       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10541                          DAG.getNode(ISD::BITCAST, dl,
10542                                      N->getOperand(0).getValueType(),
10543                                      V->getOperand(0)), N->getOperand(1));
10544     }
10545   }
10546
10547   return SDValue();
10548 }
10549
10550 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10551 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10552   EVT VT = N->getValueType(0);
10553   unsigned NumElts = VT.getVectorNumElements();
10554
10555   SDValue N0 = N->getOperand(0);
10556   SDValue N1 = N->getOperand(1);
10557   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10558
10559   SmallVector<SDValue, 4> Ops;
10560   EVT ConcatVT = N0.getOperand(0).getValueType();
10561   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10562   unsigned NumConcats = NumElts / NumElemsPerConcat;
10563
10564   // Look at every vector that's inserted. We're looking for exact
10565   // subvector-sized copies from a concatenated vector
10566   for (unsigned I = 0; I != NumConcats; ++I) {
10567     // Make sure we're dealing with a copy.
10568     unsigned Begin = I * NumElemsPerConcat;
10569     bool AllUndef = true, NoUndef = true;
10570     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10571       if (SVN->getMaskElt(J) >= 0)
10572         AllUndef = false;
10573       else
10574         NoUndef = false;
10575     }
10576
10577     if (NoUndef) {
10578       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10579         return SDValue();
10580
10581       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10582         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10583           return SDValue();
10584
10585       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10586       if (FirstElt < N0.getNumOperands())
10587         Ops.push_back(N0.getOperand(FirstElt));
10588       else
10589         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10590
10591     } else if (AllUndef) {
10592       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10593     } else { // Mixed with general masks and undefs, can't do optimization.
10594       return SDValue();
10595     }
10596   }
10597
10598   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10599 }
10600
10601 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10602   EVT VT = N->getValueType(0);
10603   unsigned NumElts = VT.getVectorNumElements();
10604
10605   SDValue N0 = N->getOperand(0);
10606   SDValue N1 = N->getOperand(1);
10607
10608   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10609
10610   // Canonicalize shuffle undef, undef -> undef
10611   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10612     return DAG.getUNDEF(VT);
10613
10614   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10615
10616   // Canonicalize shuffle v, v -> v, undef
10617   if (N0 == N1) {
10618     SmallVector<int, 8> NewMask;
10619     for (unsigned i = 0; i != NumElts; ++i) {
10620       int Idx = SVN->getMaskElt(i);
10621       if (Idx >= (int)NumElts) Idx -= NumElts;
10622       NewMask.push_back(Idx);
10623     }
10624     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10625                                 &NewMask[0]);
10626   }
10627
10628   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10629   if (N0.getOpcode() == ISD::UNDEF) {
10630     SmallVector<int, 8> NewMask;
10631     for (unsigned i = 0; i != NumElts; ++i) {
10632       int Idx = SVN->getMaskElt(i);
10633       if (Idx >= 0) {
10634         if (Idx >= (int)NumElts)
10635           Idx -= NumElts;
10636         else
10637           Idx = -1; // remove reference to lhs
10638       }
10639       NewMask.push_back(Idx);
10640     }
10641     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10642                                 &NewMask[0]);
10643   }
10644
10645   // Remove references to rhs if it is undef
10646   if (N1.getOpcode() == ISD::UNDEF) {
10647     bool Changed = false;
10648     SmallVector<int, 8> NewMask;
10649     for (unsigned i = 0; i != NumElts; ++i) {
10650       int Idx = SVN->getMaskElt(i);
10651       if (Idx >= (int)NumElts) {
10652         Idx = -1;
10653         Changed = true;
10654       }
10655       NewMask.push_back(Idx);
10656     }
10657     if (Changed)
10658       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10659   }
10660
10661   // If it is a splat, check if the argument vector is another splat or a
10662   // build_vector with all scalar elements the same.
10663   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10664     SDNode *V = N0.getNode();
10665
10666     // If this is a bit convert that changes the element type of the vector but
10667     // not the number of vector elements, look through it.  Be careful not to
10668     // look though conversions that change things like v4f32 to v2f64.
10669     if (V->getOpcode() == ISD::BITCAST) {
10670       SDValue ConvInput = V->getOperand(0);
10671       if (ConvInput.getValueType().isVector() &&
10672           ConvInput.getValueType().getVectorNumElements() == NumElts)
10673         V = ConvInput.getNode();
10674     }
10675
10676     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10677       assert(V->getNumOperands() == NumElts &&
10678              "BUILD_VECTOR has wrong number of operands");
10679       SDValue Base;
10680       bool AllSame = true;
10681       for (unsigned i = 0; i != NumElts; ++i) {
10682         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10683           Base = V->getOperand(i);
10684           break;
10685         }
10686       }
10687       // Splat of <u, u, u, u>, return <u, u, u, u>
10688       if (!Base.getNode())
10689         return N0;
10690       for (unsigned i = 0; i != NumElts; ++i) {
10691         if (V->getOperand(i) != Base) {
10692           AllSame = false;
10693           break;
10694         }
10695       }
10696       // Splat of <x, x, x, x>, return <x, x, x, x>
10697       if (AllSame)
10698         return N0;
10699     }
10700   }
10701
10702   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10703       Level < AfterLegalizeVectorOps &&
10704       (N1.getOpcode() == ISD::UNDEF ||
10705       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10706        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10707     SDValue V = partitionShuffleOfConcats(N, DAG);
10708
10709     if (V.getNode())
10710       return V;
10711   }
10712
10713   // If this shuffle node is simply a swizzle of another shuffle node,
10714   // then try to simplify it.
10715   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10716       N1.getOpcode() == ISD::UNDEF) {
10717
10718     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10719
10720     // The incoming shuffle must be of the same type as the result of the
10721     // current shuffle.
10722     assert(OtherSV->getOperand(0).getValueType() == VT &&
10723            "Shuffle types don't match");
10724
10725     SmallVector<int, 4> Mask;
10726     // Compute the combined shuffle mask.
10727     for (unsigned i = 0; i != NumElts; ++i) {
10728       int Idx = SVN->getMaskElt(i);
10729       assert(Idx < (int)NumElts && "Index references undef operand");
10730       // Next, this index comes from the first value, which is the incoming
10731       // shuffle. Adopt the incoming index.
10732       if (Idx >= 0)
10733         Idx = OtherSV->getMaskElt(Idx);
10734       Mask.push_back(Idx);
10735     }
10736     
10737     bool CommuteOperands = false;
10738     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10739       // To be valid, the combine shuffle mask should only reference elements
10740       // from one of the two vectors in input to the inner shufflevector.
10741       bool IsValidMask = true;
10742       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10743         // See if the combined mask only reference undefs or elements coming
10744         // from the first shufflevector operand.
10745         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10746
10747       if (!IsValidMask) {
10748         IsValidMask = true;
10749         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10750           // Check that all the elements come from the second shuffle operand.
10751           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10752         CommuteOperands = IsValidMask;
10753       }
10754
10755       // Early exit if the combined shuffle mask is not valid.
10756       if (!IsValidMask)
10757         return SDValue();
10758     }
10759
10760     // See if this pair of shuffles can be safely folded according to either
10761     // of the following rules:
10762     //   shuffle(shuffle(x, y), undef) -> x
10763     //   shuffle(shuffle(x, undef), undef) -> x
10764     //   shuffle(shuffle(x, y), undef) -> y
10765     bool IsIdentityMask = true;
10766     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10767     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10768       // Skip Undefs.
10769       if (Mask[i] < 0)
10770         continue;
10771
10772       // The combined shuffle must map each index to itself.
10773       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10774     }
10775     
10776     if (IsIdentityMask) {
10777       if (CommuteOperands)
10778         // optimize shuffle(shuffle(x, y), undef) -> y.
10779         return OtherSV->getOperand(1);
10780       
10781       // optimize shuffle(shuffle(x, undef), undef) -> x
10782       // optimize shuffle(shuffle(x, y), undef) -> x
10783       return OtherSV->getOperand(0);
10784     }
10785
10786     // It may still be beneficial to combine the two shuffles if the
10787     // resulting shuffle is legal.
10788     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10789       if (!CommuteOperands)
10790         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10791         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10792         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10793                                     &Mask[0]);
10794       
10795       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10796       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10797                                   &Mask[0]);
10798     }
10799   }
10800
10801   // Canonicalize shuffles according to rules:
10802   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10803   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10804   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10805   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10806       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10807       TLI.isTypeLegal(VT)) {
10808     // The incoming shuffle must be of the same type as the result of the
10809     // current shuffle.
10810     assert(N1->getOperand(0).getValueType() == VT &&
10811            "Shuffle types don't match");
10812
10813     SDValue SV0 = N1->getOperand(0);
10814     SDValue SV1 = N1->getOperand(1);
10815     bool HasSameOp0 = N0 == SV0;
10816     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10817     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10818       // Commute the operands of this shuffle so that next rule
10819       // will trigger.
10820       return DAG.getCommutedVectorShuffle(*SVN);
10821   }
10822
10823   // Try to fold according to rules:
10824   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10825   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10826   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10827   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10828   // Don't try to fold shuffles with illegal type.
10829   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10830       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10831     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10832
10833     // The incoming shuffle must be of the same type as the result of the
10834     // current shuffle.
10835     assert(OtherSV->getOperand(0).getValueType() == VT &&
10836            "Shuffle types don't match");
10837
10838     SDValue SV0 = OtherSV->getOperand(0);
10839     SDValue SV1 = OtherSV->getOperand(1);
10840     bool HasSameOp0 = N1 == SV0;
10841     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10842     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10843       // Early exit.
10844       return SDValue();
10845
10846     SmallVector<int, 4> Mask;
10847     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10848     // operand, and SV1 as the second operand.
10849     for (unsigned i = 0; i != NumElts; ++i) {
10850       int Idx = SVN->getMaskElt(i);
10851       if (Idx < 0) {
10852         // Propagate Undef.
10853         Mask.push_back(Idx);
10854         continue;
10855       }
10856
10857       if (Idx < (int)NumElts) {
10858         Idx = OtherSV->getMaskElt(Idx);
10859         if (IsSV1Undef && Idx >= (int) NumElts)
10860           Idx = -1;  // Propagate Undef.
10861       } else
10862         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10863
10864       Mask.push_back(Idx);
10865     }
10866
10867     // Avoid introducing shuffles with illegal mask.
10868     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10869       if (IsSV1Undef)
10870         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10871         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10872         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10873       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10874     }
10875   }
10876
10877   return SDValue();
10878 }
10879
10880 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10881   SDValue N0 = N->getOperand(0);
10882   SDValue N2 = N->getOperand(2);
10883
10884   // If the input vector is a concatenation, and the insert replaces
10885   // one of the halves, we can optimize into a single concat_vectors.
10886   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10887       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10888     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10889     EVT VT = N->getValueType(0);
10890
10891     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10892     // (concat_vectors Z, Y)
10893     if (InsIdx == 0)
10894       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10895                          N->getOperand(1), N0.getOperand(1));
10896
10897     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10898     // (concat_vectors X, Z)
10899     if (InsIdx == VT.getVectorNumElements()/2)
10900       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10901                          N0.getOperand(0), N->getOperand(1));
10902   }
10903
10904   return SDValue();
10905 }
10906
10907 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10908 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10909 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10910 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10911 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10912   EVT VT = N->getValueType(0);
10913   SDLoc dl(N);
10914   SDValue LHS = N->getOperand(0);
10915   SDValue RHS = N->getOperand(1);
10916   if (N->getOpcode() == ISD::AND) {
10917     if (RHS.getOpcode() == ISD::BITCAST)
10918       RHS = RHS.getOperand(0);
10919     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10920       SmallVector<int, 8> Indices;
10921       unsigned NumElts = RHS.getNumOperands();
10922       for (unsigned i = 0; i != NumElts; ++i) {
10923         SDValue Elt = RHS.getOperand(i);
10924         if (!isa<ConstantSDNode>(Elt))
10925           return SDValue();
10926
10927         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10928           Indices.push_back(i);
10929         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10930           Indices.push_back(NumElts);
10931         else
10932           return SDValue();
10933       }
10934
10935       // Let's see if the target supports this vector_shuffle.
10936       EVT RVT = RHS.getValueType();
10937       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10938         return SDValue();
10939
10940       // Return the new VECTOR_SHUFFLE node.
10941       EVT EltVT = RVT.getVectorElementType();
10942       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10943                                      DAG.getConstant(0, EltVT));
10944       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10945       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10946       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10947       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10948     }
10949   }
10950
10951   return SDValue();
10952 }
10953
10954 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10955 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10956   assert(N->getValueType(0).isVector() &&
10957          "SimplifyVBinOp only works on vectors!");
10958
10959   SDValue LHS = N->getOperand(0);
10960   SDValue RHS = N->getOperand(1);
10961   SDValue Shuffle = XformToShuffleWithZero(N);
10962   if (Shuffle.getNode()) return Shuffle;
10963
10964   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10965   // this operation.
10966   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10967       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10968     // Check if both vectors are constants. If not bail out.
10969     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10970           cast<BuildVectorSDNode>(RHS)->isConstant()))
10971       return SDValue();
10972
10973     SmallVector<SDValue, 8> Ops;
10974     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10975       SDValue LHSOp = LHS.getOperand(i);
10976       SDValue RHSOp = RHS.getOperand(i);
10977
10978       // Can't fold divide by zero.
10979       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10980           N->getOpcode() == ISD::FDIV) {
10981         if ((RHSOp.getOpcode() == ISD::Constant &&
10982              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10983             (RHSOp.getOpcode() == ISD::ConstantFP &&
10984              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10985           break;
10986       }
10987
10988       EVT VT = LHSOp.getValueType();
10989       EVT RVT = RHSOp.getValueType();
10990       if (RVT != VT) {
10991         // Integer BUILD_VECTOR operands may have types larger than the element
10992         // size (e.g., when the element type is not legal).  Prior to type
10993         // legalization, the types may not match between the two BUILD_VECTORS.
10994         // Truncate one of the operands to make them match.
10995         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10996           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10997         } else {
10998           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10999           VT = RVT;
11000         }
11001       }
11002       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11003                                    LHSOp, RHSOp);
11004       if (FoldOp.getOpcode() != ISD::UNDEF &&
11005           FoldOp.getOpcode() != ISD::Constant &&
11006           FoldOp.getOpcode() != ISD::ConstantFP)
11007         break;
11008       Ops.push_back(FoldOp);
11009       AddToWorklist(FoldOp.getNode());
11010     }
11011
11012     if (Ops.size() == LHS.getNumOperands())
11013       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11014   }
11015
11016   // Type legalization might introduce new shuffles in the DAG.
11017   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11018   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11019   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11020       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11021       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11022       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11023     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11024     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11025
11026     if (SVN0->getMask().equals(SVN1->getMask())) {
11027       EVT VT = N->getValueType(0);
11028       SDValue UndefVector = LHS.getOperand(1);
11029       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11030                                      LHS.getOperand(0), RHS.getOperand(0));
11031       AddUsersToWorklist(N);
11032       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11033                                   &SVN0->getMask()[0]);
11034     }
11035   }
11036
11037   return SDValue();
11038 }
11039
11040 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11041 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11042   assert(N->getValueType(0).isVector() &&
11043          "SimplifyVUnaryOp only works on vectors!");
11044
11045   SDValue N0 = N->getOperand(0);
11046
11047   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11048     return SDValue();
11049
11050   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11051   SmallVector<SDValue, 8> Ops;
11052   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11053     SDValue Op = N0.getOperand(i);
11054     if (Op.getOpcode() != ISD::UNDEF &&
11055         Op.getOpcode() != ISD::ConstantFP)
11056       break;
11057     EVT EltVT = Op.getValueType();
11058     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11059     if (FoldOp.getOpcode() != ISD::UNDEF &&
11060         FoldOp.getOpcode() != ISD::ConstantFP)
11061       break;
11062     Ops.push_back(FoldOp);
11063     AddToWorklist(FoldOp.getNode());
11064   }
11065
11066   if (Ops.size() != N0.getNumOperands())
11067     return SDValue();
11068
11069   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11070 }
11071
11072 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11073                                     SDValue N1, SDValue N2){
11074   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11075
11076   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11077                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11078
11079   // If we got a simplified select_cc node back from SimplifySelectCC, then
11080   // break it down into a new SETCC node, and a new SELECT node, and then return
11081   // the SELECT node, since we were called with a SELECT node.
11082   if (SCC.getNode()) {
11083     // Check to see if we got a select_cc back (to turn into setcc/select).
11084     // Otherwise, just return whatever node we got back, like fabs.
11085     if (SCC.getOpcode() == ISD::SELECT_CC) {
11086       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11087                                   N0.getValueType(),
11088                                   SCC.getOperand(0), SCC.getOperand(1),
11089                                   SCC.getOperand(4));
11090       AddToWorklist(SETCC.getNode());
11091       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11092                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11093     }
11094
11095     return SCC;
11096   }
11097   return SDValue();
11098 }
11099
11100 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11101 /// are the two values being selected between, see if we can simplify the
11102 /// select.  Callers of this should assume that TheSelect is deleted if this
11103 /// returns true.  As such, they should return the appropriate thing (e.g. the
11104 /// node) back to the top-level of the DAG combiner loop to avoid it being
11105 /// looked at.
11106 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11107                                     SDValue RHS) {
11108
11109   // Cannot simplify select with vector condition
11110   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11111
11112   // If this is a select from two identical things, try to pull the operation
11113   // through the select.
11114   if (LHS.getOpcode() != RHS.getOpcode() ||
11115       !LHS.hasOneUse() || !RHS.hasOneUse())
11116     return false;
11117
11118   // If this is a load and the token chain is identical, replace the select
11119   // of two loads with a load through a select of the address to load from.
11120   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11121   // constants have been dropped into the constant pool.
11122   if (LHS.getOpcode() == ISD::LOAD) {
11123     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11124     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11125
11126     // Token chains must be identical.
11127     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11128         // Do not let this transformation reduce the number of volatile loads.
11129         LLD->isVolatile() || RLD->isVolatile() ||
11130         // If this is an EXTLOAD, the VT's must match.
11131         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11132         // If this is an EXTLOAD, the kind of extension must match.
11133         (LLD->getExtensionType() != RLD->getExtensionType() &&
11134          // The only exception is if one of the extensions is anyext.
11135          LLD->getExtensionType() != ISD::EXTLOAD &&
11136          RLD->getExtensionType() != ISD::EXTLOAD) ||
11137         // FIXME: this discards src value information.  This is
11138         // over-conservative. It would be beneficial to be able to remember
11139         // both potential memory locations.  Since we are discarding
11140         // src value info, don't do the transformation if the memory
11141         // locations are not in the default address space.
11142         LLD->getPointerInfo().getAddrSpace() != 0 ||
11143         RLD->getPointerInfo().getAddrSpace() != 0 ||
11144         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11145                                       LLD->getBasePtr().getValueType()))
11146       return false;
11147
11148     // Check that the select condition doesn't reach either load.  If so,
11149     // folding this will induce a cycle into the DAG.  If not, this is safe to
11150     // xform, so create a select of the addresses.
11151     SDValue Addr;
11152     if (TheSelect->getOpcode() == ISD::SELECT) {
11153       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11154       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11155           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11156         return false;
11157       // The loads must not depend on one another.
11158       if (LLD->isPredecessorOf(RLD) ||
11159           RLD->isPredecessorOf(LLD))
11160         return false;
11161       Addr = DAG.getSelect(SDLoc(TheSelect),
11162                            LLD->getBasePtr().getValueType(),
11163                            TheSelect->getOperand(0), LLD->getBasePtr(),
11164                            RLD->getBasePtr());
11165     } else {  // Otherwise SELECT_CC
11166       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11167       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11168
11169       if ((LLD->hasAnyUseOfValue(1) &&
11170            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11171           (RLD->hasAnyUseOfValue(1) &&
11172            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11173         return false;
11174
11175       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11176                          LLD->getBasePtr().getValueType(),
11177                          TheSelect->getOperand(0),
11178                          TheSelect->getOperand(1),
11179                          LLD->getBasePtr(), RLD->getBasePtr(),
11180                          TheSelect->getOperand(4));
11181     }
11182
11183     SDValue Load;
11184     // It is safe to replace the two loads if they have different alignments,
11185     // but the new load must be the minimum (most restrictive) alignment of the
11186     // inputs.
11187     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11188     unsigned Alignment = std::min(LLD->getAlignment(),RLD->getAlignment());
11189     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11190       Load = DAG.getLoad(TheSelect->getValueType(0),
11191                          SDLoc(TheSelect),
11192                          // FIXME: Discards pointer and AA info.
11193                          LLD->getChain(), Addr, MachinePointerInfo(),
11194                          LLD->isVolatile(), LLD->isNonTemporal(),
11195                          isInvariant, Alignment);
11196     } else {
11197       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11198                             RLD->getExtensionType() : LLD->getExtensionType(),
11199                             SDLoc(TheSelect),
11200                             TheSelect->getValueType(0),
11201                             // FIXME: Discards pointer and AA info.
11202                             LLD->getChain(), Addr, MachinePointerInfo(),
11203                             LLD->getMemoryVT(), LLD->isVolatile(),
11204                             LLD->isNonTemporal(), isInvariant, Alignment);
11205     }
11206
11207     // Users of the select now use the result of the load.
11208     CombineTo(TheSelect, Load);
11209
11210     // Users of the old loads now use the new load's chain.  We know the
11211     // old-load value is dead now.
11212     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11213     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11214     return true;
11215   }
11216
11217   return false;
11218 }
11219
11220 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11221 /// where 'cond' is the comparison specified by CC.
11222 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11223                                       SDValue N2, SDValue N3,
11224                                       ISD::CondCode CC, bool NotExtCompare) {
11225   // (x ? y : y) -> y.
11226   if (N2 == N3) return N2;
11227
11228   EVT VT = N2.getValueType();
11229   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11230   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11231   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11232
11233   // Determine if the condition we're dealing with is constant
11234   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11235                               N0, N1, CC, DL, false);
11236   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11237   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11238
11239   // fold select_cc true, x, y -> x
11240   if (SCCC && !SCCC->isNullValue())
11241     return N2;
11242   // fold select_cc false, x, y -> y
11243   if (SCCC && SCCC->isNullValue())
11244     return N3;
11245
11246   // Check to see if we can simplify the select into an fabs node
11247   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11248     // Allow either -0.0 or 0.0
11249     if (CFP->getValueAPF().isZero()) {
11250       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11251       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11252           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11253           N2 == N3.getOperand(0))
11254         return DAG.getNode(ISD::FABS, DL, VT, N0);
11255
11256       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11257       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11258           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11259           N2.getOperand(0) == N3)
11260         return DAG.getNode(ISD::FABS, DL, VT, N3);
11261     }
11262   }
11263
11264   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11265   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11266   // in it.  This is a win when the constant is not otherwise available because
11267   // it replaces two constant pool loads with one.  We only do this if the FP
11268   // type is known to be legal, because if it isn't, then we are before legalize
11269   // types an we want the other legalization to happen first (e.g. to avoid
11270   // messing with soft float) and if the ConstantFP is not legal, because if
11271   // it is legal, we may not need to store the FP constant in a constant pool.
11272   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11273     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11274       if (TLI.isTypeLegal(N2.getValueType()) &&
11275           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11276                TargetLowering::Legal &&
11277            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11278            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11279           // If both constants have multiple uses, then we won't need to do an
11280           // extra load, they are likely around in registers for other users.
11281           (TV->hasOneUse() || FV->hasOneUse())) {
11282         Constant *Elts[] = {
11283           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11284           const_cast<ConstantFP*>(TV->getConstantFPValue())
11285         };
11286         Type *FPTy = Elts[0]->getType();
11287         const DataLayout &TD = *TLI.getDataLayout();
11288
11289         // Create a ConstantArray of the two constants.
11290         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11291         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11292                                             TD.getPrefTypeAlignment(FPTy));
11293         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11294
11295         // Get the offsets to the 0 and 1 element of the array so that we can
11296         // select between them.
11297         SDValue Zero = DAG.getIntPtrConstant(0);
11298         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11299         SDValue One = DAG.getIntPtrConstant(EltSize);
11300
11301         SDValue Cond = DAG.getSetCC(DL,
11302                                     getSetCCResultType(N0.getValueType()),
11303                                     N0, N1, CC);
11304         AddToWorklist(Cond.getNode());
11305         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11306                                           Cond, One, Zero);
11307         AddToWorklist(CstOffset.getNode());
11308         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11309                             CstOffset);
11310         AddToWorklist(CPIdx.getNode());
11311         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11312                            MachinePointerInfo::getConstantPool(), false,
11313                            false, false, Alignment);
11314
11315       }
11316     }
11317
11318   // Check to see if we can perform the "gzip trick", transforming
11319   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11320   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11321       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11322        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11323     EVT XType = N0.getValueType();
11324     EVT AType = N2.getValueType();
11325     if (XType.bitsGE(AType)) {
11326       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11327       // single-bit constant.
11328       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11329         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11330         ShCtV = XType.getSizeInBits()-ShCtV-1;
11331         SDValue ShCt = DAG.getConstant(ShCtV,
11332                                        getShiftAmountTy(N0.getValueType()));
11333         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11334                                     XType, N0, ShCt);
11335         AddToWorklist(Shift.getNode());
11336
11337         if (XType.bitsGT(AType)) {
11338           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11339           AddToWorklist(Shift.getNode());
11340         }
11341
11342         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11343       }
11344
11345       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11346                                   XType, N0,
11347                                   DAG.getConstant(XType.getSizeInBits()-1,
11348                                          getShiftAmountTy(N0.getValueType())));
11349       AddToWorklist(Shift.getNode());
11350
11351       if (XType.bitsGT(AType)) {
11352         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11353         AddToWorklist(Shift.getNode());
11354       }
11355
11356       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11357     }
11358   }
11359
11360   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11361   // where y is has a single bit set.
11362   // A plaintext description would be, we can turn the SELECT_CC into an AND
11363   // when the condition can be materialized as an all-ones register.  Any
11364   // single bit-test can be materialized as an all-ones register with
11365   // shift-left and shift-right-arith.
11366   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11367       N0->getValueType(0) == VT &&
11368       N1C && N1C->isNullValue() &&
11369       N2C && N2C->isNullValue()) {
11370     SDValue AndLHS = N0->getOperand(0);
11371     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11372     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11373       // Shift the tested bit over the sign bit.
11374       APInt AndMask = ConstAndRHS->getAPIntValue();
11375       SDValue ShlAmt =
11376         DAG.getConstant(AndMask.countLeadingZeros(),
11377                         getShiftAmountTy(AndLHS.getValueType()));
11378       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11379
11380       // Now arithmetic right shift it all the way over, so the result is either
11381       // all-ones, or zero.
11382       SDValue ShrAmt =
11383         DAG.getConstant(AndMask.getBitWidth()-1,
11384                         getShiftAmountTy(Shl.getValueType()));
11385       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11386
11387       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11388     }
11389   }
11390
11391   // fold select C, 16, 0 -> shl C, 4
11392   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11393       TLI.getBooleanContents(N0.getValueType()) ==
11394           TargetLowering::ZeroOrOneBooleanContent) {
11395
11396     // If the caller doesn't want us to simplify this into a zext of a compare,
11397     // don't do it.
11398     if (NotExtCompare && N2C->getAPIntValue() == 1)
11399       return SDValue();
11400
11401     // Get a SetCC of the condition
11402     // NOTE: Don't create a SETCC if it's not legal on this target.
11403     if (!LegalOperations ||
11404         TLI.isOperationLegal(ISD::SETCC,
11405           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11406       SDValue Temp, SCC;
11407       // cast from setcc result type to select result type
11408       if (LegalTypes) {
11409         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11410                             N0, N1, CC);
11411         if (N2.getValueType().bitsLT(SCC.getValueType()))
11412           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11413                                         N2.getValueType());
11414         else
11415           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11416                              N2.getValueType(), SCC);
11417       } else {
11418         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11419         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11420                            N2.getValueType(), SCC);
11421       }
11422
11423       AddToWorklist(SCC.getNode());
11424       AddToWorklist(Temp.getNode());
11425
11426       if (N2C->getAPIntValue() == 1)
11427         return Temp;
11428
11429       // shl setcc result by log2 n2c
11430       return DAG.getNode(
11431           ISD::SHL, DL, N2.getValueType(), Temp,
11432           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11433                           getShiftAmountTy(Temp.getValueType())));
11434     }
11435   }
11436
11437   // Check to see if this is the equivalent of setcc
11438   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11439   // otherwise, go ahead with the folds.
11440   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11441     EVT XType = N0.getValueType();
11442     if (!LegalOperations ||
11443         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11444       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11445       if (Res.getValueType() != VT)
11446         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11447       return Res;
11448     }
11449
11450     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11451     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11452         (!LegalOperations ||
11453          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11454       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11455       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11456                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11457                                        getShiftAmountTy(Ctlz.getValueType())));
11458     }
11459     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11460     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11461       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11462                                   XType, DAG.getConstant(0, XType), N0);
11463       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11464       return DAG.getNode(ISD::SRL, DL, XType,
11465                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11466                          DAG.getConstant(XType.getSizeInBits()-1,
11467                                          getShiftAmountTy(XType)));
11468     }
11469     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11470     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11471       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11472                                  DAG.getConstant(XType.getSizeInBits()-1,
11473                                          getShiftAmountTy(N0.getValueType())));
11474       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11475     }
11476   }
11477
11478   // Check to see if this is an integer abs.
11479   // select_cc setg[te] X,  0,  X, -X ->
11480   // select_cc setgt    X, -1,  X, -X ->
11481   // select_cc setl[te] X,  0, -X,  X ->
11482   // select_cc setlt    X,  1, -X,  X ->
11483   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11484   if (N1C) {
11485     ConstantSDNode *SubC = nullptr;
11486     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11487          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11488         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11489       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11490     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11491               (N1C->isOne() && CC == ISD::SETLT)) &&
11492              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11493       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11494
11495     EVT XType = N0.getValueType();
11496     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11497       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11498                                   N0,
11499                                   DAG.getConstant(XType.getSizeInBits()-1,
11500                                          getShiftAmountTy(N0.getValueType())));
11501       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11502                                 XType, N0, Shift);
11503       AddToWorklist(Shift.getNode());
11504       AddToWorklist(Add.getNode());
11505       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11506     }
11507   }
11508
11509   return SDValue();
11510 }
11511
11512 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11513 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11514                                    SDValue N1, ISD::CondCode Cond,
11515                                    SDLoc DL, bool foldBooleans) {
11516   TargetLowering::DAGCombinerInfo
11517     DagCombineInfo(DAG, Level, false, this);
11518   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11519 }
11520
11521 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11522 /// a DAG expression to select that will generate the same value by multiplying
11523 /// by a magic number.  See:
11524 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11525 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11526   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11527   if (!C)
11528     return SDValue();
11529
11530   // Avoid division by zero.
11531   if (!C->getAPIntValue())
11532     return SDValue();
11533
11534   std::vector<SDNode*> Built;
11535   SDValue S =
11536       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11537
11538   for (SDNode *N : Built)
11539     AddToWorklist(N);
11540   return S;
11541 }
11542
11543 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11544 /// power of 2, return a DAG expression to select that will generate the same
11545 /// value by right shifting.
11546 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11547   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11548   if (!C)
11549     return SDValue();
11550
11551   // Avoid division by zero.
11552   if (!C->getAPIntValue())
11553     return SDValue();
11554
11555   std::vector<SDNode *> Built;
11556   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11557
11558   for (SDNode *N : Built)
11559     AddToWorklist(N);
11560   return S;
11561 }
11562
11563 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11564 /// return a DAG expression to select that will generate the same value by
11565 /// multiplying by a magic number.  See:
11566 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11567 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11568   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11569   if (!C)
11570     return SDValue();
11571
11572   // Avoid division by zero.
11573   if (!C->getAPIntValue())
11574     return SDValue();
11575
11576   std::vector<SDNode*> Built;
11577   SDValue S =
11578       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11579
11580   for (SDNode *N : Built)
11581     AddToWorklist(N);
11582   return S;
11583 }
11584
11585 /// FindBaseOffset - Return true if base is a frame index, which is known not
11586 // to alias with anything but itself.  Provides base object and offset as
11587 // results.
11588 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11589                            const GlobalValue *&GV, const void *&CV) {
11590   // Assume it is a primitive operation.
11591   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11592
11593   // If it's an adding a simple constant then integrate the offset.
11594   if (Base.getOpcode() == ISD::ADD) {
11595     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11596       Base = Base.getOperand(0);
11597       Offset += C->getZExtValue();
11598     }
11599   }
11600
11601   // Return the underlying GlobalValue, and update the Offset.  Return false
11602   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11603   // by multiple nodes with different offsets.
11604   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11605     GV = G->getGlobal();
11606     Offset += G->getOffset();
11607     return false;
11608   }
11609
11610   // Return the underlying Constant value, and update the Offset.  Return false
11611   // for ConstantSDNodes since the same constant pool entry may be represented
11612   // by multiple nodes with different offsets.
11613   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11614     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11615                                          : (const void *)C->getConstVal();
11616     Offset += C->getOffset();
11617     return false;
11618   }
11619   // If it's any of the following then it can't alias with anything but itself.
11620   return isa<FrameIndexSDNode>(Base);
11621 }
11622
11623 /// isAlias - Return true if there is any possibility that the two addresses
11624 /// overlap.
11625 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11626   // If they are the same then they must be aliases.
11627   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11628
11629   // If they are both volatile then they cannot be reordered.
11630   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11631
11632   // Gather base node and offset information.
11633   SDValue Base1, Base2;
11634   int64_t Offset1, Offset2;
11635   const GlobalValue *GV1, *GV2;
11636   const void *CV1, *CV2;
11637   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11638                                       Base1, Offset1, GV1, CV1);
11639   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11640                                       Base2, Offset2, GV2, CV2);
11641
11642   // If they have a same base address then check to see if they overlap.
11643   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11644     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11645              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11646
11647   // It is possible for different frame indices to alias each other, mostly
11648   // when tail call optimization reuses return address slots for arguments.
11649   // To catch this case, look up the actual index of frame indices to compute
11650   // the real alias relationship.
11651   if (isFrameIndex1 && isFrameIndex2) {
11652     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11653     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11654     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11655     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11656              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11657   }
11658
11659   // Otherwise, if we know what the bases are, and they aren't identical, then
11660   // we know they cannot alias.
11661   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11662     return false;
11663
11664   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11665   // compared to the size and offset of the access, we may be able to prove they
11666   // do not alias.  This check is conservative for now to catch cases created by
11667   // splitting vector types.
11668   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11669       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11670       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11671        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11672       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11673     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11674     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11675
11676     // There is no overlap between these relatively aligned accesses of similar
11677     // size, return no alias.
11678     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11679         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11680       return false;
11681   }
11682
11683   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11684     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11685 #ifndef NDEBUG
11686   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11687       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11688     UseAA = false;
11689 #endif
11690   if (UseAA &&
11691       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11692     // Use alias analysis information.
11693     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11694                                  Op1->getSrcValueOffset());
11695     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11696         Op0->getSrcValueOffset() - MinOffset;
11697     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11698         Op1->getSrcValueOffset() - MinOffset;
11699     AliasAnalysis::AliasResult AAResult =
11700         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11701                                          Overlap1,
11702                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11703                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11704                                          Overlap2,
11705                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11706     if (AAResult == AliasAnalysis::NoAlias)
11707       return false;
11708   }
11709
11710   // Otherwise we have to assume they alias.
11711   return true;
11712 }
11713
11714 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11715 /// looking for aliasing nodes and adding them to the Aliases vector.
11716 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11717                                    SmallVectorImpl<SDValue> &Aliases) {
11718   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11719   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11720
11721   // Get alias information for node.
11722   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11723
11724   // Starting off.
11725   Chains.push_back(OriginalChain);
11726   unsigned Depth = 0;
11727
11728   // Look at each chain and determine if it is an alias.  If so, add it to the
11729   // aliases list.  If not, then continue up the chain looking for the next
11730   // candidate.
11731   while (!Chains.empty()) {
11732     SDValue Chain = Chains.back();
11733     Chains.pop_back();
11734
11735     // For TokenFactor nodes, look at each operand and only continue up the
11736     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11737     // find more and revert to original chain since the xform is unlikely to be
11738     // profitable.
11739     //
11740     // FIXME: The depth check could be made to return the last non-aliasing
11741     // chain we found before we hit a tokenfactor rather than the original
11742     // chain.
11743     if (Depth > 6 || Aliases.size() == 2) {
11744       Aliases.clear();
11745       Aliases.push_back(OriginalChain);
11746       return;
11747     }
11748
11749     // Don't bother if we've been before.
11750     if (!Visited.insert(Chain.getNode()))
11751       continue;
11752
11753     switch (Chain.getOpcode()) {
11754     case ISD::EntryToken:
11755       // Entry token is ideal chain operand, but handled in FindBetterChain.
11756       break;
11757
11758     case ISD::LOAD:
11759     case ISD::STORE: {
11760       // Get alias information for Chain.
11761       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11762           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11763
11764       // If chain is alias then stop here.
11765       if (!(IsLoad && IsOpLoad) &&
11766           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11767         Aliases.push_back(Chain);
11768       } else {
11769         // Look further up the chain.
11770         Chains.push_back(Chain.getOperand(0));
11771         ++Depth;
11772       }
11773       break;
11774     }
11775
11776     case ISD::TokenFactor:
11777       // We have to check each of the operands of the token factor for "small"
11778       // token factors, so we queue them up.  Adding the operands to the queue
11779       // (stack) in reverse order maintains the original order and increases the
11780       // likelihood that getNode will find a matching token factor (CSE.)
11781       if (Chain.getNumOperands() > 16) {
11782         Aliases.push_back(Chain);
11783         break;
11784       }
11785       for (unsigned n = Chain.getNumOperands(); n;)
11786         Chains.push_back(Chain.getOperand(--n));
11787       ++Depth;
11788       break;
11789
11790     default:
11791       // For all other instructions we will just have to take what we can get.
11792       Aliases.push_back(Chain);
11793       break;
11794     }
11795   }
11796
11797   // We need to be careful here to also search for aliases through the
11798   // value operand of a store, etc. Consider the following situation:
11799   //   Token1 = ...
11800   //   L1 = load Token1, %52
11801   //   S1 = store Token1, L1, %51
11802   //   L2 = load Token1, %52+8
11803   //   S2 = store Token1, L2, %51+8
11804   //   Token2 = Token(S1, S2)
11805   //   L3 = load Token2, %53
11806   //   S3 = store Token2, L3, %52
11807   //   L4 = load Token2, %53+8
11808   //   S4 = store Token2, L4, %52+8
11809   // If we search for aliases of S3 (which loads address %52), and we look
11810   // only through the chain, then we'll miss the trivial dependence on L1
11811   // (which also loads from %52). We then might change all loads and
11812   // stores to use Token1 as their chain operand, which could result in
11813   // copying %53 into %52 before copying %52 into %51 (which should
11814   // happen first).
11815   //
11816   // The problem is, however, that searching for such data dependencies
11817   // can become expensive, and the cost is not directly related to the
11818   // chain depth. Instead, we'll rule out such configurations here by
11819   // insisting that we've visited all chain users (except for users
11820   // of the original chain, which is not necessary). When doing this,
11821   // we need to look through nodes we don't care about (otherwise, things
11822   // like register copies will interfere with trivial cases).
11823
11824   SmallVector<const SDNode *, 16> Worklist;
11825   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11826        IE = Visited.end(); I != IE; ++I)
11827     if (*I != OriginalChain.getNode())
11828       Worklist.push_back(*I);
11829
11830   while (!Worklist.empty()) {
11831     const SDNode *M = Worklist.pop_back_val();
11832
11833     // We have already visited M, and want to make sure we've visited any uses
11834     // of M that we care about. For uses that we've not visisted, and don't
11835     // care about, queue them to the worklist.
11836
11837     for (SDNode::use_iterator UI = M->use_begin(),
11838          UIE = M->use_end(); UI != UIE; ++UI)
11839       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11840         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11841           // We've not visited this use, and we care about it (it could have an
11842           // ordering dependency with the original node).
11843           Aliases.clear();
11844           Aliases.push_back(OriginalChain);
11845           return;
11846         }
11847
11848         // We've not visited this use, but we don't care about it. Mark it as
11849         // visited and enqueue it to the worklist.
11850         Worklist.push_back(*UI);
11851       }
11852   }
11853 }
11854
11855 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11856 /// for a better chain (aliasing node.)
11857 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11858   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11859
11860   // Accumulate all the aliases to this node.
11861   GatherAllAliases(N, OldChain, Aliases);
11862
11863   // If no operands then chain to entry token.
11864   if (Aliases.size() == 0)
11865     return DAG.getEntryNode();
11866
11867   // If a single operand then chain to it.  We don't need to revisit it.
11868   if (Aliases.size() == 1)
11869     return Aliases[0];
11870
11871   // Construct a custom tailored token factor.
11872   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11873 }
11874
11875 // SelectionDAG::Combine - This is the entry point for the file.
11876 //
11877 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11878                            CodeGenOpt::Level OptLevel) {
11879   /// run - This is the main entry point to this class.
11880   ///
11881   DAGCombiner(*this, AA, OptLevel).Run(Level);
11882 }