Optionally enable more-aggressive FMA formation in DAGCombine
[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   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
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     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFCOPYSIGN(SDNode *N);
280     SDValue visitSINT_TO_FP(SDNode *N);
281     SDValue visitUINT_TO_FP(SDNode *N);
282     SDValue visitFP_TO_SINT(SDNode *N);
283     SDValue visitFP_TO_UINT(SDNode *N);
284     SDValue visitFP_ROUND(SDNode *N);
285     SDValue visitFP_ROUND_INREG(SDNode *N);
286     SDValue visitFP_EXTEND(SDNode *N);
287     SDValue visitFNEG(SDNode *N);
288     SDValue visitFABS(SDNode *N);
289     SDValue visitFCEIL(SDNode *N);
290     SDValue visitFTRUNC(SDNode *N);
291     SDValue visitFFLOOR(SDNode *N);
292     SDValue visitBRCOND(SDNode *N);
293     SDValue visitBR_CC(SDNode *N);
294     SDValue visitLOAD(SDNode *N);
295     SDValue visitSTORE(SDNode *N);
296     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298     SDValue visitBUILD_VECTOR(SDNode *N);
299     SDValue visitCONCAT_VECTORS(SDNode *N);
300     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
301     SDValue visitVECTOR_SHUFFLE(SDNode *N);
302     SDValue visitINSERT_SUBVECTOR(SDNode *N);
303
304     SDValue XformToShuffleWithZero(SDNode *N);
305     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306
307     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308
309     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
311     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
313                              SDValue N3, ISD::CondCode CC,
314                              bool NotExtCompare = false);
315     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
316                           SDLoc DL, bool foldBooleans = true);
317
318     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319                            SDValue &CC) const;
320     bool isOneUseSetCC(SDValue N) const;
321
322     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323                                          unsigned HiOp);
324     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
325     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
326     SDValue BuildSDIV(SDNode *N);
327     SDValue BuildSDIVPow2(SDNode *N);
328     SDValue BuildUDIV(SDNode *N);
329     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330                                bool DemandHighBits = true);
331     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
332     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333                               SDValue InnerPos, SDValue InnerNeg,
334                               unsigned PosOpcode, unsigned NegOpcode,
335                               SDLoc DL);
336     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
337     SDValue ReduceLoadWidth(SDNode *N);
338     SDValue ReduceLoadOpStoreWidth(SDNode *N);
339     SDValue TransformFPLoadStorePair(SDNode *N);
340     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
341     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342
343     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344
345     /// Walk up chain skipping non-aliasing memory nodes,
346     /// looking for aliasing nodes and adding them to the Aliases vector.
347     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
348                           SmallVectorImpl<SDValue> &Aliases);
349
350     /// Return true if there is any possibility that the two addresses overlap.
351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
352
353     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354     /// chain (aliasing node.)
355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
356
357     /// Merge consecutive store operations into a wide store.
358     /// This optimization uses wide integers or vectors when possible.
359     /// \return True if some memory operations were changed.
360     bool MergeConsecutiveStores(StoreSDNode *N);
361
362     /// \brief Try to transform a truncation where C is a constant:
363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
364     ///
365     /// \p N needs to be a truncation and its first operand an AND. Other
366     /// requirements are checked by the function (e.g. that trunc is
367     /// single-use) and if missed an empty SDValue is returned.
368     SDValue distributeTruncateThroughAnd(SDNode *N);
369
370   public:
371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374       AttributeSet FnAttrs =
375           DAG.getMachineFunction().getFunction()->getAttributes();
376       ForCodeSize =
377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378                                Attribute::OptimizeForSize) ||
379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
380     }
381
382     /// Runs the dag combiner on all nodes in the work list
383     void Run(CombineLevel AtLevel);
384
385     SelectionDAG &getDAG() const { return DAG; }
386
387     /// Returns a type large enough to hold any valid shift amount - before type
388     /// legalization these can be huge.
389     EVT getShiftAmountTy(EVT LHSTy) {
390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391       if (LHSTy.isVector())
392         return LHSTy;
393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394                         : TLI.getPointerTy();
395     }
396
397     /// This method returns true if we are running before type legalization or
398     /// if the specified VT is legal.
399     bool isTypeLegal(const EVT &VT) {
400       if (!LegalTypes) return true;
401       return TLI.isTypeLegal(VT);
402     }
403
404     /// Convenience wrapper around TargetLowering::getSetCCResultType
405     EVT getSetCCResultType(EVT VT) const {
406       return TLI.getSetCCResultType(*DAG.getContext(), VT);
407     }
408   };
409 }
410
411
412 namespace {
413 /// This class is a DAGUpdateListener that removes any deleted
414 /// nodes from the worklist.
415 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
416   DAGCombiner &DC;
417 public:
418   explicit WorklistRemover(DAGCombiner &dc)
419     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
420
421   void NodeDeleted(SDNode *N, SDNode *E) override {
422     DC.removeFromWorklist(N);
423   }
424 };
425 }
426
427 //===----------------------------------------------------------------------===//
428 //  TargetLowering::DAGCombinerInfo implementation
429 //===----------------------------------------------------------------------===//
430
431 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
432   ((DAGCombiner*)DC)->AddToWorklist(N);
433 }
434
435 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
436   ((DAGCombiner*)DC)->removeFromWorklist(N);
437 }
438
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
442 }
443
444 SDValue TargetLowering::DAGCombinerInfo::
445 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
447 }
448
449
450 SDValue TargetLowering::DAGCombinerInfo::
451 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
453 }
454
455 void TargetLowering::DAGCombinerInfo::
456 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
458 }
459
460 //===----------------------------------------------------------------------===//
461 // Helper Functions
462 //===----------------------------------------------------------------------===//
463
464 void DAGCombiner::deleteAndRecombine(SDNode *N) {
465   removeFromWorklist(N);
466
467   // If the operands of this node are only used by the node, they will now be
468   // dead. Make sure to re-visit them and recursively delete dead nodes.
469   for (const SDValue &Op : N->ops())
470     // For an operand generating multiple values, one of the values may
471     // become dead allowing further simplification (e.g. split index
472     // arithmetic from an indexed load).
473     if (Op->hasOneUse() || Op->getNumValues() > 1)
474       AddToWorklist(Op.getNode());
475
476   DAG.DeleteNode(N);
477 }
478
479 /// Return 1 if we can compute the negated form of the specified expression for
480 /// the same cost as the expression itself, or 2 if we can compute the negated
481 /// form more cheaply than the expression itself.
482 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
483                                const TargetLowering &TLI,
484                                const TargetOptions *Options,
485                                unsigned Depth = 0) {
486   // fneg is removable even if it has multiple uses.
487   if (Op.getOpcode() == ISD::FNEG) return 2;
488
489   // Don't allow anything with multiple uses.
490   if (!Op.hasOneUse()) return 0;
491
492   // Don't recurse exponentially.
493   if (Depth > 6) return 0;
494
495   switch (Op.getOpcode()) {
496   default: return false;
497   case ISD::ConstantFP:
498     // Don't invert constant FP values after legalize.  The negated constant
499     // isn't necessarily legal.
500     return LegalOperations ? 0 : 1;
501   case ISD::FADD:
502     // FIXME: determine better conditions for this xform.
503     if (!Options->UnsafeFPMath) return 0;
504
505     // After operation legalization, it might not be legal to create new FSUBs.
506     if (LegalOperations &&
507         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
508       return 0;
509
510     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
511     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512                                     Options, Depth + 1))
513       return V;
514     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
515     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516                               Depth + 1);
517   case ISD::FSUB:
518     // We can't turn -(A-B) into B-A when we honor signed zeros.
519     if (!Options->UnsafeFPMath) return 0;
520
521     // fold (fneg (fsub A, B)) -> (fsub B, A)
522     return 1;
523
524   case ISD::FMUL:
525   case ISD::FDIV:
526     if (Options->HonorSignDependentRoundingFPMath()) return 0;
527
528     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
529     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
530                                     Options, Depth + 1))
531       return V;
532
533     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
534                               Depth + 1);
535
536   case ISD::FP_EXTEND:
537   case ISD::FP_ROUND:
538   case ISD::FSIN:
539     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
540                               Depth + 1);
541   }
542 }
543
544 /// If isNegatibleForFree returns true, return the newly negated expression.
545 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
546                                     bool LegalOperations, unsigned Depth = 0) {
547   const TargetOptions &Options = DAG.getTarget().Options;
548   // fneg is removable even if it has multiple uses.
549   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
550
551   // Don't allow anything with multiple uses.
552   assert(Op.hasOneUse() && "Unknown reuse!");
553
554   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
555   switch (Op.getOpcode()) {
556   default: llvm_unreachable("Unknown code");
557   case ISD::ConstantFP: {
558     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
559     V.changeSign();
560     return DAG.getConstantFP(V, Op.getValueType());
561   }
562   case ISD::FADD:
563     // FIXME: determine better conditions for this xform.
564     assert(Options.UnsafeFPMath);
565
566     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
567     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
568                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
569       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
570                          GetNegatedExpression(Op.getOperand(0), DAG,
571                                               LegalOperations, Depth+1),
572                          Op.getOperand(1));
573     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
574     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
575                        GetNegatedExpression(Op.getOperand(1), DAG,
576                                             LegalOperations, Depth+1),
577                        Op.getOperand(0));
578   case ISD::FSUB:
579     // We can't turn -(A-B) into B-A when we honor signed zeros.
580     assert(Options.UnsafeFPMath);
581
582     // fold (fneg (fsub 0, B)) -> B
583     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
584       if (N0CFP->getValueAPF().isZero())
585         return Op.getOperand(1);
586
587     // fold (fneg (fsub A, B)) -> (fsub B, A)
588     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
589                        Op.getOperand(1), Op.getOperand(0));
590
591   case ISD::FMUL:
592   case ISD::FDIV:
593     assert(!Options.HonorSignDependentRoundingFPMath());
594
595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
596     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
597                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
598       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599                          GetNegatedExpression(Op.getOperand(0), DAG,
600                                               LegalOperations, Depth+1),
601                          Op.getOperand(1));
602
603     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
605                        Op.getOperand(0),
606                        GetNegatedExpression(Op.getOperand(1), DAG,
607                                             LegalOperations, Depth+1));
608
609   case ISD::FP_EXTEND:
610   case ISD::FSIN:
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(0), DAG,
613                                             LegalOperations, Depth+1));
614   case ISD::FP_ROUND:
615       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616                          GetNegatedExpression(Op.getOperand(0), DAG,
617                                               LegalOperations, Depth+1),
618                          Op.getOperand(1));
619   }
620 }
621
622 // Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
628                                     SDValue &CC) const {
629   if (N.getOpcode() == ISD::SETCC) {
630     LHS = N.getOperand(0);
631     RHS = N.getOperand(1);
632     CC  = N.getOperand(2);
633     return true;
634   }
635
636   if (N.getOpcode() != ISD::SELECT_CC ||
637       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
639     return false;
640
641   LHS = N.getOperand(0);
642   RHS = N.getOperand(1);
643   CC  = N.getOperand(4);
644   return true;
645 }
646
647 /// Return true if this is a SetCC-equivalent operation with only one use.
648 /// If this is true, it allows the users to invert the operation for free when
649 /// it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
651   SDValue N0, N1, N2;
652   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
653     return true;
654   return false;
655 }
656
657 /// Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
661   if (!C)
662     return false;
663
664   APInt SplatUndef;
665   unsigned SplatBitSize;
666   bool HasAnyUndefs;
667   EVT EltVT = N->getValueType(0).getVectorElementType();
668   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
669                              HasAnyUndefs) &&
670           EltVT.getSizeInBits() >= SplatBitSize);
671 }
672
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675   if (isa<ConstantSDNode>(N))
676     return N.getNode();
677   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678   if (BV && BV->isConstant())
679     return BV;
680   return nullptr;
681 }
682
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
684 // int.
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
687     return CN;
688
689   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690     BitVector UndefElements;
691     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
692
693     // BuildVectors can truncate their operands. Ignore that case here.
694     // FIXME: We blindly ignore splats which include undef which is overly
695     // pessimistic.
696     if (CN && UndefElements.none() &&
697         CN->getValueType(0) == N.getValueType().getScalarType())
698       return CN;
699   }
700
701   return nullptr;
702 }
703
704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
705 // float.
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
708     return CN;
709
710   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711     BitVector UndefElements;
712     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
713
714     if (CN && UndefElements.none())
715       return CN;
716   }
717
718   return nullptr;
719 }
720
721 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
722                                     SDValue N0, SDValue N1) {
723   EVT VT = N0.getValueType();
724   if (N0.getOpcode() == Opc) {
725     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
726       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
727         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
728         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
729         if (!OpNode.getNode())
730           return SDValue();
731         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
732       }
733       if (N0.hasOneUse()) {
734         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
735         // use
736         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
737         if (!OpNode.getNode())
738           return SDValue();
739         AddToWorklist(OpNode.getNode());
740         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
741       }
742     }
743   }
744
745   if (N1.getOpcode() == Opc) {
746     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
747       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
748         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
749         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
750         if (!OpNode.getNode())
751           return SDValue();
752         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
753       }
754       if (N1.hasOneUse()) {
755         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
756         // use
757         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
758         if (!OpNode.getNode())
759           return SDValue();
760         AddToWorklist(OpNode.getNode());
761         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
762       }
763     }
764   }
765
766   return SDValue();
767 }
768
769 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
770                                bool AddTo) {
771   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
772   ++NodesCombined;
773   DEBUG(dbgs() << "\nReplacing.1 ";
774         N->dump(&DAG);
775         dbgs() << "\nWith: ";
776         To[0].getNode()->dump(&DAG);
777         dbgs() << " and " << NumTo-1 << " other values\n";
778         for (unsigned i = 0, e = NumTo; i != e; ++i)
779           assert((!To[i].getNode() ||
780                   N->getValueType(i) == To[i].getValueType()) &&
781                  "Cannot combine value to value of different type!"));
782   WorklistRemover DeadNodes(*this);
783   DAG.ReplaceAllUsesWith(N, To);
784   if (AddTo) {
785     // Push the new nodes and any users onto the worklist
786     for (unsigned i = 0, e = NumTo; i != e; ++i) {
787       if (To[i].getNode()) {
788         AddToWorklist(To[i].getNode());
789         AddUsersToWorklist(To[i].getNode());
790       }
791     }
792   }
793
794   // Finally, if the node is now dead, remove it from the graph.  The node
795   // may not be dead if the replacement process recursively simplified to
796   // something else needing this node.
797   if (N->use_empty())
798     deleteAndRecombine(N);
799   return SDValue(N, 0);
800 }
801
802 void DAGCombiner::
803 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
804   // Replace all uses.  If any nodes become isomorphic to other nodes and
805   // are deleted, make sure to remove them from our worklist.
806   WorklistRemover DeadNodes(*this);
807   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
808
809   // Push the new node and any (possibly new) users onto the worklist.
810   AddToWorklist(TLO.New.getNode());
811   AddUsersToWorklist(TLO.New.getNode());
812
813   // Finally, if the node is now dead, remove it from the graph.  The node
814   // may not be dead if the replacement process recursively simplified to
815   // something else needing this node.
816   if (TLO.Old.getNode()->use_empty())
817     deleteAndRecombine(TLO.Old.getNode());
818 }
819
820 /// Check the specified integer node value to see if it can be simplified or if
821 /// things it uses can be simplified by bit propagation. If so, return true.
822 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
823   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
824   APInt KnownZero, KnownOne;
825   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
826     return false;
827
828   // Revisit the node.
829   AddToWorklist(Op.getNode());
830
831   // Replace the old value with the new one.
832   ++NodesCombined;
833   DEBUG(dbgs() << "\nReplacing.2 ";
834         TLO.Old.getNode()->dump(&DAG);
835         dbgs() << "\nWith: ";
836         TLO.New.getNode()->dump(&DAG);
837         dbgs() << '\n');
838
839   CommitTargetLoweringOpt(TLO);
840   return true;
841 }
842
843 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
844   SDLoc dl(Load);
845   EVT VT = Load->getValueType(0);
846   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
847
848   DEBUG(dbgs() << "\nReplacing.9 ";
849         Load->dump(&DAG);
850         dbgs() << "\nWith: ";
851         Trunc.getNode()->dump(&DAG);
852         dbgs() << '\n');
853   WorklistRemover DeadNodes(*this);
854   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
855   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
856   deleteAndRecombine(Load);
857   AddToWorklist(Trunc.getNode());
858 }
859
860 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
861   Replace = false;
862   SDLoc dl(Op);
863   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
864     EVT MemVT = LD->getMemoryVT();
865     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
866       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
867                                                   : ISD::EXTLOAD)
868       : LD->getExtensionType();
869     Replace = true;
870     return DAG.getExtLoad(ExtType, dl, PVT,
871                           LD->getChain(), LD->getBasePtr(),
872                           MemVT, LD->getMemOperand());
873   }
874
875   unsigned Opc = Op.getOpcode();
876   switch (Opc) {
877   default: break;
878   case ISD::AssertSext:
879     return DAG.getNode(ISD::AssertSext, dl, PVT,
880                        SExtPromoteOperand(Op.getOperand(0), PVT),
881                        Op.getOperand(1));
882   case ISD::AssertZext:
883     return DAG.getNode(ISD::AssertZext, dl, PVT,
884                        ZExtPromoteOperand(Op.getOperand(0), PVT),
885                        Op.getOperand(1));
886   case ISD::Constant: {
887     unsigned ExtOpc =
888       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
889     return DAG.getNode(ExtOpc, dl, PVT, Op);
890   }
891   }
892
893   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
894     return SDValue();
895   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
896 }
897
898 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
899   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
900     return SDValue();
901   EVT OldVT = Op.getValueType();
902   SDLoc dl(Op);
903   bool Replace = false;
904   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
905   if (!NewOp.getNode())
906     return SDValue();
907   AddToWorklist(NewOp.getNode());
908
909   if (Replace)
910     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
911   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
912                      DAG.getValueType(OldVT));
913 }
914
915 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
916   EVT OldVT = Op.getValueType();
917   SDLoc dl(Op);
918   bool Replace = false;
919   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
920   if (!NewOp.getNode())
921     return SDValue();
922   AddToWorklist(NewOp.getNode());
923
924   if (Replace)
925     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
926   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
927 }
928
929 /// Promote the specified integer binary operation if the target indicates it is
930 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
931 /// i32 since i16 instructions are longer.
932 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
933   if (!LegalOperations)
934     return SDValue();
935
936   EVT VT = Op.getValueType();
937   if (VT.isVector() || !VT.isInteger())
938     return SDValue();
939
940   // If operation type is 'undesirable', e.g. i16 on x86, consider
941   // promoting it.
942   unsigned Opc = Op.getOpcode();
943   if (TLI.isTypeDesirableForOp(Opc, VT))
944     return SDValue();
945
946   EVT PVT = VT;
947   // Consult target whether it is a good idea to promote this operation and
948   // what's the right type to promote it to.
949   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950     assert(PVT != VT && "Don't know what type to promote to!");
951
952     bool Replace0 = false;
953     SDValue N0 = Op.getOperand(0);
954     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
955     if (!NN0.getNode())
956       return SDValue();
957
958     bool Replace1 = false;
959     SDValue N1 = Op.getOperand(1);
960     SDValue NN1;
961     if (N0 == N1)
962       NN1 = NN0;
963     else {
964       NN1 = PromoteOperand(N1, PVT, Replace1);
965       if (!NN1.getNode())
966         return SDValue();
967     }
968
969     AddToWorklist(NN0.getNode());
970     if (NN1.getNode())
971       AddToWorklist(NN1.getNode());
972
973     if (Replace0)
974       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
975     if (Replace1)
976       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
977
978     DEBUG(dbgs() << "\nPromoting ";
979           Op.getNode()->dump(&DAG));
980     SDLoc dl(Op);
981     return DAG.getNode(ISD::TRUNCATE, dl, VT,
982                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
983   }
984   return SDValue();
985 }
986
987 /// Promote the specified integer shift operation if the target indicates it is
988 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
989 /// i32 since i16 instructions are longer.
990 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
991   if (!LegalOperations)
992     return SDValue();
993
994   EVT VT = Op.getValueType();
995   if (VT.isVector() || !VT.isInteger())
996     return SDValue();
997
998   // If operation type is 'undesirable', e.g. i16 on x86, consider
999   // promoting it.
1000   unsigned Opc = Op.getOpcode();
1001   if (TLI.isTypeDesirableForOp(Opc, VT))
1002     return SDValue();
1003
1004   EVT PVT = VT;
1005   // Consult target whether it is a good idea to promote this operation and
1006   // what's the right type to promote it to.
1007   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1008     assert(PVT != VT && "Don't know what type to promote to!");
1009
1010     bool Replace = false;
1011     SDValue N0 = Op.getOperand(0);
1012     if (Opc == ISD::SRA)
1013       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1014     else if (Opc == ISD::SRL)
1015       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1016     else
1017       N0 = PromoteOperand(N0, PVT, Replace);
1018     if (!N0.getNode())
1019       return SDValue();
1020
1021     AddToWorklist(N0.getNode());
1022     if (Replace)
1023       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1024
1025     DEBUG(dbgs() << "\nPromoting ";
1026           Op.getNode()->dump(&DAG));
1027     SDLoc dl(Op);
1028     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1029                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1030   }
1031   return SDValue();
1032 }
1033
1034 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1035   if (!LegalOperations)
1036     return SDValue();
1037
1038   EVT VT = Op.getValueType();
1039   if (VT.isVector() || !VT.isInteger())
1040     return SDValue();
1041
1042   // If operation type is 'undesirable', e.g. i16 on x86, consider
1043   // promoting it.
1044   unsigned Opc = Op.getOpcode();
1045   if (TLI.isTypeDesirableForOp(Opc, VT))
1046     return SDValue();
1047
1048   EVT PVT = VT;
1049   // Consult target whether it is a good idea to promote this operation and
1050   // what's the right type to promote it to.
1051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1052     assert(PVT != VT && "Don't know what type to promote to!");
1053     // fold (aext (aext x)) -> (aext x)
1054     // fold (aext (zext x)) -> (zext x)
1055     // fold (aext (sext x)) -> (sext x)
1056     DEBUG(dbgs() << "\nPromoting ";
1057           Op.getNode()->dump(&DAG));
1058     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1059   }
1060   return SDValue();
1061 }
1062
1063 bool DAGCombiner::PromoteLoad(SDValue Op) {
1064   if (!LegalOperations)
1065     return false;
1066
1067   EVT VT = Op.getValueType();
1068   if (VT.isVector() || !VT.isInteger())
1069     return false;
1070
1071   // If operation type is 'undesirable', e.g. i16 on x86, consider
1072   // promoting it.
1073   unsigned Opc = Op.getOpcode();
1074   if (TLI.isTypeDesirableForOp(Opc, VT))
1075     return false;
1076
1077   EVT PVT = VT;
1078   // Consult target whether it is a good idea to promote this operation and
1079   // what's the right type to promote it to.
1080   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1081     assert(PVT != VT && "Don't know what type to promote to!");
1082
1083     SDLoc dl(Op);
1084     SDNode *N = Op.getNode();
1085     LoadSDNode *LD = cast<LoadSDNode>(N);
1086     EVT MemVT = LD->getMemoryVT();
1087     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1088       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1089                                                   : ISD::EXTLOAD)
1090       : LD->getExtensionType();
1091     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1092                                    LD->getChain(), LD->getBasePtr(),
1093                                    MemVT, LD->getMemOperand());
1094     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1095
1096     DEBUG(dbgs() << "\nPromoting ";
1097           N->dump(&DAG);
1098           dbgs() << "\nTo: ";
1099           Result.getNode()->dump(&DAG);
1100           dbgs() << '\n');
1101     WorklistRemover DeadNodes(*this);
1102     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1103     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1104     deleteAndRecombine(N);
1105     AddToWorklist(Result.getNode());
1106     return true;
1107   }
1108   return false;
1109 }
1110
1111 /// \brief Recursively delete a node which has no uses and any operands for
1112 /// which it is the only use.
1113 ///
1114 /// Note that this both deletes the nodes and removes them from the worklist.
1115 /// It also adds any nodes who have had a user deleted to the worklist as they
1116 /// may now have only one use and subject to other combines.
1117 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1118   if (!N->use_empty())
1119     return false;
1120
1121   SmallSetVector<SDNode *, 16> Nodes;
1122   Nodes.insert(N);
1123   do {
1124     N = Nodes.pop_back_val();
1125     if (!N)
1126       continue;
1127
1128     if (N->use_empty()) {
1129       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1130         Nodes.insert(N->getOperand(i).getNode());
1131
1132       removeFromWorklist(N);
1133       DAG.DeleteNode(N);
1134     } else {
1135       AddToWorklist(N);
1136     }
1137   } while (!Nodes.empty());
1138   return true;
1139 }
1140
1141 //===----------------------------------------------------------------------===//
1142 //  Main DAG Combiner implementation
1143 //===----------------------------------------------------------------------===//
1144
1145 void DAGCombiner::Run(CombineLevel AtLevel) {
1146   // set the instance variables, so that the various visit routines may use it.
1147   Level = AtLevel;
1148   LegalOperations = Level >= AfterLegalizeVectorOps;
1149   LegalTypes = Level >= AfterLegalizeTypes;
1150
1151   // Add all the dag nodes to the worklist.
1152   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1153        E = DAG.allnodes_end(); I != E; ++I)
1154     AddToWorklist(I);
1155
1156   // Create a dummy node (which is not added to allnodes), that adds a reference
1157   // to the root node, preventing it from being deleted, and tracking any
1158   // changes of the root.
1159   HandleSDNode Dummy(DAG.getRoot());
1160
1161   // while the worklist isn't empty, find a node and
1162   // try and combine it.
1163   while (!WorklistMap.empty()) {
1164     SDNode *N;
1165     // The Worklist holds the SDNodes in order, but it may contain null entries.
1166     do {
1167       N = Worklist.pop_back_val();
1168     } while (!N);
1169
1170     bool GoodWorklistEntry = WorklistMap.erase(N);
1171     (void)GoodWorklistEntry;
1172     assert(GoodWorklistEntry &&
1173            "Found a worklist entry without a corresponding map entry!");
1174
1175     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1176     // N is deleted from the DAG, since they too may now be dead or may have a
1177     // reduced number of uses, allowing other xforms.
1178     if (recursivelyDeleteUnusedNodes(N))
1179       continue;
1180
1181     WorklistRemover DeadNodes(*this);
1182
1183     // If this combine is running after legalizing the DAG, re-legalize any
1184     // nodes pulled off the worklist.
1185     if (Level == AfterLegalizeDAG) {
1186       SmallSetVector<SDNode *, 16> UpdatedNodes;
1187       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1188
1189       for (SDNode *LN : UpdatedNodes) {
1190         AddToWorklist(LN);
1191         AddUsersToWorklist(LN);
1192       }
1193       if (!NIsValid)
1194         continue;
1195     }
1196
1197     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1198
1199     // Add any operands of the new node which have not yet been combined to the
1200     // worklist as well. Because the worklist uniques things already, this
1201     // won't repeatedly process the same operand.
1202     CombinedNodes.insert(N);
1203     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1204       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1205         AddToWorklist(N->getOperand(i).getNode());
1206
1207     SDValue RV = combine(N);
1208
1209     if (!RV.getNode())
1210       continue;
1211
1212     ++NodesCombined;
1213
1214     // If we get back the same node we passed in, rather than a new node or
1215     // zero, we know that the node must have defined multiple values and
1216     // CombineTo was used.  Since CombineTo takes care of the worklist
1217     // mechanics for us, we have no work to do in this case.
1218     if (RV.getNode() == N)
1219       continue;
1220
1221     assert(N->getOpcode() != ISD::DELETED_NODE &&
1222            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1223            "Node was deleted but visit returned new node!");
1224
1225     DEBUG(dbgs() << " ... into: ";
1226           RV.getNode()->dump(&DAG));
1227
1228     // Transfer debug value.
1229     DAG.TransferDbgValues(SDValue(N, 0), RV);
1230     if (N->getNumValues() == RV.getNode()->getNumValues())
1231       DAG.ReplaceAllUsesWith(N, RV.getNode());
1232     else {
1233       assert(N->getValueType(0) == RV.getValueType() &&
1234              N->getNumValues() == 1 && "Type mismatch");
1235       SDValue OpV = RV;
1236       DAG.ReplaceAllUsesWith(N, &OpV);
1237     }
1238
1239     // Push the new node and any users onto the worklist
1240     AddToWorklist(RV.getNode());
1241     AddUsersToWorklist(RV.getNode());
1242
1243     // Finally, if the node is now dead, remove it from the graph.  The node
1244     // may not be dead if the replacement process recursively simplified to
1245     // something else needing this node. This will also take care of adding any
1246     // operands which have lost a user to the worklist.
1247     recursivelyDeleteUnusedNodes(N);
1248   }
1249
1250   // If the root changed (e.g. it was a dead load, update the root).
1251   DAG.setRoot(Dummy.getValue());
1252   DAG.RemoveDeadNodes();
1253 }
1254
1255 SDValue DAGCombiner::visit(SDNode *N) {
1256   switch (N->getOpcode()) {
1257   default: break;
1258   case ISD::TokenFactor:        return visitTokenFactor(N);
1259   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1260   case ISD::ADD:                return visitADD(N);
1261   case ISD::SUB:                return visitSUB(N);
1262   case ISD::ADDC:               return visitADDC(N);
1263   case ISD::SUBC:               return visitSUBC(N);
1264   case ISD::ADDE:               return visitADDE(N);
1265   case ISD::SUBE:               return visitSUBE(N);
1266   case ISD::MUL:                return visitMUL(N);
1267   case ISD::SDIV:               return visitSDIV(N);
1268   case ISD::UDIV:               return visitUDIV(N);
1269   case ISD::SREM:               return visitSREM(N);
1270   case ISD::UREM:               return visitUREM(N);
1271   case ISD::MULHU:              return visitMULHU(N);
1272   case ISD::MULHS:              return visitMULHS(N);
1273   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1274   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1275   case ISD::SMULO:              return visitSMULO(N);
1276   case ISD::UMULO:              return visitUMULO(N);
1277   case ISD::SDIVREM:            return visitSDIVREM(N);
1278   case ISD::UDIVREM:            return visitUDIVREM(N);
1279   case ISD::AND:                return visitAND(N);
1280   case ISD::OR:                 return visitOR(N);
1281   case ISD::XOR:                return visitXOR(N);
1282   case ISD::SHL:                return visitSHL(N);
1283   case ISD::SRA:                return visitSRA(N);
1284   case ISD::SRL:                return visitSRL(N);
1285   case ISD::ROTR:
1286   case ISD::ROTL:               return visitRotate(N);
1287   case ISD::CTLZ:               return visitCTLZ(N);
1288   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1289   case ISD::CTTZ:               return visitCTTZ(N);
1290   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1291   case ISD::CTPOP:              return visitCTPOP(N);
1292   case ISD::SELECT:             return visitSELECT(N);
1293   case ISD::VSELECT:            return visitVSELECT(N);
1294   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1295   case ISD::SETCC:              return visitSETCC(N);
1296   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1297   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1298   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1299   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1300   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1301   case ISD::BITCAST:            return visitBITCAST(N);
1302   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1303   case ISD::FADD:               return visitFADD(N);
1304   case ISD::FSUB:               return visitFSUB(N);
1305   case ISD::FMUL:               return visitFMUL(N);
1306   case ISD::FMA:                return visitFMA(N);
1307   case ISD::FDIV:               return visitFDIV(N);
1308   case ISD::FREM:               return visitFREM(N);
1309   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1310   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1311   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1312   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1313   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1314   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1315   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1316   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1317   case ISD::FNEG:               return visitFNEG(N);
1318   case ISD::FABS:               return visitFABS(N);
1319   case ISD::FFLOOR:             return visitFFLOOR(N);
1320   case ISD::FCEIL:              return visitFCEIL(N);
1321   case ISD::FTRUNC:             return visitFTRUNC(N);
1322   case ISD::BRCOND:             return visitBRCOND(N);
1323   case ISD::BR_CC:              return visitBR_CC(N);
1324   case ISD::LOAD:               return visitLOAD(N);
1325   case ISD::STORE:              return visitSTORE(N);
1326   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1327   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1328   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1329   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1330   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1331   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1332   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1333   }
1334   return SDValue();
1335 }
1336
1337 SDValue DAGCombiner::combine(SDNode *N) {
1338   SDValue RV = visit(N);
1339
1340   // If nothing happened, try a target-specific DAG combine.
1341   if (!RV.getNode()) {
1342     assert(N->getOpcode() != ISD::DELETED_NODE &&
1343            "Node was deleted but visit returned NULL!");
1344
1345     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1346         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1347
1348       // Expose the DAG combiner to the target combiner impls.
1349       TargetLowering::DAGCombinerInfo
1350         DagCombineInfo(DAG, Level, false, this);
1351
1352       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1353     }
1354   }
1355
1356   // If nothing happened still, try promoting the operation.
1357   if (!RV.getNode()) {
1358     switch (N->getOpcode()) {
1359     default: break;
1360     case ISD::ADD:
1361     case ISD::SUB:
1362     case ISD::MUL:
1363     case ISD::AND:
1364     case ISD::OR:
1365     case ISD::XOR:
1366       RV = PromoteIntBinOp(SDValue(N, 0));
1367       break;
1368     case ISD::SHL:
1369     case ISD::SRA:
1370     case ISD::SRL:
1371       RV = PromoteIntShiftOp(SDValue(N, 0));
1372       break;
1373     case ISD::SIGN_EXTEND:
1374     case ISD::ZERO_EXTEND:
1375     case ISD::ANY_EXTEND:
1376       RV = PromoteExtend(SDValue(N, 0));
1377       break;
1378     case ISD::LOAD:
1379       if (PromoteLoad(SDValue(N, 0)))
1380         RV = SDValue(N, 0);
1381       break;
1382     }
1383   }
1384
1385   // If N is a commutative binary node, try commuting it to enable more
1386   // sdisel CSE.
1387   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1388       N->getNumValues() == 1) {
1389     SDValue N0 = N->getOperand(0);
1390     SDValue N1 = N->getOperand(1);
1391
1392     // Constant operands are canonicalized to RHS.
1393     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1394       SDValue Ops[] = {N1, N0};
1395       SDNode *CSENode;
1396       if (const BinaryWithFlagsSDNode *BinNode =
1397               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1398         CSENode = DAG.getNodeIfExists(
1399             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1400             BinNode->hasNoSignedWrap(), BinNode->isExact());
1401       } else {
1402         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1403       }
1404       if (CSENode)
1405         return SDValue(CSENode, 0);
1406     }
1407   }
1408
1409   return RV;
1410 }
1411
1412 /// Given a node, return its input chain if it has one, otherwise return a null
1413 /// sd operand.
1414 static SDValue getInputChainForNode(SDNode *N) {
1415   if (unsigned NumOps = N->getNumOperands()) {
1416     if (N->getOperand(0).getValueType() == MVT::Other)
1417       return N->getOperand(0);
1418     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1419       return N->getOperand(NumOps-1);
1420     for (unsigned i = 1; i < NumOps-1; ++i)
1421       if (N->getOperand(i).getValueType() == MVT::Other)
1422         return N->getOperand(i);
1423   }
1424   return SDValue();
1425 }
1426
1427 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1428   // If N has two operands, where one has an input chain equal to the other,
1429   // the 'other' chain is redundant.
1430   if (N->getNumOperands() == 2) {
1431     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1432       return N->getOperand(0);
1433     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1434       return N->getOperand(1);
1435   }
1436
1437   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1438   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1439   SmallPtrSet<SDNode*, 16> SeenOps;
1440   bool Changed = false;             // If we should replace this token factor.
1441
1442   // Start out with this token factor.
1443   TFs.push_back(N);
1444
1445   // Iterate through token factors.  The TFs grows when new token factors are
1446   // encountered.
1447   for (unsigned i = 0; i < TFs.size(); ++i) {
1448     SDNode *TF = TFs[i];
1449
1450     // Check each of the operands.
1451     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1452       SDValue Op = TF->getOperand(i);
1453
1454       switch (Op.getOpcode()) {
1455       case ISD::EntryToken:
1456         // Entry tokens don't need to be added to the list. They are
1457         // rededundant.
1458         Changed = true;
1459         break;
1460
1461       case ISD::TokenFactor:
1462         if (Op.hasOneUse() &&
1463             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1464           // Queue up for processing.
1465           TFs.push_back(Op.getNode());
1466           // Clean up in case the token factor is removed.
1467           AddToWorklist(Op.getNode());
1468           Changed = true;
1469           break;
1470         }
1471         // Fall thru
1472
1473       default:
1474         // Only add if it isn't already in the list.
1475         if (SeenOps.insert(Op.getNode()))
1476           Ops.push_back(Op);
1477         else
1478           Changed = true;
1479         break;
1480       }
1481     }
1482   }
1483
1484   SDValue Result;
1485
1486   // If we've change things around then replace token factor.
1487   if (Changed) {
1488     if (Ops.empty()) {
1489       // The entry token is the only possible outcome.
1490       Result = DAG.getEntryNode();
1491     } else {
1492       // New and improved token factor.
1493       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1494     }
1495
1496     // Don't add users to work list.
1497     return CombineTo(N, Result, false);
1498   }
1499
1500   return Result;
1501 }
1502
1503 /// MERGE_VALUES can always be eliminated.
1504 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1505   WorklistRemover DeadNodes(*this);
1506   // Replacing results may cause a different MERGE_VALUES to suddenly
1507   // be CSE'd with N, and carry its uses with it. Iterate until no
1508   // uses remain, to ensure that the node can be safely deleted.
1509   // First add the users of this node to the work list so that they
1510   // can be tried again once they have new operands.
1511   AddUsersToWorklist(N);
1512   do {
1513     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1514       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1515   } while (!N->use_empty());
1516   deleteAndRecombine(N);
1517   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1518 }
1519
1520 SDValue DAGCombiner::visitADD(SDNode *N) {
1521   SDValue N0 = N->getOperand(0);
1522   SDValue N1 = N->getOperand(1);
1523   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1524   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1525   EVT VT = N0.getValueType();
1526
1527   // fold vector ops
1528   if (VT.isVector()) {
1529     SDValue FoldedVOp = SimplifyVBinOp(N);
1530     if (FoldedVOp.getNode()) return FoldedVOp;
1531
1532     // fold (add x, 0) -> x, vector edition
1533     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1534       return N0;
1535     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1536       return N1;
1537   }
1538
1539   // fold (add x, undef) -> undef
1540   if (N0.getOpcode() == ISD::UNDEF)
1541     return N0;
1542   if (N1.getOpcode() == ISD::UNDEF)
1543     return N1;
1544   // fold (add c1, c2) -> c1+c2
1545   if (N0C && N1C)
1546     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1547   // canonicalize constant to RHS
1548   if (N0C && !N1C)
1549     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1550   // fold (add x, 0) -> x
1551   if (N1C && N1C->isNullValue())
1552     return N0;
1553   // fold (add Sym, c) -> Sym+c
1554   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1555     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1556         GA->getOpcode() == ISD::GlobalAddress)
1557       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1558                                   GA->getOffset() +
1559                                     (uint64_t)N1C->getSExtValue());
1560   // fold ((c1-A)+c2) -> (c1+c2)-A
1561   if (N1C && N0.getOpcode() == ISD::SUB)
1562     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1563       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1564                          DAG.getConstant(N1C->getAPIntValue()+
1565                                          N0C->getAPIntValue(), VT),
1566                          N0.getOperand(1));
1567   // reassociate add
1568   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1569   if (RADD.getNode())
1570     return RADD;
1571   // fold ((0-A) + B) -> B-A
1572   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1573       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1574     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1575   // fold (A + (0-B)) -> A-B
1576   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1577       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1578     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1579   // fold (A+(B-A)) -> B
1580   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1581     return N1.getOperand(0);
1582   // fold ((B-A)+A) -> B
1583   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1584     return N0.getOperand(0);
1585   // fold (A+(B-(A+C))) to (B-C)
1586   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1587       N0 == N1.getOperand(1).getOperand(0))
1588     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1589                        N1.getOperand(1).getOperand(1));
1590   // fold (A+(B-(C+A))) to (B-C)
1591   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1592       N0 == N1.getOperand(1).getOperand(1))
1593     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1594                        N1.getOperand(1).getOperand(0));
1595   // fold (A+((B-A)+or-C)) to (B+or-C)
1596   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1597       N1.getOperand(0).getOpcode() == ISD::SUB &&
1598       N0 == N1.getOperand(0).getOperand(1))
1599     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1600                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1601
1602   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1603   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1604     SDValue N00 = N0.getOperand(0);
1605     SDValue N01 = N0.getOperand(1);
1606     SDValue N10 = N1.getOperand(0);
1607     SDValue N11 = N1.getOperand(1);
1608
1609     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1610       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1611                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1612                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1613   }
1614
1615   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1616     return SDValue(N, 0);
1617
1618   // fold (a+b) -> (a|b) iff a and b share no bits.
1619   if (VT.isInteger() && !VT.isVector()) {
1620     APInt LHSZero, LHSOne;
1621     APInt RHSZero, RHSOne;
1622     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1623
1624     if (LHSZero.getBoolValue()) {
1625       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1626
1627       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1628       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1629       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1630         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1631           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1632       }
1633     }
1634   }
1635
1636   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1637   if (N1.getOpcode() == ISD::SHL &&
1638       N1.getOperand(0).getOpcode() == ISD::SUB)
1639     if (ConstantSDNode *C =
1640           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1641       if (C->getAPIntValue() == 0)
1642         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1643                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1644                                        N1.getOperand(0).getOperand(1),
1645                                        N1.getOperand(1)));
1646   if (N0.getOpcode() == ISD::SHL &&
1647       N0.getOperand(0).getOpcode() == ISD::SUB)
1648     if (ConstantSDNode *C =
1649           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1650       if (C->getAPIntValue() == 0)
1651         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1652                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1653                                        N0.getOperand(0).getOperand(1),
1654                                        N0.getOperand(1)));
1655
1656   if (N1.getOpcode() == ISD::AND) {
1657     SDValue AndOp0 = N1.getOperand(0);
1658     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1659     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1660     unsigned DestBits = VT.getScalarType().getSizeInBits();
1661
1662     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1663     // and similar xforms where the inner op is either ~0 or 0.
1664     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1665       SDLoc DL(N);
1666       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1667     }
1668   }
1669
1670   // add (sext i1), X -> sub X, (zext i1)
1671   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1672       N0.getOperand(0).getValueType() == MVT::i1 &&
1673       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1674     SDLoc DL(N);
1675     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1676     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1677   }
1678
1679   return SDValue();
1680 }
1681
1682 SDValue DAGCombiner::visitADDC(SDNode *N) {
1683   SDValue N0 = N->getOperand(0);
1684   SDValue N1 = N->getOperand(1);
1685   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1686   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1687   EVT VT = N0.getValueType();
1688
1689   // If the flag result is dead, turn this into an ADD.
1690   if (!N->hasAnyUseOfValue(1))
1691     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1692                      DAG.getNode(ISD::CARRY_FALSE,
1693                                  SDLoc(N), MVT::Glue));
1694
1695   // canonicalize constant to RHS.
1696   if (N0C && !N1C)
1697     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1698
1699   // fold (addc x, 0) -> x + no carry out
1700   if (N1C && N1C->isNullValue())
1701     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1702                                         SDLoc(N), MVT::Glue));
1703
1704   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1705   APInt LHSZero, LHSOne;
1706   APInt RHSZero, RHSOne;
1707   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1708
1709   if (LHSZero.getBoolValue()) {
1710     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1711
1712     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1713     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1714     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1715       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1716                        DAG.getNode(ISD::CARRY_FALSE,
1717                                    SDLoc(N), MVT::Glue));
1718   }
1719
1720   return SDValue();
1721 }
1722
1723 SDValue DAGCombiner::visitADDE(SDNode *N) {
1724   SDValue N0 = N->getOperand(0);
1725   SDValue N1 = N->getOperand(1);
1726   SDValue CarryIn = N->getOperand(2);
1727   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1728   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1729
1730   // canonicalize constant to RHS
1731   if (N0C && !N1C)
1732     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1733                        N1, N0, CarryIn);
1734
1735   // fold (adde x, y, false) -> (addc x, y)
1736   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1737     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1738
1739   return SDValue();
1740 }
1741
1742 // Since it may not be valid to emit a fold to zero for vector initializers
1743 // check if we can before folding.
1744 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1745                              SelectionDAG &DAG,
1746                              bool LegalOperations, bool LegalTypes) {
1747   if (!VT.isVector())
1748     return DAG.getConstant(0, VT);
1749   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1750     return DAG.getConstant(0, VT);
1751   return SDValue();
1752 }
1753
1754 SDValue DAGCombiner::visitSUB(SDNode *N) {
1755   SDValue N0 = N->getOperand(0);
1756   SDValue N1 = N->getOperand(1);
1757   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1758   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1759   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1760     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1761   EVT VT = N0.getValueType();
1762
1763   // fold vector ops
1764   if (VT.isVector()) {
1765     SDValue FoldedVOp = SimplifyVBinOp(N);
1766     if (FoldedVOp.getNode()) return FoldedVOp;
1767
1768     // fold (sub x, 0) -> x, vector edition
1769     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1770       return N0;
1771   }
1772
1773   // fold (sub x, x) -> 0
1774   // FIXME: Refactor this and xor and other similar operations together.
1775   if (N0 == N1)
1776     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1777   // fold (sub c1, c2) -> c1-c2
1778   if (N0C && N1C)
1779     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1780   // fold (sub x, c) -> (add x, -c)
1781   if (N1C)
1782     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1783                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1784   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1785   if (N0C && N0C->isAllOnesValue())
1786     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1787   // fold A-(A-B) -> B
1788   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1789     return N1.getOperand(1);
1790   // fold (A+B)-A -> B
1791   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1792     return N0.getOperand(1);
1793   // fold (A+B)-B -> A
1794   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1795     return N0.getOperand(0);
1796   // fold C2-(A+C1) -> (C2-C1)-A
1797   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1798     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1799                                    VT);
1800     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1801                        N1.getOperand(0));
1802   }
1803   // fold ((A+(B+or-C))-B) -> A+or-C
1804   if (N0.getOpcode() == ISD::ADD &&
1805       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1806        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1807       N0.getOperand(1).getOperand(0) == N1)
1808     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1809                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1810   // fold ((A+(C+B))-B) -> A+C
1811   if (N0.getOpcode() == ISD::ADD &&
1812       N0.getOperand(1).getOpcode() == ISD::ADD &&
1813       N0.getOperand(1).getOperand(1) == N1)
1814     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1815                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1816   // fold ((A-(B-C))-C) -> A-B
1817   if (N0.getOpcode() == ISD::SUB &&
1818       N0.getOperand(1).getOpcode() == ISD::SUB &&
1819       N0.getOperand(1).getOperand(1) == N1)
1820     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1821                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1822
1823   // If either operand of a sub is undef, the result is undef
1824   if (N0.getOpcode() == ISD::UNDEF)
1825     return N0;
1826   if (N1.getOpcode() == ISD::UNDEF)
1827     return N1;
1828
1829   // If the relocation model supports it, consider symbol offsets.
1830   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1831     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1832       // fold (sub Sym, c) -> Sym-c
1833       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1834         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1835                                     GA->getOffset() -
1836                                       (uint64_t)N1C->getSExtValue());
1837       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1838       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1839         if (GA->getGlobal() == GB->getGlobal())
1840           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1841                                  VT);
1842     }
1843
1844   return SDValue();
1845 }
1846
1847 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1848   SDValue N0 = N->getOperand(0);
1849   SDValue N1 = N->getOperand(1);
1850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1852   EVT VT = N0.getValueType();
1853
1854   // If the flag result is dead, turn this into an SUB.
1855   if (!N->hasAnyUseOfValue(1))
1856     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1857                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1858                                  MVT::Glue));
1859
1860   // fold (subc x, x) -> 0 + no borrow
1861   if (N0 == N1)
1862     return CombineTo(N, DAG.getConstant(0, VT),
1863                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1864                                  MVT::Glue));
1865
1866   // fold (subc x, 0) -> x + no borrow
1867   if (N1C && N1C->isNullValue())
1868     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1869                                         MVT::Glue));
1870
1871   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1872   if (N0C && N0C->isAllOnesValue())
1873     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1874                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1875                                  MVT::Glue));
1876
1877   return SDValue();
1878 }
1879
1880 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1881   SDValue N0 = N->getOperand(0);
1882   SDValue N1 = N->getOperand(1);
1883   SDValue CarryIn = N->getOperand(2);
1884
1885   // fold (sube x, y, false) -> (subc x, y)
1886   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1887     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1888
1889   return SDValue();
1890 }
1891
1892 SDValue DAGCombiner::visitMUL(SDNode *N) {
1893   SDValue N0 = N->getOperand(0);
1894   SDValue N1 = N->getOperand(1);
1895   EVT VT = N0.getValueType();
1896
1897   // fold (mul x, undef) -> 0
1898   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1899     return DAG.getConstant(0, VT);
1900
1901   bool N0IsConst = false;
1902   bool N1IsConst = false;
1903   APInt ConstValue0, ConstValue1;
1904   // fold vector ops
1905   if (VT.isVector()) {
1906     SDValue FoldedVOp = SimplifyVBinOp(N);
1907     if (FoldedVOp.getNode()) return FoldedVOp;
1908
1909     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1910     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1911   } else {
1912     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1913     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1914                             : APInt();
1915     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1916     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1917                             : APInt();
1918   }
1919
1920   // fold (mul c1, c2) -> c1*c2
1921   if (N0IsConst && N1IsConst)
1922     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1923
1924   // canonicalize constant to RHS
1925   if (N0IsConst && !N1IsConst)
1926     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1927   // fold (mul x, 0) -> 0
1928   if (N1IsConst && ConstValue1 == 0)
1929     return N1;
1930   // We require a splat of the entire scalar bit width for non-contiguous
1931   // bit patterns.
1932   bool IsFullSplat =
1933     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1934   // fold (mul x, 1) -> x
1935   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1936     return N0;
1937   // fold (mul x, -1) -> 0-x
1938   if (N1IsConst && ConstValue1.isAllOnesValue())
1939     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1940                        DAG.getConstant(0, VT), N0);
1941   // fold (mul x, (1 << c)) -> x << c
1942   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1943     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1944                        DAG.getConstant(ConstValue1.logBase2(),
1945                                        getShiftAmountTy(N0.getValueType())));
1946   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1947   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1948     unsigned Log2Val = (-ConstValue1).logBase2();
1949     // FIXME: If the input is something that is easily negated (e.g. a
1950     // single-use add), we should put the negate there.
1951     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1952                        DAG.getConstant(0, VT),
1953                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1954                             DAG.getConstant(Log2Val,
1955                                       getShiftAmountTy(N0.getValueType()))));
1956   }
1957
1958   APInt Val;
1959   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1960   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1961       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1962                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1963     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1964                              N1, N0.getOperand(1));
1965     AddToWorklist(C3.getNode());
1966     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1967                        N0.getOperand(0), C3);
1968   }
1969
1970   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1971   // use.
1972   {
1973     SDValue Sh(nullptr,0), Y(nullptr,0);
1974     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1975     if (N0.getOpcode() == ISD::SHL &&
1976         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1977                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1978         N0.getNode()->hasOneUse()) {
1979       Sh = N0; Y = N1;
1980     } else if (N1.getOpcode() == ISD::SHL &&
1981                isa<ConstantSDNode>(N1.getOperand(1)) &&
1982                N1.getNode()->hasOneUse()) {
1983       Sh = N1; Y = N0;
1984     }
1985
1986     if (Sh.getNode()) {
1987       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1988                                 Sh.getOperand(0), Y);
1989       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1990                          Mul, Sh.getOperand(1));
1991     }
1992   }
1993
1994   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1995   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1996       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1997                      isa<ConstantSDNode>(N0.getOperand(1))))
1998     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1999                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2000                                    N0.getOperand(0), N1),
2001                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2002                                    N0.getOperand(1), N1));
2003
2004   // reassociate mul
2005   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2006   if (RMUL.getNode())
2007     return RMUL;
2008
2009   return SDValue();
2010 }
2011
2012 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2013   SDValue N0 = N->getOperand(0);
2014   SDValue N1 = N->getOperand(1);
2015   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2016   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2017   EVT VT = N->getValueType(0);
2018
2019   // fold vector ops
2020   if (VT.isVector()) {
2021     SDValue FoldedVOp = SimplifyVBinOp(N);
2022     if (FoldedVOp.getNode()) return FoldedVOp;
2023   }
2024
2025   // fold (sdiv c1, c2) -> c1/c2
2026   if (N0C && N1C && !N1C->isNullValue())
2027     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2028   // fold (sdiv X, 1) -> X
2029   if (N1C && N1C->getAPIntValue() == 1LL)
2030     return N0;
2031   // fold (sdiv X, -1) -> 0-X
2032   if (N1C && N1C->isAllOnesValue())
2033     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2034                        DAG.getConstant(0, VT), N0);
2035   // If we know the sign bits of both operands are zero, strength reduce to a
2036   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2037   if (!VT.isVector()) {
2038     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2039       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2040                          N0, N1);
2041   }
2042
2043   // fold (sdiv X, pow2) -> simple ops after legalize
2044   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2045                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2046     // If dividing by powers of two is cheap, then don't perform the following
2047     // fold.
2048     if (TLI.isPow2SDivCheap())
2049       return SDValue();
2050
2051     // Target-specific implementation of sdiv x, pow2.
2052     SDValue Res = BuildSDIVPow2(N);
2053     if (Res.getNode())
2054       return Res;
2055
2056     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2057
2058     // Splat the sign bit into the register
2059     SDValue SGN =
2060         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2061                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2062                                     getShiftAmountTy(N0.getValueType())));
2063     AddToWorklist(SGN.getNode());
2064
2065     // Add (N0 < 0) ? abs2 - 1 : 0;
2066     SDValue SRL =
2067         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2068                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2069                                     getShiftAmountTy(SGN.getValueType())));
2070     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2071     AddToWorklist(SRL.getNode());
2072     AddToWorklist(ADD.getNode());    // Divide by pow2
2073     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2074                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2075
2076     // If we're dividing by a positive value, we're done.  Otherwise, we must
2077     // negate the result.
2078     if (N1C->getAPIntValue().isNonNegative())
2079       return SRA;
2080
2081     AddToWorklist(SRA.getNode());
2082     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2083   }
2084
2085   // if integer divide is expensive and we satisfy the requirements, emit an
2086   // alternate sequence.
2087   if (N1C && !TLI.isIntDivCheap()) {
2088     SDValue Op = BuildSDIV(N);
2089     if (Op.getNode()) return Op;
2090   }
2091
2092   // undef / X -> 0
2093   if (N0.getOpcode() == ISD::UNDEF)
2094     return DAG.getConstant(0, VT);
2095   // X / undef -> undef
2096   if (N1.getOpcode() == ISD::UNDEF)
2097     return N1;
2098
2099   return SDValue();
2100 }
2101
2102 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2103   SDValue N0 = N->getOperand(0);
2104   SDValue N1 = N->getOperand(1);
2105   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2106   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2107   EVT VT = N->getValueType(0);
2108
2109   // fold vector ops
2110   if (VT.isVector()) {
2111     SDValue FoldedVOp = SimplifyVBinOp(N);
2112     if (FoldedVOp.getNode()) return FoldedVOp;
2113   }
2114
2115   // fold (udiv c1, c2) -> c1/c2
2116   if (N0C && N1C && !N1C->isNullValue())
2117     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2118   // fold (udiv x, (1 << c)) -> x >>u c
2119   if (N1C && N1C->getAPIntValue().isPowerOf2())
2120     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2121                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2122                                        getShiftAmountTy(N0.getValueType())));
2123   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2124   if (N1.getOpcode() == ISD::SHL) {
2125     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2126       if (SHC->getAPIntValue().isPowerOf2()) {
2127         EVT ADDVT = N1.getOperand(1).getValueType();
2128         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2129                                   N1.getOperand(1),
2130                                   DAG.getConstant(SHC->getAPIntValue()
2131                                                                   .logBase2(),
2132                                                   ADDVT));
2133         AddToWorklist(Add.getNode());
2134         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2135       }
2136     }
2137   }
2138   // fold (udiv x, c) -> alternate
2139   if (N1C && !TLI.isIntDivCheap()) {
2140     SDValue Op = BuildUDIV(N);
2141     if (Op.getNode()) return Op;
2142   }
2143
2144   // undef / X -> 0
2145   if (N0.getOpcode() == ISD::UNDEF)
2146     return DAG.getConstant(0, VT);
2147   // X / undef -> undef
2148   if (N1.getOpcode() == ISD::UNDEF)
2149     return N1;
2150
2151   return SDValue();
2152 }
2153
2154 SDValue DAGCombiner::visitSREM(SDNode *N) {
2155   SDValue N0 = N->getOperand(0);
2156   SDValue N1 = N->getOperand(1);
2157   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2158   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2159   EVT VT = N->getValueType(0);
2160
2161   // fold (srem c1, c2) -> c1%c2
2162   if (N0C && N1C && !N1C->isNullValue())
2163     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2164   // If we know the sign bits of both operands are zero, strength reduce to a
2165   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2166   if (!VT.isVector()) {
2167     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2168       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2169   }
2170
2171   // If X/C can be simplified by the division-by-constant logic, lower
2172   // X%C to the equivalent of X-X/C*C.
2173   if (N1C && !N1C->isNullValue()) {
2174     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2175     AddToWorklist(Div.getNode());
2176     SDValue OptimizedDiv = combine(Div.getNode());
2177     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2178       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2179                                 OptimizedDiv, N1);
2180       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2181       AddToWorklist(Mul.getNode());
2182       return Sub;
2183     }
2184   }
2185
2186   // undef % X -> 0
2187   if (N0.getOpcode() == ISD::UNDEF)
2188     return DAG.getConstant(0, VT);
2189   // X % undef -> undef
2190   if (N1.getOpcode() == ISD::UNDEF)
2191     return N1;
2192
2193   return SDValue();
2194 }
2195
2196 SDValue DAGCombiner::visitUREM(SDNode *N) {
2197   SDValue N0 = N->getOperand(0);
2198   SDValue N1 = N->getOperand(1);
2199   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2200   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2201   EVT VT = N->getValueType(0);
2202
2203   // fold (urem c1, c2) -> c1%c2
2204   if (N0C && N1C && !N1C->isNullValue())
2205     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2206   // fold (urem x, pow2) -> (and x, pow2-1)
2207   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2208     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2209                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2210   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2211   if (N1.getOpcode() == ISD::SHL) {
2212     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2213       if (SHC->getAPIntValue().isPowerOf2()) {
2214         SDValue Add =
2215           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2216                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2217                                  VT));
2218         AddToWorklist(Add.getNode());
2219         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2220       }
2221     }
2222   }
2223
2224   // If X/C can be simplified by the division-by-constant logic, lower
2225   // X%C to the equivalent of X-X/C*C.
2226   if (N1C && !N1C->isNullValue()) {
2227     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2228     AddToWorklist(Div.getNode());
2229     SDValue OptimizedDiv = combine(Div.getNode());
2230     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2231       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2232                                 OptimizedDiv, N1);
2233       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2234       AddToWorklist(Mul.getNode());
2235       return Sub;
2236     }
2237   }
2238
2239   // undef % X -> 0
2240   if (N0.getOpcode() == ISD::UNDEF)
2241     return DAG.getConstant(0, VT);
2242   // X % undef -> undef
2243   if (N1.getOpcode() == ISD::UNDEF)
2244     return N1;
2245
2246   return SDValue();
2247 }
2248
2249 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2250   SDValue N0 = N->getOperand(0);
2251   SDValue N1 = N->getOperand(1);
2252   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2253   EVT VT = N->getValueType(0);
2254   SDLoc DL(N);
2255
2256   // fold (mulhs x, 0) -> 0
2257   if (N1C && N1C->isNullValue())
2258     return N1;
2259   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2260   if (N1C && N1C->getAPIntValue() == 1)
2261     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2262                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2263                                        getShiftAmountTy(N0.getValueType())));
2264   // fold (mulhs x, undef) -> 0
2265   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2266     return DAG.getConstant(0, VT);
2267
2268   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2269   // plus a shift.
2270   if (VT.isSimple() && !VT.isVector()) {
2271     MVT Simple = VT.getSimpleVT();
2272     unsigned SimpleSize = Simple.getSizeInBits();
2273     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2274     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2275       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2276       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2277       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2278       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2279             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2280       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2281     }
2282   }
2283
2284   return SDValue();
2285 }
2286
2287 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2288   SDValue N0 = N->getOperand(0);
2289   SDValue N1 = N->getOperand(1);
2290   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2291   EVT VT = N->getValueType(0);
2292   SDLoc DL(N);
2293
2294   // fold (mulhu x, 0) -> 0
2295   if (N1C && N1C->isNullValue())
2296     return N1;
2297   // fold (mulhu x, 1) -> 0
2298   if (N1C && N1C->getAPIntValue() == 1)
2299     return DAG.getConstant(0, N0.getValueType());
2300   // fold (mulhu x, undef) -> 0
2301   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2302     return DAG.getConstant(0, VT);
2303
2304   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2305   // plus a shift.
2306   if (VT.isSimple() && !VT.isVector()) {
2307     MVT Simple = VT.getSimpleVT();
2308     unsigned SimpleSize = Simple.getSizeInBits();
2309     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2310     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2311       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2312       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2313       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2314       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2315             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2316       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2317     }
2318   }
2319
2320   return SDValue();
2321 }
2322
2323 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2324 /// give the opcodes for the two computations that are being performed. Return
2325 /// true if a simplification was made.
2326 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2327                                                 unsigned HiOp) {
2328   // If the high half is not needed, just compute the low half.
2329   bool HiExists = N->hasAnyUseOfValue(1);
2330   if (!HiExists &&
2331       (!LegalOperations ||
2332        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2333     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2334     return CombineTo(N, Res, Res);
2335   }
2336
2337   // If the low half is not needed, just compute the high half.
2338   bool LoExists = N->hasAnyUseOfValue(0);
2339   if (!LoExists &&
2340       (!LegalOperations ||
2341        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2342     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2343     return CombineTo(N, Res, Res);
2344   }
2345
2346   // If both halves are used, return as it is.
2347   if (LoExists && HiExists)
2348     return SDValue();
2349
2350   // If the two computed results can be simplified separately, separate them.
2351   if (LoExists) {
2352     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2353     AddToWorklist(Lo.getNode());
2354     SDValue LoOpt = combine(Lo.getNode());
2355     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2356         (!LegalOperations ||
2357          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2358       return CombineTo(N, LoOpt, LoOpt);
2359   }
2360
2361   if (HiExists) {
2362     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2363     AddToWorklist(Hi.getNode());
2364     SDValue HiOpt = combine(Hi.getNode());
2365     if (HiOpt.getNode() && HiOpt != Hi &&
2366         (!LegalOperations ||
2367          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2368       return CombineTo(N, HiOpt, HiOpt);
2369   }
2370
2371   return SDValue();
2372 }
2373
2374 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2375   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2376   if (Res.getNode()) return Res;
2377
2378   EVT VT = N->getValueType(0);
2379   SDLoc DL(N);
2380
2381   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2382   // plus a shift.
2383   if (VT.isSimple() && !VT.isVector()) {
2384     MVT Simple = VT.getSimpleVT();
2385     unsigned SimpleSize = Simple.getSizeInBits();
2386     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2387     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2388       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2389       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2390       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2391       // Compute the high part as N1.
2392       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2393             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2394       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2395       // Compute the low part as N0.
2396       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2397       return CombineTo(N, Lo, Hi);
2398     }
2399   }
2400
2401   return SDValue();
2402 }
2403
2404 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2405   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2406   if (Res.getNode()) return Res;
2407
2408   EVT VT = N->getValueType(0);
2409   SDLoc DL(N);
2410
2411   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2412   // plus a shift.
2413   if (VT.isSimple() && !VT.isVector()) {
2414     MVT Simple = VT.getSimpleVT();
2415     unsigned SimpleSize = Simple.getSizeInBits();
2416     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2417     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2418       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2419       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2420       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2421       // Compute the high part as N1.
2422       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2423             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2424       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2425       // Compute the low part as N0.
2426       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2427       return CombineTo(N, Lo, Hi);
2428     }
2429   }
2430
2431   return SDValue();
2432 }
2433
2434 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2435   // (smulo x, 2) -> (saddo x, x)
2436   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2437     if (C2->getAPIntValue() == 2)
2438       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2439                          N->getOperand(0), N->getOperand(0));
2440
2441   return SDValue();
2442 }
2443
2444 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2445   // (umulo x, 2) -> (uaddo x, x)
2446   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2447     if (C2->getAPIntValue() == 2)
2448       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2449                          N->getOperand(0), N->getOperand(0));
2450
2451   return SDValue();
2452 }
2453
2454 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2455   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2456   if (Res.getNode()) return Res;
2457
2458   return SDValue();
2459 }
2460
2461 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2462   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2463   if (Res.getNode()) return Res;
2464
2465   return SDValue();
2466 }
2467
2468 /// If this is a binary operator with two operands of the same opcode, try to
2469 /// simplify it.
2470 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2471   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2472   EVT VT = N0.getValueType();
2473   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2474
2475   // Bail early if none of these transforms apply.
2476   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2477
2478   // For each of OP in AND/OR/XOR:
2479   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2480   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2481   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2482   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2483   //
2484   // do not sink logical op inside of a vector extend, since it may combine
2485   // into a vsetcc.
2486   EVT Op0VT = N0.getOperand(0).getValueType();
2487   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2488        N0.getOpcode() == ISD::SIGN_EXTEND ||
2489        // Avoid infinite looping with PromoteIntBinOp.
2490        (N0.getOpcode() == ISD::ANY_EXTEND &&
2491         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2492        (N0.getOpcode() == ISD::TRUNCATE &&
2493         (!TLI.isZExtFree(VT, Op0VT) ||
2494          !TLI.isTruncateFree(Op0VT, VT)) &&
2495         TLI.isTypeLegal(Op0VT))) &&
2496       !VT.isVector() &&
2497       Op0VT == N1.getOperand(0).getValueType() &&
2498       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2499     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2500                                  N0.getOperand(0).getValueType(),
2501                                  N0.getOperand(0), N1.getOperand(0));
2502     AddToWorklist(ORNode.getNode());
2503     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2504   }
2505
2506   // For each of OP in SHL/SRL/SRA/AND...
2507   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2508   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2509   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2510   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2511        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2512       N0.getOperand(1) == N1.getOperand(1)) {
2513     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2514                                  N0.getOperand(0).getValueType(),
2515                                  N0.getOperand(0), N1.getOperand(0));
2516     AddToWorklist(ORNode.getNode());
2517     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2518                        ORNode, N0.getOperand(1));
2519   }
2520
2521   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2522   // Only perform this optimization after type legalization and before
2523   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2524   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2525   // we don't want to undo this promotion.
2526   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2527   // on scalars.
2528   if ((N0.getOpcode() == ISD::BITCAST ||
2529        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2530       Level == AfterLegalizeTypes) {
2531     SDValue In0 = N0.getOperand(0);
2532     SDValue In1 = N1.getOperand(0);
2533     EVT In0Ty = In0.getValueType();
2534     EVT In1Ty = In1.getValueType();
2535     SDLoc DL(N);
2536     // If both incoming values are integers, and the original types are the
2537     // same.
2538     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2539       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2540       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2541       AddToWorklist(Op.getNode());
2542       return BC;
2543     }
2544   }
2545
2546   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2547   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2548   // If both shuffles use the same mask, and both shuffle within a single
2549   // vector, then it is worthwhile to move the swizzle after the operation.
2550   // The type-legalizer generates this pattern when loading illegal
2551   // vector types from memory. In many cases this allows additional shuffle
2552   // optimizations.
2553   // There are other cases where moving the shuffle after the xor/and/or
2554   // is profitable even if shuffles don't perform a swizzle.
2555   // If both shuffles use the same mask, and both shuffles have the same first
2556   // or second operand, then it might still be profitable to move the shuffle
2557   // after the xor/and/or operation.
2558   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2559     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2560     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2561
2562     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2563            "Inputs to shuffles are not the same type");
2564
2565     // Check that both shuffles use the same mask. The masks are known to be of
2566     // the same length because the result vector type is the same.
2567     // Check also that shuffles have only one use to avoid introducing extra
2568     // instructions.
2569     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2570         SVN0->getMask().equals(SVN1->getMask())) {
2571       SDValue ShOp = N0->getOperand(1);
2572
2573       // Don't try to fold this node if it requires introducing a
2574       // build vector of all zeros that might be illegal at this stage.
2575       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2576         if (!LegalTypes)
2577           ShOp = DAG.getConstant(0, VT);
2578         else
2579           ShOp = SDValue();
2580       }
2581
2582       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2583       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2584       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2585       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2586         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2587                                       N0->getOperand(0), N1->getOperand(0));
2588         AddToWorklist(NewNode.getNode());
2589         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2590                                     &SVN0->getMask()[0]);
2591       }
2592
2593       // Don't try to fold this node if it requires introducing a
2594       // build vector of all zeros that might be illegal at this stage.
2595       ShOp = N0->getOperand(0);
2596       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2597         if (!LegalTypes)
2598           ShOp = DAG.getConstant(0, VT);
2599         else
2600           ShOp = SDValue();
2601       }
2602
2603       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2604       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2605       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2606       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2607         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2608                                       N0->getOperand(1), N1->getOperand(1));
2609         AddToWorklist(NewNode.getNode());
2610         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2611                                     &SVN0->getMask()[0]);
2612       }
2613     }
2614   }
2615
2616   return SDValue();
2617 }
2618
2619 SDValue DAGCombiner::visitAND(SDNode *N) {
2620   SDValue N0 = N->getOperand(0);
2621   SDValue N1 = N->getOperand(1);
2622   SDValue LL, LR, RL, RR, CC0, CC1;
2623   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2624   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2625   EVT VT = N1.getValueType();
2626   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2627
2628   // fold vector ops
2629   if (VT.isVector()) {
2630     SDValue FoldedVOp = SimplifyVBinOp(N);
2631     if (FoldedVOp.getNode()) return FoldedVOp;
2632
2633     // fold (and x, 0) -> 0, vector edition
2634     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2635       // do not return N0, because undef node may exist in N0
2636       return DAG.getConstant(
2637           APInt::getNullValue(
2638               N0.getValueType().getScalarType().getSizeInBits()),
2639           N0.getValueType());
2640     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2641       // do not return N1, because undef node may exist in N1
2642       return DAG.getConstant(
2643           APInt::getNullValue(
2644               N1.getValueType().getScalarType().getSizeInBits()),
2645           N1.getValueType());
2646
2647     // fold (and x, -1) -> x, vector edition
2648     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2649       return N1;
2650     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2651       return N0;
2652   }
2653
2654   // fold (and x, undef) -> 0
2655   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2656     return DAG.getConstant(0, VT);
2657   // fold (and c1, c2) -> c1&c2
2658   if (N0C && N1C)
2659     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2660   // canonicalize constant to RHS
2661   if (N0C && !N1C)
2662     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2663   // fold (and x, -1) -> x
2664   if (N1C && N1C->isAllOnesValue())
2665     return N0;
2666   // if (and x, c) is known to be zero, return 0
2667   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2668                                    APInt::getAllOnesValue(BitWidth)))
2669     return DAG.getConstant(0, VT);
2670   // reassociate and
2671   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2672   if (RAND.getNode())
2673     return RAND;
2674   // fold (and (or x, C), D) -> D if (C & D) == D
2675   if (N1C && N0.getOpcode() == ISD::OR)
2676     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2677       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2678         return N1;
2679   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2680   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2681     SDValue N0Op0 = N0.getOperand(0);
2682     APInt Mask = ~N1C->getAPIntValue();
2683     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2684     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2685       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2686                                  N0.getValueType(), N0Op0);
2687
2688       // Replace uses of the AND with uses of the Zero extend node.
2689       CombineTo(N, Zext);
2690
2691       // We actually want to replace all uses of the any_extend with the
2692       // zero_extend, to avoid duplicating things.  This will later cause this
2693       // AND to be folded.
2694       CombineTo(N0.getNode(), Zext);
2695       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2696     }
2697   }
2698   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2699   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2700   // already be zero by virtue of the width of the base type of the load.
2701   //
2702   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2703   // more cases.
2704   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2705        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2706       N0.getOpcode() == ISD::LOAD) {
2707     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2708                                          N0 : N0.getOperand(0) );
2709
2710     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2711     // This can be a pure constant or a vector splat, in which case we treat the
2712     // vector as a scalar and use the splat value.
2713     APInt Constant = APInt::getNullValue(1);
2714     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2715       Constant = C->getAPIntValue();
2716     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2717       APInt SplatValue, SplatUndef;
2718       unsigned SplatBitSize;
2719       bool HasAnyUndefs;
2720       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2721                                              SplatBitSize, HasAnyUndefs);
2722       if (IsSplat) {
2723         // Undef bits can contribute to a possible optimisation if set, so
2724         // set them.
2725         SplatValue |= SplatUndef;
2726
2727         // The splat value may be something like "0x00FFFFFF", which means 0 for
2728         // the first vector value and FF for the rest, repeating. We need a mask
2729         // that will apply equally to all members of the vector, so AND all the
2730         // lanes of the constant together.
2731         EVT VT = Vector->getValueType(0);
2732         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2733
2734         // If the splat value has been compressed to a bitlength lower
2735         // than the size of the vector lane, we need to re-expand it to
2736         // the lane size.
2737         if (BitWidth > SplatBitSize)
2738           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2739                SplatBitSize < BitWidth;
2740                SplatBitSize = SplatBitSize * 2)
2741             SplatValue |= SplatValue.shl(SplatBitSize);
2742
2743         Constant = APInt::getAllOnesValue(BitWidth);
2744         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2745           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2746       }
2747     }
2748
2749     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2750     // actually legal and isn't going to get expanded, else this is a false
2751     // optimisation.
2752     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2753                                                     Load->getMemoryVT());
2754
2755     // Resize the constant to the same size as the original memory access before
2756     // extension. If it is still the AllOnesValue then this AND is completely
2757     // unneeded.
2758     Constant =
2759       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2760
2761     bool B;
2762     switch (Load->getExtensionType()) {
2763     default: B = false; break;
2764     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2765     case ISD::ZEXTLOAD:
2766     case ISD::NON_EXTLOAD: B = true; break;
2767     }
2768
2769     if (B && Constant.isAllOnesValue()) {
2770       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2771       // preserve semantics once we get rid of the AND.
2772       SDValue NewLoad(Load, 0);
2773       if (Load->getExtensionType() == ISD::EXTLOAD) {
2774         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2775                               Load->getValueType(0), SDLoc(Load),
2776                               Load->getChain(), Load->getBasePtr(),
2777                               Load->getOffset(), Load->getMemoryVT(),
2778                               Load->getMemOperand());
2779         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2780         if (Load->getNumValues() == 3) {
2781           // PRE/POST_INC loads have 3 values.
2782           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2783                            NewLoad.getValue(2) };
2784           CombineTo(Load, To, 3, true);
2785         } else {
2786           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2787         }
2788       }
2789
2790       // Fold the AND away, taking care not to fold to the old load node if we
2791       // replaced it.
2792       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2793
2794       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2795     }
2796   }
2797   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2798   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2799     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2800     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2801
2802     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2803         LL.getValueType().isInteger()) {
2804       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2805       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2806         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2807                                      LR.getValueType(), LL, RL);
2808         AddToWorklist(ORNode.getNode());
2809         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2810       }
2811       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2812       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2813         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2814                                       LR.getValueType(), LL, RL);
2815         AddToWorklist(ANDNode.getNode());
2816         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2817       }
2818       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2819       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2820         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2821                                      LR.getValueType(), LL, RL);
2822         AddToWorklist(ORNode.getNode());
2823         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2824       }
2825     }
2826     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2827     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2828         Op0 == Op1 && LL.getValueType().isInteger() &&
2829       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2830                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2831                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2832                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2833       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2834                                     LL, DAG.getConstant(1, LL.getValueType()));
2835       AddToWorklist(ADDNode.getNode());
2836       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2837                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2838     }
2839     // canonicalize equivalent to ll == rl
2840     if (LL == RR && LR == RL) {
2841       Op1 = ISD::getSetCCSwappedOperands(Op1);
2842       std::swap(RL, RR);
2843     }
2844     if (LL == RL && LR == RR) {
2845       bool isInteger = LL.getValueType().isInteger();
2846       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2847       if (Result != ISD::SETCC_INVALID &&
2848           (!LegalOperations ||
2849            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2850             TLI.isOperationLegal(ISD::SETCC,
2851                             getSetCCResultType(N0.getSimpleValueType())))))
2852         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2853                             LL, LR, Result);
2854     }
2855   }
2856
2857   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2858   if (N0.getOpcode() == N1.getOpcode()) {
2859     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2860     if (Tmp.getNode()) return Tmp;
2861   }
2862
2863   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2864   // fold (and (sra)) -> (and (srl)) when possible.
2865   if (!VT.isVector() &&
2866       SimplifyDemandedBits(SDValue(N, 0)))
2867     return SDValue(N, 0);
2868
2869   // fold (zext_inreg (extload x)) -> (zextload x)
2870   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2871     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2872     EVT MemVT = LN0->getMemoryVT();
2873     // If we zero all the possible extended bits, then we can turn this into
2874     // a zextload if we are running before legalize or the operation is legal.
2875     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2876     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2877                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2878         ((!LegalOperations && !LN0->isVolatile()) ||
2879          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2880       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2881                                        LN0->getChain(), LN0->getBasePtr(),
2882                                        MemVT, LN0->getMemOperand());
2883       AddToWorklist(N);
2884       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2885       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2886     }
2887   }
2888   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2889   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2890       N0.hasOneUse()) {
2891     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2892     EVT MemVT = LN0->getMemoryVT();
2893     // If we zero all the possible extended bits, then we can turn this into
2894     // a zextload if we are running before legalize or the operation is legal.
2895     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2896     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2897                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2898         ((!LegalOperations && !LN0->isVolatile()) ||
2899          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2900       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2901                                        LN0->getChain(), LN0->getBasePtr(),
2902                                        MemVT, LN0->getMemOperand());
2903       AddToWorklist(N);
2904       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2905       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2906     }
2907   }
2908
2909   // fold (and (load x), 255) -> (zextload x, i8)
2910   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2911   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2912   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2913               (N0.getOpcode() == ISD::ANY_EXTEND &&
2914                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2915     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2916     LoadSDNode *LN0 = HasAnyExt
2917       ? cast<LoadSDNode>(N0.getOperand(0))
2918       : cast<LoadSDNode>(N0);
2919     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2920         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2921       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2922       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2923         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2924         EVT LoadedVT = LN0->getMemoryVT();
2925
2926         if (ExtVT == LoadedVT &&
2927             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2928           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2929
2930           SDValue NewLoad =
2931             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2932                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2933                            LN0->getMemOperand());
2934           AddToWorklist(N);
2935           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2936           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2937         }
2938
2939         // Do not change the width of a volatile load.
2940         // Do not generate loads of non-round integer types since these can
2941         // be expensive (and would be wrong if the type is not byte sized).
2942         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2943             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2944           EVT PtrType = LN0->getOperand(1).getValueType();
2945
2946           unsigned Alignment = LN0->getAlignment();
2947           SDValue NewPtr = LN0->getBasePtr();
2948
2949           // For big endian targets, we need to add an offset to the pointer
2950           // to load the correct bytes.  For little endian systems, we merely
2951           // need to read fewer bytes from the same pointer.
2952           if (TLI.isBigEndian()) {
2953             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2954             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2955             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2956             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2957                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2958             Alignment = MinAlign(Alignment, PtrOff);
2959           }
2960
2961           AddToWorklist(NewPtr.getNode());
2962
2963           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2964           SDValue Load =
2965             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2966                            LN0->getChain(), NewPtr,
2967                            LN0->getPointerInfo(),
2968                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2969                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2970           AddToWorklist(N);
2971           CombineTo(LN0, Load, Load.getValue(1));
2972           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2973         }
2974       }
2975     }
2976   }
2977
2978   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2979       VT.getSizeInBits() <= 64) {
2980     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2981       APInt ADDC = ADDI->getAPIntValue();
2982       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2983         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2984         // immediate for an add, but it is legal if its top c2 bits are set,
2985         // transform the ADD so the immediate doesn't need to be materialized
2986         // in a register.
2987         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2988           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2989                                              SRLI->getZExtValue());
2990           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2991             ADDC |= Mask;
2992             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2993               SDValue NewAdd =
2994                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2995                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2996               CombineTo(N0.getNode(), NewAdd);
2997               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2998             }
2999           }
3000         }
3001       }
3002     }
3003   }
3004
3005   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3006   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3007     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3008                                        N0.getOperand(1), false);
3009     if (BSwap.getNode())
3010       return BSwap;
3011   }
3012
3013   return SDValue();
3014 }
3015
3016 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3017 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3018                                         bool DemandHighBits) {
3019   if (!LegalOperations)
3020     return SDValue();
3021
3022   EVT VT = N->getValueType(0);
3023   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3024     return SDValue();
3025   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3026     return SDValue();
3027
3028   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3029   bool LookPassAnd0 = false;
3030   bool LookPassAnd1 = false;
3031   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3032       std::swap(N0, N1);
3033   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3034       std::swap(N0, N1);
3035   if (N0.getOpcode() == ISD::AND) {
3036     if (!N0.getNode()->hasOneUse())
3037       return SDValue();
3038     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3039     if (!N01C || N01C->getZExtValue() != 0xFF00)
3040       return SDValue();
3041     N0 = N0.getOperand(0);
3042     LookPassAnd0 = true;
3043   }
3044
3045   if (N1.getOpcode() == ISD::AND) {
3046     if (!N1.getNode()->hasOneUse())
3047       return SDValue();
3048     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3049     if (!N11C || N11C->getZExtValue() != 0xFF)
3050       return SDValue();
3051     N1 = N1.getOperand(0);
3052     LookPassAnd1 = true;
3053   }
3054
3055   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3056     std::swap(N0, N1);
3057   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3058     return SDValue();
3059   if (!N0.getNode()->hasOneUse() ||
3060       !N1.getNode()->hasOneUse())
3061     return SDValue();
3062
3063   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3064   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3065   if (!N01C || !N11C)
3066     return SDValue();
3067   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3068     return SDValue();
3069
3070   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3071   SDValue N00 = N0->getOperand(0);
3072   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3073     if (!N00.getNode()->hasOneUse())
3074       return SDValue();
3075     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3076     if (!N001C || N001C->getZExtValue() != 0xFF)
3077       return SDValue();
3078     N00 = N00.getOperand(0);
3079     LookPassAnd0 = true;
3080   }
3081
3082   SDValue N10 = N1->getOperand(0);
3083   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3084     if (!N10.getNode()->hasOneUse())
3085       return SDValue();
3086     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3087     if (!N101C || N101C->getZExtValue() != 0xFF00)
3088       return SDValue();
3089     N10 = N10.getOperand(0);
3090     LookPassAnd1 = true;
3091   }
3092
3093   if (N00 != N10)
3094     return SDValue();
3095
3096   // Make sure everything beyond the low halfword gets set to zero since the SRL
3097   // 16 will clear the top bits.
3098   unsigned OpSizeInBits = VT.getSizeInBits();
3099   if (DemandHighBits && OpSizeInBits > 16) {
3100     // If the left-shift isn't masked out then the only way this is a bswap is
3101     // if all bits beyond the low 8 are 0. In that case the entire pattern
3102     // reduces to a left shift anyway: leave it for other parts of the combiner.
3103     if (!LookPassAnd0)
3104       return SDValue();
3105
3106     // However, if the right shift isn't masked out then it might be because
3107     // it's not needed. See if we can spot that too.
3108     if (!LookPassAnd1 &&
3109         !DAG.MaskedValueIsZero(
3110             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3111       return SDValue();
3112   }
3113
3114   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3115   if (OpSizeInBits > 16)
3116     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3117                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3118   return Res;
3119 }
3120
3121 /// Return true if the specified node is an element that makes up a 32-bit
3122 /// packed halfword byteswap.
3123 /// ((x & 0x000000ff) << 8) |
3124 /// ((x & 0x0000ff00) >> 8) |
3125 /// ((x & 0x00ff0000) << 8) |
3126 /// ((x & 0xff000000) >> 8)
3127 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3128   if (!N.getNode()->hasOneUse())
3129     return false;
3130
3131   unsigned Opc = N.getOpcode();
3132   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3133     return false;
3134
3135   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3136   if (!N1C)
3137     return false;
3138
3139   unsigned Num;
3140   switch (N1C->getZExtValue()) {
3141   default:
3142     return false;
3143   case 0xFF:       Num = 0; break;
3144   case 0xFF00:     Num = 1; break;
3145   case 0xFF0000:   Num = 2; break;
3146   case 0xFF000000: Num = 3; break;
3147   }
3148
3149   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3150   SDValue N0 = N.getOperand(0);
3151   if (Opc == ISD::AND) {
3152     if (Num == 0 || Num == 2) {
3153       // (x >> 8) & 0xff
3154       // (x >> 8) & 0xff0000
3155       if (N0.getOpcode() != ISD::SRL)
3156         return false;
3157       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3158       if (!C || C->getZExtValue() != 8)
3159         return false;
3160     } else {
3161       // (x << 8) & 0xff00
3162       // (x << 8) & 0xff000000
3163       if (N0.getOpcode() != ISD::SHL)
3164         return false;
3165       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3166       if (!C || C->getZExtValue() != 8)
3167         return false;
3168     }
3169   } else if (Opc == ISD::SHL) {
3170     // (x & 0xff) << 8
3171     // (x & 0xff0000) << 8
3172     if (Num != 0 && Num != 2)
3173       return false;
3174     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3175     if (!C || C->getZExtValue() != 8)
3176       return false;
3177   } else { // Opc == ISD::SRL
3178     // (x & 0xff00) >> 8
3179     // (x & 0xff000000) >> 8
3180     if (Num != 1 && Num != 3)
3181       return false;
3182     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3183     if (!C || C->getZExtValue() != 8)
3184       return false;
3185   }
3186
3187   if (Parts[Num])
3188     return false;
3189
3190   Parts[Num] = N0.getOperand(0).getNode();
3191   return true;
3192 }
3193
3194 /// Match a 32-bit packed halfword bswap. That is
3195 /// ((x & 0x000000ff) << 8) |
3196 /// ((x & 0x0000ff00) >> 8) |
3197 /// ((x & 0x00ff0000) << 8) |
3198 /// ((x & 0xff000000) >> 8)
3199 /// => (rotl (bswap x), 16)
3200 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3201   if (!LegalOperations)
3202     return SDValue();
3203
3204   EVT VT = N->getValueType(0);
3205   if (VT != MVT::i32)
3206     return SDValue();
3207   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3208     return SDValue();
3209
3210   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3211   // Look for either
3212   // (or (or (and), (and)), (or (and), (and)))
3213   // (or (or (or (and), (and)), (and)), (and))
3214   if (N0.getOpcode() != ISD::OR)
3215     return SDValue();
3216   SDValue N00 = N0.getOperand(0);
3217   SDValue N01 = N0.getOperand(1);
3218
3219   if (N1.getOpcode() == ISD::OR &&
3220       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3221     // (or (or (and), (and)), (or (and), (and)))
3222     SDValue N000 = N00.getOperand(0);
3223     if (!isBSwapHWordElement(N000, Parts))
3224       return SDValue();
3225
3226     SDValue N001 = N00.getOperand(1);
3227     if (!isBSwapHWordElement(N001, Parts))
3228       return SDValue();
3229     SDValue N010 = N01.getOperand(0);
3230     if (!isBSwapHWordElement(N010, Parts))
3231       return SDValue();
3232     SDValue N011 = N01.getOperand(1);
3233     if (!isBSwapHWordElement(N011, Parts))
3234       return SDValue();
3235   } else {
3236     // (or (or (or (and), (and)), (and)), (and))
3237     if (!isBSwapHWordElement(N1, Parts))
3238       return SDValue();
3239     if (!isBSwapHWordElement(N01, Parts))
3240       return SDValue();
3241     if (N00.getOpcode() != ISD::OR)
3242       return SDValue();
3243     SDValue N000 = N00.getOperand(0);
3244     if (!isBSwapHWordElement(N000, Parts))
3245       return SDValue();
3246     SDValue N001 = N00.getOperand(1);
3247     if (!isBSwapHWordElement(N001, Parts))
3248       return SDValue();
3249   }
3250
3251   // Make sure the parts are all coming from the same node.
3252   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3253     return SDValue();
3254
3255   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3256                               SDValue(Parts[0],0));
3257
3258   // Result of the bswap should be rotated by 16. If it's not legal, then
3259   // do  (x << 16) | (x >> 16).
3260   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3261   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3262     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3263   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3264     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3265   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3266                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3267                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3268 }
3269
3270 SDValue DAGCombiner::visitOR(SDNode *N) {
3271   SDValue N0 = N->getOperand(0);
3272   SDValue N1 = N->getOperand(1);
3273   SDValue LL, LR, RL, RR, CC0, CC1;
3274   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3276   EVT VT = N1.getValueType();
3277
3278   // fold vector ops
3279   if (VT.isVector()) {
3280     SDValue FoldedVOp = SimplifyVBinOp(N);
3281     if (FoldedVOp.getNode()) return FoldedVOp;
3282
3283     // fold (or x, 0) -> x, vector edition
3284     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3285       return N1;
3286     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3287       return N0;
3288
3289     // fold (or x, -1) -> -1, vector edition
3290     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3291       // do not return N0, because undef node may exist in N0
3292       return DAG.getConstant(
3293           APInt::getAllOnesValue(
3294               N0.getValueType().getScalarType().getSizeInBits()),
3295           N0.getValueType());
3296     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3297       // do not return N1, because undef node may exist in N1
3298       return DAG.getConstant(
3299           APInt::getAllOnesValue(
3300               N1.getValueType().getScalarType().getSizeInBits()),
3301           N1.getValueType());
3302
3303     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3304     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3305     // Do this only if the resulting shuffle is legal.
3306     if (isa<ShuffleVectorSDNode>(N0) &&
3307         isa<ShuffleVectorSDNode>(N1) &&
3308         // Avoid folding a node with illegal type.
3309         TLI.isTypeLegal(VT) &&
3310         N0->getOperand(1) == N1->getOperand(1) &&
3311         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3312       bool CanFold = true;
3313       unsigned NumElts = VT.getVectorNumElements();
3314       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3315       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3316       // We construct two shuffle masks:
3317       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3318       // and N1 as the second operand.
3319       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3320       // and N0 as the second operand.
3321       // We do this because OR is commutable and therefore there might be
3322       // two ways to fold this node into a shuffle.
3323       SmallVector<int,4> Mask1;
3324       SmallVector<int,4> Mask2;
3325
3326       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3327         int M0 = SV0->getMaskElt(i);
3328         int M1 = SV1->getMaskElt(i);
3329
3330         // Both shuffle indexes are undef. Propagate Undef.
3331         if (M0 < 0 && M1 < 0) {
3332           Mask1.push_back(M0);
3333           Mask2.push_back(M0);
3334           continue;
3335         }
3336
3337         if (M0 < 0 || M1 < 0 ||
3338             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3339             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3340           CanFold = false;
3341           break;
3342         }
3343
3344         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3345         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3346       }
3347
3348       if (CanFold) {
3349         // Fold this sequence only if the resulting shuffle is 'legal'.
3350         if (TLI.isShuffleMaskLegal(Mask1, VT))
3351           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3352                                       N1->getOperand(0), &Mask1[0]);
3353         if (TLI.isShuffleMaskLegal(Mask2, VT))
3354           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3355                                       N0->getOperand(0), &Mask2[0]);
3356       }
3357     }
3358   }
3359
3360   // fold (or x, undef) -> -1
3361   if (!LegalOperations &&
3362       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3363     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3364     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3365   }
3366   // fold (or c1, c2) -> c1|c2
3367   if (N0C && N1C)
3368     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3369   // canonicalize constant to RHS
3370   if (N0C && !N1C)
3371     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3372   // fold (or x, 0) -> x
3373   if (N1C && N1C->isNullValue())
3374     return N0;
3375   // fold (or x, -1) -> -1
3376   if (N1C && N1C->isAllOnesValue())
3377     return N1;
3378   // fold (or x, c) -> c iff (x & ~c) == 0
3379   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3380     return N1;
3381
3382   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3383   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3384   if (BSwap.getNode())
3385     return BSwap;
3386   BSwap = MatchBSwapHWordLow(N, N0, N1);
3387   if (BSwap.getNode())
3388     return BSwap;
3389
3390   // reassociate or
3391   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3392   if (ROR.getNode())
3393     return ROR;
3394   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3395   // iff (c1 & c2) == 0.
3396   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3397              isa<ConstantSDNode>(N0.getOperand(1))) {
3398     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3399     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3400       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3401       if (!COR.getNode())
3402         return SDValue();
3403       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3404                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3405                                      N0.getOperand(0), N1), COR);
3406     }
3407   }
3408   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3409   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3410     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3411     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3412
3413     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3414         LL.getValueType().isInteger()) {
3415       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3416       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3417       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3418           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3419         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3420                                      LR.getValueType(), LL, RL);
3421         AddToWorklist(ORNode.getNode());
3422         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3423       }
3424       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3425       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3426       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3427           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3428         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3429                                       LR.getValueType(), LL, RL);
3430         AddToWorklist(ANDNode.getNode());
3431         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3432       }
3433     }
3434     // canonicalize equivalent to ll == rl
3435     if (LL == RR && LR == RL) {
3436       Op1 = ISD::getSetCCSwappedOperands(Op1);
3437       std::swap(RL, RR);
3438     }
3439     if (LL == RL && LR == RR) {
3440       bool isInteger = LL.getValueType().isInteger();
3441       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3442       if (Result != ISD::SETCC_INVALID &&
3443           (!LegalOperations ||
3444            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3445             TLI.isOperationLegal(ISD::SETCC,
3446               getSetCCResultType(N0.getValueType())))))
3447         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3448                             LL, LR, Result);
3449     }
3450   }
3451
3452   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3453   if (N0.getOpcode() == N1.getOpcode()) {
3454     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3455     if (Tmp.getNode()) return Tmp;
3456   }
3457
3458   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3459   if (N0.getOpcode() == ISD::AND &&
3460       N1.getOpcode() == ISD::AND &&
3461       N0.getOperand(1).getOpcode() == ISD::Constant &&
3462       N1.getOperand(1).getOpcode() == ISD::Constant &&
3463       // Don't increase # computations.
3464       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3465     // We can only do this xform if we know that bits from X that are set in C2
3466     // but not in C1 are already zero.  Likewise for Y.
3467     const APInt &LHSMask =
3468       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3469     const APInt &RHSMask =
3470       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3471
3472     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3473         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3474       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3475                               N0.getOperand(0), N1.getOperand(0));
3476       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3477                          DAG.getConstant(LHSMask | RHSMask, VT));
3478     }
3479   }
3480
3481   // See if this is some rotate idiom.
3482   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3483     return SDValue(Rot, 0);
3484
3485   // Simplify the operands using demanded-bits information.
3486   if (!VT.isVector() &&
3487       SimplifyDemandedBits(SDValue(N, 0)))
3488     return SDValue(N, 0);
3489
3490   return SDValue();
3491 }
3492
3493 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3494 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3495   if (Op.getOpcode() == ISD::AND) {
3496     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3497       Mask = Op.getOperand(1);
3498       Op = Op.getOperand(0);
3499     } else {
3500       return false;
3501     }
3502   }
3503
3504   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3505     Shift = Op;
3506     return true;
3507   }
3508
3509   return false;
3510 }
3511
3512 // Return true if we can prove that, whenever Neg and Pos are both in the
3513 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3514 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3515 //
3516 //     (or (shift1 X, Neg), (shift2 X, Pos))
3517 //
3518 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3519 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3520 // to consider shift amounts with defined behavior.
3521 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3522   // If OpSize is a power of 2 then:
3523   //
3524   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3525   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3526   //
3527   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3528   // for the stronger condition:
3529   //
3530   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3531   //
3532   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3533   // we can just replace Neg with Neg' for the rest of the function.
3534   //
3535   // In other cases we check for the even stronger condition:
3536   //
3537   //     Neg == OpSize - Pos                                    [B]
3538   //
3539   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3540   // behavior if Pos == 0 (and consequently Neg == OpSize).
3541   //
3542   // We could actually use [A] whenever OpSize is a power of 2, but the
3543   // only extra cases that it would match are those uninteresting ones
3544   // where Neg and Pos are never in range at the same time.  E.g. for
3545   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3546   // as well as (sub 32, Pos), but:
3547   //
3548   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3549   //
3550   // always invokes undefined behavior for 32-bit X.
3551   //
3552   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3553   unsigned MaskLoBits = 0;
3554   if (Neg.getOpcode() == ISD::AND &&
3555       isPowerOf2_64(OpSize) &&
3556       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3557       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3558     Neg = Neg.getOperand(0);
3559     MaskLoBits = Log2_64(OpSize);
3560   }
3561
3562   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3563   if (Neg.getOpcode() != ISD::SUB)
3564     return 0;
3565   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3566   if (!NegC)
3567     return 0;
3568   SDValue NegOp1 = Neg.getOperand(1);
3569
3570   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3571   // Pos'.  The truncation is redundant for the purpose of the equality.
3572   if (MaskLoBits &&
3573       Pos.getOpcode() == ISD::AND &&
3574       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3575       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3576     Pos = Pos.getOperand(0);
3577
3578   // The condition we need is now:
3579   //
3580   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3581   //
3582   // If NegOp1 == Pos then we need:
3583   //
3584   //              OpSize & Mask == NegC & Mask
3585   //
3586   // (because "x & Mask" is a truncation and distributes through subtraction).
3587   APInt Width;
3588   if (Pos == NegOp1)
3589     Width = NegC->getAPIntValue();
3590   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3591   // Then the condition we want to prove becomes:
3592   //
3593   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3594   //
3595   // which, again because "x & Mask" is a truncation, becomes:
3596   //
3597   //                NegC & Mask == (OpSize - PosC) & Mask
3598   //              OpSize & Mask == (NegC + PosC) & Mask
3599   else if (Pos.getOpcode() == ISD::ADD &&
3600            Pos.getOperand(0) == NegOp1 &&
3601            Pos.getOperand(1).getOpcode() == ISD::Constant)
3602     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3603              NegC->getAPIntValue());
3604   else
3605     return false;
3606
3607   // Now we just need to check that OpSize & Mask == Width & Mask.
3608   if (MaskLoBits)
3609     // Opsize & Mask is 0 since Mask is Opsize - 1.
3610     return Width.getLoBits(MaskLoBits) == 0;
3611   return Width == OpSize;
3612 }
3613
3614 // A subroutine of MatchRotate used once we have found an OR of two opposite
3615 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3616 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3617 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3618 // Neg with outer conversions stripped away.
3619 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3620                                        SDValue Neg, SDValue InnerPos,
3621                                        SDValue InnerNeg, unsigned PosOpcode,
3622                                        unsigned NegOpcode, SDLoc DL) {
3623   // fold (or (shl x, (*ext y)),
3624   //          (srl x, (*ext (sub 32, y)))) ->
3625   //   (rotl x, y) or (rotr x, (sub 32, y))
3626   //
3627   // fold (or (shl x, (*ext (sub 32, y))),
3628   //          (srl x, (*ext y))) ->
3629   //   (rotr x, y) or (rotl x, (sub 32, y))
3630   EVT VT = Shifted.getValueType();
3631   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3632     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3633     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3634                        HasPos ? Pos : Neg).getNode();
3635   }
3636
3637   return nullptr;
3638 }
3639
3640 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3641 // idioms for rotate, and if the target supports rotation instructions, generate
3642 // a rot[lr].
3643 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3644   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3645   EVT VT = LHS.getValueType();
3646   if (!TLI.isTypeLegal(VT)) return nullptr;
3647
3648   // The target must have at least one rotate flavor.
3649   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3650   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3651   if (!HasROTL && !HasROTR) return nullptr;
3652
3653   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3654   SDValue LHSShift;   // The shift.
3655   SDValue LHSMask;    // AND value if any.
3656   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3657     return nullptr; // Not part of a rotate.
3658
3659   SDValue RHSShift;   // The shift.
3660   SDValue RHSMask;    // AND value if any.
3661   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3662     return nullptr; // Not part of a rotate.
3663
3664   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3665     return nullptr;   // Not shifting the same value.
3666
3667   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3668     return nullptr;   // Shifts must disagree.
3669
3670   // Canonicalize shl to left side in a shl/srl pair.
3671   if (RHSShift.getOpcode() == ISD::SHL) {
3672     std::swap(LHS, RHS);
3673     std::swap(LHSShift, RHSShift);
3674     std::swap(LHSMask , RHSMask );
3675   }
3676
3677   unsigned OpSizeInBits = VT.getSizeInBits();
3678   SDValue LHSShiftArg = LHSShift.getOperand(0);
3679   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3680   SDValue RHSShiftArg = RHSShift.getOperand(0);
3681   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3682
3683   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3684   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3685   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3686       RHSShiftAmt.getOpcode() == ISD::Constant) {
3687     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3688     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3689     if ((LShVal + RShVal) != OpSizeInBits)
3690       return nullptr;
3691
3692     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3693                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3694
3695     // If there is an AND of either shifted operand, apply it to the result.
3696     if (LHSMask.getNode() || RHSMask.getNode()) {
3697       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3698
3699       if (LHSMask.getNode()) {
3700         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3701         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3702       }
3703       if (RHSMask.getNode()) {
3704         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3705         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3706       }
3707
3708       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3709     }
3710
3711     return Rot.getNode();
3712   }
3713
3714   // If there is a mask here, and we have a variable shift, we can't be sure
3715   // that we're masking out the right stuff.
3716   if (LHSMask.getNode() || RHSMask.getNode())
3717     return nullptr;
3718
3719   // If the shift amount is sign/zext/any-extended just peel it off.
3720   SDValue LExtOp0 = LHSShiftAmt;
3721   SDValue RExtOp0 = RHSShiftAmt;
3722   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3723        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3724        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3725        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3726       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3727        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3728        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3729        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3730     LExtOp0 = LHSShiftAmt.getOperand(0);
3731     RExtOp0 = RHSShiftAmt.getOperand(0);
3732   }
3733
3734   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3735                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3736   if (TryL)
3737     return TryL;
3738
3739   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3740                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3741   if (TryR)
3742     return TryR;
3743
3744   return nullptr;
3745 }
3746
3747 SDValue DAGCombiner::visitXOR(SDNode *N) {
3748   SDValue N0 = N->getOperand(0);
3749   SDValue N1 = N->getOperand(1);
3750   SDValue LHS, RHS, CC;
3751   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3753   EVT VT = N0.getValueType();
3754
3755   // fold vector ops
3756   if (VT.isVector()) {
3757     SDValue FoldedVOp = SimplifyVBinOp(N);
3758     if (FoldedVOp.getNode()) return FoldedVOp;
3759
3760     // fold (xor x, 0) -> x, vector edition
3761     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3762       return N1;
3763     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3764       return N0;
3765   }
3766
3767   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3768   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3769     return DAG.getConstant(0, VT);
3770   // fold (xor x, undef) -> undef
3771   if (N0.getOpcode() == ISD::UNDEF)
3772     return N0;
3773   if (N1.getOpcode() == ISD::UNDEF)
3774     return N1;
3775   // fold (xor c1, c2) -> c1^c2
3776   if (N0C && N1C)
3777     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3778   // canonicalize constant to RHS
3779   if (N0C && !N1C)
3780     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3781   // fold (xor x, 0) -> x
3782   if (N1C && N1C->isNullValue())
3783     return N0;
3784   // reassociate xor
3785   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3786   if (RXOR.getNode())
3787     return RXOR;
3788
3789   // fold !(x cc y) -> (x !cc y)
3790   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3791     bool isInt = LHS.getValueType().isInteger();
3792     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3793                                                isInt);
3794
3795     if (!LegalOperations ||
3796         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3797       switch (N0.getOpcode()) {
3798       default:
3799         llvm_unreachable("Unhandled SetCC Equivalent!");
3800       case ISD::SETCC:
3801         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3802       case ISD::SELECT_CC:
3803         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3804                                N0.getOperand(3), NotCC);
3805       }
3806     }
3807   }
3808
3809   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3810   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3811       N0.getNode()->hasOneUse() &&
3812       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3813     SDValue V = N0.getOperand(0);
3814     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3815                     DAG.getConstant(1, V.getValueType()));
3816     AddToWorklist(V.getNode());
3817     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3818   }
3819
3820   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3821   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3822       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3823     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3824     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3825       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3826       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3827       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3828       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3829       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3830     }
3831   }
3832   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3833   if (N1C && N1C->isAllOnesValue() &&
3834       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3835     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3836     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3837       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3838       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3839       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3840       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3841       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3842     }
3843   }
3844   // fold (xor (and x, y), y) -> (and (not x), y)
3845   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3846       N0->getOperand(1) == N1) {
3847     SDValue X = N0->getOperand(0);
3848     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3849     AddToWorklist(NotX.getNode());
3850     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3851   }
3852   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3853   if (N1C && N0.getOpcode() == ISD::XOR) {
3854     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3855     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3856     if (N00C)
3857       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3858                          DAG.getConstant(N1C->getAPIntValue() ^
3859                                          N00C->getAPIntValue(), VT));
3860     if (N01C)
3861       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3862                          DAG.getConstant(N1C->getAPIntValue() ^
3863                                          N01C->getAPIntValue(), VT));
3864   }
3865   // fold (xor x, x) -> 0
3866   if (N0 == N1)
3867     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3868
3869   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3870   if (N0.getOpcode() == N1.getOpcode()) {
3871     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3872     if (Tmp.getNode()) return Tmp;
3873   }
3874
3875   // Simplify the expression using non-local knowledge.
3876   if (!VT.isVector() &&
3877       SimplifyDemandedBits(SDValue(N, 0)))
3878     return SDValue(N, 0);
3879
3880   return SDValue();
3881 }
3882
3883 /// Handle transforms common to the three shifts, when the shift amount is a
3884 /// constant.
3885 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3886   // We can't and shouldn't fold opaque constants.
3887   if (Amt->isOpaque())
3888     return SDValue();
3889
3890   SDNode *LHS = N->getOperand(0).getNode();
3891   if (!LHS->hasOneUse()) return SDValue();
3892
3893   // We want to pull some binops through shifts, so that we have (and (shift))
3894   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3895   // thing happens with address calculations, so it's important to canonicalize
3896   // it.
3897   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3898
3899   switch (LHS->getOpcode()) {
3900   default: return SDValue();
3901   case ISD::OR:
3902   case ISD::XOR:
3903     HighBitSet = false; // We can only transform sra if the high bit is clear.
3904     break;
3905   case ISD::AND:
3906     HighBitSet = true;  // We can only transform sra if the high bit is set.
3907     break;
3908   case ISD::ADD:
3909     if (N->getOpcode() != ISD::SHL)
3910       return SDValue(); // only shl(add) not sr[al](add).
3911     HighBitSet = false; // We can only transform sra if the high bit is clear.
3912     break;
3913   }
3914
3915   // We require the RHS of the binop to be a constant and not opaque as well.
3916   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3917   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3918
3919   // FIXME: disable this unless the input to the binop is a shift by a constant.
3920   // If it is not a shift, it pessimizes some common cases like:
3921   //
3922   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3923   //    int bar(int *X, int i) { return X[i & 255]; }
3924   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3925   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3926        BinOpLHSVal->getOpcode() != ISD::SRA &&
3927        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3928       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3929     return SDValue();
3930
3931   EVT VT = N->getValueType(0);
3932
3933   // If this is a signed shift right, and the high bit is modified by the
3934   // logical operation, do not perform the transformation. The highBitSet
3935   // boolean indicates the value of the high bit of the constant which would
3936   // cause it to be modified for this operation.
3937   if (N->getOpcode() == ISD::SRA) {
3938     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3939     if (BinOpRHSSignSet != HighBitSet)
3940       return SDValue();
3941   }
3942
3943   if (!TLI.isDesirableToCommuteWithShift(LHS))
3944     return SDValue();
3945
3946   // Fold the constants, shifting the binop RHS by the shift amount.
3947   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3948                                N->getValueType(0),
3949                                LHS->getOperand(1), N->getOperand(1));
3950   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3951
3952   // Create the new shift.
3953   SDValue NewShift = DAG.getNode(N->getOpcode(),
3954                                  SDLoc(LHS->getOperand(0)),
3955                                  VT, LHS->getOperand(0), N->getOperand(1));
3956
3957   // Create the new binop.
3958   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3959 }
3960
3961 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3962   assert(N->getOpcode() == ISD::TRUNCATE);
3963   assert(N->getOperand(0).getOpcode() == ISD::AND);
3964
3965   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3966   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3967     SDValue N01 = N->getOperand(0).getOperand(1);
3968
3969     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3970       EVT TruncVT = N->getValueType(0);
3971       SDValue N00 = N->getOperand(0).getOperand(0);
3972       APInt TruncC = N01C->getAPIntValue();
3973       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3974
3975       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3976                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3977                          DAG.getConstant(TruncC, TruncVT));
3978     }
3979   }
3980
3981   return SDValue();
3982 }
3983
3984 SDValue DAGCombiner::visitRotate(SDNode *N) {
3985   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3986   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3987       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3988     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3989     if (NewOp1.getNode())
3990       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3991                          N->getOperand(0), NewOp1);
3992   }
3993   return SDValue();
3994 }
3995
3996 SDValue DAGCombiner::visitSHL(SDNode *N) {
3997   SDValue N0 = N->getOperand(0);
3998   SDValue N1 = N->getOperand(1);
3999   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4000   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4001   EVT VT = N0.getValueType();
4002   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4003
4004   // fold vector ops
4005   if (VT.isVector()) {
4006     SDValue FoldedVOp = SimplifyVBinOp(N);
4007     if (FoldedVOp.getNode()) return FoldedVOp;
4008
4009     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4010     // If setcc produces all-one true value then:
4011     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4012     if (N1CV && N1CV->isConstant()) {
4013       if (N0.getOpcode() == ISD::AND) {
4014         SDValue N00 = N0->getOperand(0);
4015         SDValue N01 = N0->getOperand(1);
4016         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4017
4018         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4019             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4020                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4021           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4022           if (C.getNode())
4023             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4024         }
4025       } else {
4026         N1C = isConstOrConstSplat(N1);
4027       }
4028     }
4029   }
4030
4031   // fold (shl c1, c2) -> c1<<c2
4032   if (N0C && N1C)
4033     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4034   // fold (shl 0, x) -> 0
4035   if (N0C && N0C->isNullValue())
4036     return N0;
4037   // fold (shl x, c >= size(x)) -> undef
4038   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4039     return DAG.getUNDEF(VT);
4040   // fold (shl x, 0) -> x
4041   if (N1C && N1C->isNullValue())
4042     return N0;
4043   // fold (shl undef, x) -> 0
4044   if (N0.getOpcode() == ISD::UNDEF)
4045     return DAG.getConstant(0, VT);
4046   // if (shl x, c) is known to be zero, return 0
4047   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4048                             APInt::getAllOnesValue(OpSizeInBits)))
4049     return DAG.getConstant(0, VT);
4050   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4051   if (N1.getOpcode() == ISD::TRUNCATE &&
4052       N1.getOperand(0).getOpcode() == ISD::AND) {
4053     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4054     if (NewOp1.getNode())
4055       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4056   }
4057
4058   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4059     return SDValue(N, 0);
4060
4061   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4062   if (N1C && N0.getOpcode() == ISD::SHL) {
4063     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4064       uint64_t c1 = N0C1->getZExtValue();
4065       uint64_t c2 = N1C->getZExtValue();
4066       if (c1 + c2 >= OpSizeInBits)
4067         return DAG.getConstant(0, VT);
4068       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4069                          DAG.getConstant(c1 + c2, N1.getValueType()));
4070     }
4071   }
4072
4073   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4074   // For this to be valid, the second form must not preserve any of the bits
4075   // that are shifted out by the inner shift in the first form.  This means
4076   // the outer shift size must be >= the number of bits added by the ext.
4077   // As a corollary, we don't care what kind of ext it is.
4078   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4079               N0.getOpcode() == ISD::ANY_EXTEND ||
4080               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4081       N0.getOperand(0).getOpcode() == ISD::SHL) {
4082     SDValue N0Op0 = N0.getOperand(0);
4083     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4084       uint64_t c1 = N0Op0C1->getZExtValue();
4085       uint64_t c2 = N1C->getZExtValue();
4086       EVT InnerShiftVT = N0Op0.getValueType();
4087       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4088       if (c2 >= OpSizeInBits - InnerShiftSize) {
4089         if (c1 + c2 >= OpSizeInBits)
4090           return DAG.getConstant(0, VT);
4091         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4092                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4093                                        N0Op0->getOperand(0)),
4094                            DAG.getConstant(c1 + c2, N1.getValueType()));
4095       }
4096     }
4097   }
4098
4099   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4100   // Only fold this if the inner zext has no other uses to avoid increasing
4101   // the total number of instructions.
4102   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4103       N0.getOperand(0).getOpcode() == ISD::SRL) {
4104     SDValue N0Op0 = N0.getOperand(0);
4105     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4106       uint64_t c1 = N0Op0C1->getZExtValue();
4107       if (c1 < VT.getScalarSizeInBits()) {
4108         uint64_t c2 = N1C->getZExtValue();
4109         if (c1 == c2) {
4110           SDValue NewOp0 = N0.getOperand(0);
4111           EVT CountVT = NewOp0.getOperand(1).getValueType();
4112           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4113                                        NewOp0, DAG.getConstant(c2, CountVT));
4114           AddToWorklist(NewSHL.getNode());
4115           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4116         }
4117       }
4118     }
4119   }
4120
4121   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4122   //                               (and (srl x, (sub c1, c2), MASK)
4123   // Only fold this if the inner shift has no other uses -- if it does, folding
4124   // this will increase the total number of instructions.
4125   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4126     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4127       uint64_t c1 = N0C1->getZExtValue();
4128       if (c1 < OpSizeInBits) {
4129         uint64_t c2 = N1C->getZExtValue();
4130         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4131         SDValue Shift;
4132         if (c2 > c1) {
4133           Mask = Mask.shl(c2 - c1);
4134           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4135                               DAG.getConstant(c2 - c1, N1.getValueType()));
4136         } else {
4137           Mask = Mask.lshr(c1 - c2);
4138           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4139                               DAG.getConstant(c1 - c2, N1.getValueType()));
4140         }
4141         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4142                            DAG.getConstant(Mask, VT));
4143       }
4144     }
4145   }
4146   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4147   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4148     unsigned BitSize = VT.getScalarSizeInBits();
4149     SDValue HiBitsMask =
4150       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4151                                             BitSize - N1C->getZExtValue()), VT);
4152     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4153                        HiBitsMask);
4154   }
4155
4156   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4157   // Variant of version done on multiply, except mul by a power of 2 is turned
4158   // into a shift.
4159   APInt Val;
4160   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4161       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4162        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4163     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4164     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4165     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4166   }
4167
4168   if (N1C) {
4169     SDValue NewSHL = visitShiftByConstant(N, N1C);
4170     if (NewSHL.getNode())
4171       return NewSHL;
4172   }
4173
4174   return SDValue();
4175 }
4176
4177 SDValue DAGCombiner::visitSRA(SDNode *N) {
4178   SDValue N0 = N->getOperand(0);
4179   SDValue N1 = N->getOperand(1);
4180   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4181   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4182   EVT VT = N0.getValueType();
4183   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4184
4185   // fold vector ops
4186   if (VT.isVector()) {
4187     SDValue FoldedVOp = SimplifyVBinOp(N);
4188     if (FoldedVOp.getNode()) return FoldedVOp;
4189
4190     N1C = isConstOrConstSplat(N1);
4191   }
4192
4193   // fold (sra c1, c2) -> (sra c1, c2)
4194   if (N0C && N1C)
4195     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4196   // fold (sra 0, x) -> 0
4197   if (N0C && N0C->isNullValue())
4198     return N0;
4199   // fold (sra -1, x) -> -1
4200   if (N0C && N0C->isAllOnesValue())
4201     return N0;
4202   // fold (sra x, (setge c, size(x))) -> undef
4203   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4204     return DAG.getUNDEF(VT);
4205   // fold (sra x, 0) -> x
4206   if (N1C && N1C->isNullValue())
4207     return N0;
4208   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4209   // sext_inreg.
4210   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4211     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4212     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4213     if (VT.isVector())
4214       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4215                                ExtVT, VT.getVectorNumElements());
4216     if ((!LegalOperations ||
4217          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4218       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4219                          N0.getOperand(0), DAG.getValueType(ExtVT));
4220   }
4221
4222   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4223   if (N1C && N0.getOpcode() == ISD::SRA) {
4224     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4225       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4226       if (Sum >= OpSizeInBits)
4227         Sum = OpSizeInBits - 1;
4228       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4229                          DAG.getConstant(Sum, N1.getValueType()));
4230     }
4231   }
4232
4233   // fold (sra (shl X, m), (sub result_size, n))
4234   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4235   // result_size - n != m.
4236   // If truncate is free for the target sext(shl) is likely to result in better
4237   // code.
4238   if (N0.getOpcode() == ISD::SHL && N1C) {
4239     // Get the two constanst of the shifts, CN0 = m, CN = n.
4240     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4241     if (N01C) {
4242       LLVMContext &Ctx = *DAG.getContext();
4243       // Determine what the truncate's result bitsize and type would be.
4244       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4245
4246       if (VT.isVector())
4247         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4248
4249       // Determine the residual right-shift amount.
4250       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4251
4252       // If the shift is not a no-op (in which case this should be just a sign
4253       // extend already), the truncated to type is legal, sign_extend is legal
4254       // on that type, and the truncate to that type is both legal and free,
4255       // perform the transform.
4256       if ((ShiftAmt > 0) &&
4257           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4258           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4259           TLI.isTruncateFree(VT, TruncVT)) {
4260
4261           SDValue Amt = DAG.getConstant(ShiftAmt,
4262               getShiftAmountTy(N0.getOperand(0).getValueType()));
4263           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4264                                       N0.getOperand(0), Amt);
4265           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4266                                       Shift);
4267           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4268                              N->getValueType(0), Trunc);
4269       }
4270     }
4271   }
4272
4273   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4274   if (N1.getOpcode() == ISD::TRUNCATE &&
4275       N1.getOperand(0).getOpcode() == ISD::AND) {
4276     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4277     if (NewOp1.getNode())
4278       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4279   }
4280
4281   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4282   //      if c1 is equal to the number of bits the trunc removes
4283   if (N0.getOpcode() == ISD::TRUNCATE &&
4284       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4285        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4286       N0.getOperand(0).hasOneUse() &&
4287       N0.getOperand(0).getOperand(1).hasOneUse() &&
4288       N1C) {
4289     SDValue N0Op0 = N0.getOperand(0);
4290     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4291       unsigned LargeShiftVal = LargeShift->getZExtValue();
4292       EVT LargeVT = N0Op0.getValueType();
4293
4294       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4295         SDValue Amt =
4296           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4297                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4298         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4299                                   N0Op0.getOperand(0), Amt);
4300         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4301       }
4302     }
4303   }
4304
4305   // Simplify, based on bits shifted out of the LHS.
4306   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4307     return SDValue(N, 0);
4308
4309
4310   // If the sign bit is known to be zero, switch this to a SRL.
4311   if (DAG.SignBitIsZero(N0))
4312     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4313
4314   if (N1C) {
4315     SDValue NewSRA = visitShiftByConstant(N, N1C);
4316     if (NewSRA.getNode())
4317       return NewSRA;
4318   }
4319
4320   return SDValue();
4321 }
4322
4323 SDValue DAGCombiner::visitSRL(SDNode *N) {
4324   SDValue N0 = N->getOperand(0);
4325   SDValue N1 = N->getOperand(1);
4326   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4328   EVT VT = N0.getValueType();
4329   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4330
4331   // fold vector ops
4332   if (VT.isVector()) {
4333     SDValue FoldedVOp = SimplifyVBinOp(N);
4334     if (FoldedVOp.getNode()) return FoldedVOp;
4335
4336     N1C = isConstOrConstSplat(N1);
4337   }
4338
4339   // fold (srl c1, c2) -> c1 >>u c2
4340   if (N0C && N1C)
4341     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4342   // fold (srl 0, x) -> 0
4343   if (N0C && N0C->isNullValue())
4344     return N0;
4345   // fold (srl x, c >= size(x)) -> undef
4346   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4347     return DAG.getUNDEF(VT);
4348   // fold (srl x, 0) -> x
4349   if (N1C && N1C->isNullValue())
4350     return N0;
4351   // if (srl x, c) is known to be zero, return 0
4352   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4353                                    APInt::getAllOnesValue(OpSizeInBits)))
4354     return DAG.getConstant(0, VT);
4355
4356   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4357   if (N1C && N0.getOpcode() == ISD::SRL) {
4358     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4359       uint64_t c1 = N01C->getZExtValue();
4360       uint64_t c2 = N1C->getZExtValue();
4361       if (c1 + c2 >= OpSizeInBits)
4362         return DAG.getConstant(0, VT);
4363       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4364                          DAG.getConstant(c1 + c2, N1.getValueType()));
4365     }
4366   }
4367
4368   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4369   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4370       N0.getOperand(0).getOpcode() == ISD::SRL &&
4371       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4372     uint64_t c1 =
4373       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4374     uint64_t c2 = N1C->getZExtValue();
4375     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4376     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4377     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4378     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4379     if (c1 + OpSizeInBits == InnerShiftSize) {
4380       if (c1 + c2 >= InnerShiftSize)
4381         return DAG.getConstant(0, VT);
4382       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4383                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4384                                      N0.getOperand(0)->getOperand(0),
4385                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4386     }
4387   }
4388
4389   // fold (srl (shl x, c), c) -> (and x, cst2)
4390   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4391     unsigned BitSize = N0.getScalarValueSizeInBits();
4392     if (BitSize <= 64) {
4393       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4394       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4395                          DAG.getConstant(~0ULL >> ShAmt, VT));
4396     }
4397   }
4398
4399   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4400   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4401     // Shifting in all undef bits?
4402     EVT SmallVT = N0.getOperand(0).getValueType();
4403     unsigned BitSize = SmallVT.getScalarSizeInBits();
4404     if (N1C->getZExtValue() >= BitSize)
4405       return DAG.getUNDEF(VT);
4406
4407     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4408       uint64_t ShiftAmt = N1C->getZExtValue();
4409       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4410                                        N0.getOperand(0),
4411                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4412       AddToWorklist(SmallShift.getNode());
4413       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4414       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4415                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4416                          DAG.getConstant(Mask, VT));
4417     }
4418   }
4419
4420   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4421   // bit, which is unmodified by sra.
4422   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4423     if (N0.getOpcode() == ISD::SRA)
4424       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4425   }
4426
4427   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4428   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4429       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4430     APInt KnownZero, KnownOne;
4431     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4432
4433     // If any of the input bits are KnownOne, then the input couldn't be all
4434     // zeros, thus the result of the srl will always be zero.
4435     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4436
4437     // If all of the bits input the to ctlz node are known to be zero, then
4438     // the result of the ctlz is "32" and the result of the shift is one.
4439     APInt UnknownBits = ~KnownZero;
4440     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4441
4442     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4443     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4444       // Okay, we know that only that the single bit specified by UnknownBits
4445       // could be set on input to the CTLZ node. If this bit is set, the SRL
4446       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4447       // to an SRL/XOR pair, which is likely to simplify more.
4448       unsigned ShAmt = UnknownBits.countTrailingZeros();
4449       SDValue Op = N0.getOperand(0);
4450
4451       if (ShAmt) {
4452         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4453                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4454         AddToWorklist(Op.getNode());
4455       }
4456
4457       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4458                          Op, DAG.getConstant(1, VT));
4459     }
4460   }
4461
4462   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4463   if (N1.getOpcode() == ISD::TRUNCATE &&
4464       N1.getOperand(0).getOpcode() == ISD::AND) {
4465     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4466     if (NewOp1.getNode())
4467       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4468   }
4469
4470   // fold operands of srl based on knowledge that the low bits are not
4471   // demanded.
4472   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4473     return SDValue(N, 0);
4474
4475   if (N1C) {
4476     SDValue NewSRL = visitShiftByConstant(N, N1C);
4477     if (NewSRL.getNode())
4478       return NewSRL;
4479   }
4480
4481   // Attempt to convert a srl of a load into a narrower zero-extending load.
4482   SDValue NarrowLoad = ReduceLoadWidth(N);
4483   if (NarrowLoad.getNode())
4484     return NarrowLoad;
4485
4486   // Here is a common situation. We want to optimize:
4487   //
4488   //   %a = ...
4489   //   %b = and i32 %a, 2
4490   //   %c = srl i32 %b, 1
4491   //   brcond i32 %c ...
4492   //
4493   // into
4494   //
4495   //   %a = ...
4496   //   %b = and %a, 2
4497   //   %c = setcc eq %b, 0
4498   //   brcond %c ...
4499   //
4500   // However when after the source operand of SRL is optimized into AND, the SRL
4501   // itself may not be optimized further. Look for it and add the BRCOND into
4502   // the worklist.
4503   if (N->hasOneUse()) {
4504     SDNode *Use = *N->use_begin();
4505     if (Use->getOpcode() == ISD::BRCOND)
4506       AddToWorklist(Use);
4507     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4508       // Also look pass the truncate.
4509       Use = *Use->use_begin();
4510       if (Use->getOpcode() == ISD::BRCOND)
4511         AddToWorklist(Use);
4512     }
4513   }
4514
4515   return SDValue();
4516 }
4517
4518 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4519   SDValue N0 = N->getOperand(0);
4520   EVT VT = N->getValueType(0);
4521
4522   // fold (ctlz c1) -> c2
4523   if (isa<ConstantSDNode>(N0))
4524     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4525   return SDValue();
4526 }
4527
4528 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4529   SDValue N0 = N->getOperand(0);
4530   EVT VT = N->getValueType(0);
4531
4532   // fold (ctlz_zero_undef c1) -> c2
4533   if (isa<ConstantSDNode>(N0))
4534     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4535   return SDValue();
4536 }
4537
4538 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4539   SDValue N0 = N->getOperand(0);
4540   EVT VT = N->getValueType(0);
4541
4542   // fold (cttz c1) -> c2
4543   if (isa<ConstantSDNode>(N0))
4544     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4545   return SDValue();
4546 }
4547
4548 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4549   SDValue N0 = N->getOperand(0);
4550   EVT VT = N->getValueType(0);
4551
4552   // fold (cttz_zero_undef c1) -> c2
4553   if (isa<ConstantSDNode>(N0))
4554     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4555   return SDValue();
4556 }
4557
4558 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4559   SDValue N0 = N->getOperand(0);
4560   EVT VT = N->getValueType(0);
4561
4562   // fold (ctpop c1) -> c2
4563   if (isa<ConstantSDNode>(N0))
4564     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   SDValue N1 = N->getOperand(1);
4571   SDValue N2 = N->getOperand(2);
4572   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4573   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4574   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4575   EVT VT = N->getValueType(0);
4576   EVT VT0 = N0.getValueType();
4577
4578   // fold (select C, X, X) -> X
4579   if (N1 == N2)
4580     return N1;
4581   // fold (select true, X, Y) -> X
4582   if (N0C && !N0C->isNullValue())
4583     return N1;
4584   // fold (select false, X, Y) -> Y
4585   if (N0C && N0C->isNullValue())
4586     return N2;
4587   // fold (select C, 1, X) -> (or C, X)
4588   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4589     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4590   // fold (select C, 0, 1) -> (xor C, 1)
4591   // We can't do this reliably if integer based booleans have different contents
4592   // to floating point based booleans. This is because we can't tell whether we
4593   // have an integer-based boolean or a floating-point-based boolean unless we
4594   // can find the SETCC that produced it and inspect its operands. This is
4595   // fairly easy if C is the SETCC node, but it can potentially be
4596   // undiscoverable (or not reasonably discoverable). For example, it could be
4597   // in another basic block or it could require searching a complicated
4598   // expression.
4599   if (VT.isInteger() &&
4600       (VT0 == MVT::i1 || (VT0.isInteger() &&
4601                           TLI.getBooleanContents(false, false) ==
4602                               TLI.getBooleanContents(false, true) &&
4603                           TLI.getBooleanContents(false, false) ==
4604                               TargetLowering::ZeroOrOneBooleanContent)) &&
4605       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4606     SDValue XORNode;
4607     if (VT == VT0)
4608       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4609                          N0, DAG.getConstant(1, VT0));
4610     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4611                           N0, DAG.getConstant(1, VT0));
4612     AddToWorklist(XORNode.getNode());
4613     if (VT.bitsGT(VT0))
4614       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4615     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4616   }
4617   // fold (select C, 0, X) -> (and (not C), X)
4618   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4619     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4620     AddToWorklist(NOTNode.getNode());
4621     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4622   }
4623   // fold (select C, X, 1) -> (or (not C), X)
4624   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4625     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4626     AddToWorklist(NOTNode.getNode());
4627     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4628   }
4629   // fold (select C, X, 0) -> (and C, X)
4630   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4631     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4632   // fold (select X, X, Y) -> (or X, Y)
4633   // fold (select X, 1, Y) -> (or X, Y)
4634   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4635     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4636   // fold (select X, Y, X) -> (and X, Y)
4637   // fold (select X, Y, 0) -> (and X, Y)
4638   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4639     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4640
4641   // If we can fold this based on the true/false value, do so.
4642   if (SimplifySelectOps(N, N1, N2))
4643     return SDValue(N, 0);  // Don't revisit N.
4644
4645   // fold selects based on a setcc into other things, such as min/max/abs
4646   if (N0.getOpcode() == ISD::SETCC) {
4647     if ((!LegalOperations &&
4648          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4649         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4650       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4651                          N0.getOperand(0), N0.getOperand(1),
4652                          N1, N2, N0.getOperand(2));
4653     return SimplifySelect(SDLoc(N), N0, N1, N2);
4654   }
4655
4656   return SDValue();
4657 }
4658
4659 static
4660 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4661   SDLoc DL(N);
4662   EVT LoVT, HiVT;
4663   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4664
4665   // Split the inputs.
4666   SDValue Lo, Hi, LL, LH, RL, RH;
4667   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4668   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4669
4670   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4671   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4672
4673   return std::make_pair(Lo, Hi);
4674 }
4675
4676 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4677 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4678 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4679   SDLoc dl(N);
4680   SDValue Cond = N->getOperand(0);
4681   SDValue LHS = N->getOperand(1);
4682   SDValue RHS = N->getOperand(2);
4683   EVT VT = N->getValueType(0);
4684   int NumElems = VT.getVectorNumElements();
4685   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4686          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4687          Cond.getOpcode() == ISD::BUILD_VECTOR);
4688
4689   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4690   // binary ones here.
4691   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4692     return SDValue();
4693
4694   // We're sure we have an even number of elements due to the
4695   // concat_vectors we have as arguments to vselect.
4696   // Skip BV elements until we find one that's not an UNDEF
4697   // After we find an UNDEF element, keep looping until we get to half the
4698   // length of the BV and see if all the non-undef nodes are the same.
4699   ConstantSDNode *BottomHalf = nullptr;
4700   for (int i = 0; i < NumElems / 2; ++i) {
4701     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4702       continue;
4703
4704     if (BottomHalf == nullptr)
4705       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4706     else if (Cond->getOperand(i).getNode() != BottomHalf)
4707       return SDValue();
4708   }
4709
4710   // Do the same for the second half of the BuildVector
4711   ConstantSDNode *TopHalf = nullptr;
4712   for (int i = NumElems / 2; i < NumElems; ++i) {
4713     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4714       continue;
4715
4716     if (TopHalf == nullptr)
4717       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4718     else if (Cond->getOperand(i).getNode() != TopHalf)
4719       return SDValue();
4720   }
4721
4722   assert(TopHalf && BottomHalf &&
4723          "One half of the selector was all UNDEFs and the other was all the "
4724          "same value. This should have been addressed before this function.");
4725   return DAG.getNode(
4726       ISD::CONCAT_VECTORS, dl, VT,
4727       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4728       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4729 }
4730
4731 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4732   SDValue N0 = N->getOperand(0);
4733   SDValue N1 = N->getOperand(1);
4734   SDValue N2 = N->getOperand(2);
4735   SDLoc DL(N);
4736
4737   // Canonicalize integer abs.
4738   // vselect (setg[te] X,  0),  X, -X ->
4739   // vselect (setgt    X, -1),  X, -X ->
4740   // vselect (setl[te] X,  0), -X,  X ->
4741   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4742   if (N0.getOpcode() == ISD::SETCC) {
4743     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4744     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4745     bool isAbs = false;
4746     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4747
4748     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4749          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4750         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4751       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4752     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4753              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4754       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4755
4756     if (isAbs) {
4757       EVT VT = LHS.getValueType();
4758       SDValue Shift = DAG.getNode(
4759           ISD::SRA, DL, VT, LHS,
4760           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4761       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4762       AddToWorklist(Shift.getNode());
4763       AddToWorklist(Add.getNode());
4764       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4765     }
4766   }
4767
4768   // If the VSELECT result requires splitting and the mask is provided by a
4769   // SETCC, then split both nodes and its operands before legalization. This
4770   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4771   // and enables future optimizations (e.g. min/max pattern matching on X86).
4772   if (N0.getOpcode() == ISD::SETCC) {
4773     EVT VT = N->getValueType(0);
4774
4775     // Check if any splitting is required.
4776     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4777         TargetLowering::TypeSplitVector)
4778       return SDValue();
4779
4780     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4781     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4782     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4783     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4784
4785     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4786     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4787
4788     // Add the new VSELECT nodes to the work list in case they need to be split
4789     // again.
4790     AddToWorklist(Lo.getNode());
4791     AddToWorklist(Hi.getNode());
4792
4793     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4794   }
4795
4796   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4797   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4798     return N1;
4799   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4800   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4801     return N2;
4802
4803   // The ConvertSelectToConcatVector function is assuming both the above
4804   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4805   // and addressed.
4806   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4807       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4808       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4809     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4810     if (CV.getNode())
4811       return CV;
4812   }
4813
4814   return SDValue();
4815 }
4816
4817 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4818   SDValue N0 = N->getOperand(0);
4819   SDValue N1 = N->getOperand(1);
4820   SDValue N2 = N->getOperand(2);
4821   SDValue N3 = N->getOperand(3);
4822   SDValue N4 = N->getOperand(4);
4823   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4824
4825   // fold select_cc lhs, rhs, x, x, cc -> x
4826   if (N2 == N3)
4827     return N2;
4828
4829   // Determine if the condition we're dealing with is constant
4830   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4831                               N0, N1, CC, SDLoc(N), false);
4832   if (SCC.getNode()) {
4833     AddToWorklist(SCC.getNode());
4834
4835     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4836       if (!SCCC->isNullValue())
4837         return N2;    // cond always true -> true val
4838       else
4839         return N3;    // cond always false -> false val
4840     }
4841
4842     // Fold to a simpler select_cc
4843     if (SCC.getOpcode() == ISD::SETCC)
4844       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4845                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4846                          SCC.getOperand(2));
4847   }
4848
4849   // If we can fold this based on the true/false value, do so.
4850   if (SimplifySelectOps(N, N2, N3))
4851     return SDValue(N, 0);  // Don't revisit N.
4852
4853   // fold select_cc into other things, such as min/max/abs
4854   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4855 }
4856
4857 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4858   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4859                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4860                        SDLoc(N));
4861 }
4862
4863 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4864 // dag node into a ConstantSDNode or a build_vector of constants.
4865 // This function is called by the DAGCombiner when visiting sext/zext/aext
4866 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4867 // Vector extends are not folded if operations are legal; this is to
4868 // avoid introducing illegal build_vector dag nodes.
4869 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4870                                          SelectionDAG &DAG, bool LegalTypes,
4871                                          bool LegalOperations) {
4872   unsigned Opcode = N->getOpcode();
4873   SDValue N0 = N->getOperand(0);
4874   EVT VT = N->getValueType(0);
4875
4876   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4877          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4878
4879   // fold (sext c1) -> c1
4880   // fold (zext c1) -> c1
4881   // fold (aext c1) -> c1
4882   if (isa<ConstantSDNode>(N0))
4883     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4884
4885   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4886   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4887   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4888   EVT SVT = VT.getScalarType();
4889   if (!(VT.isVector() &&
4890       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4891       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4892     return nullptr;
4893
4894   // We can fold this node into a build_vector.
4895   unsigned VTBits = SVT.getSizeInBits();
4896   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4897   unsigned ShAmt = VTBits - EVTBits;
4898   SmallVector<SDValue, 8> Elts;
4899   unsigned NumElts = N0->getNumOperands();
4900   SDLoc DL(N);
4901
4902   for (unsigned i=0; i != NumElts; ++i) {
4903     SDValue Op = N0->getOperand(i);
4904     if (Op->getOpcode() == ISD::UNDEF) {
4905       Elts.push_back(DAG.getUNDEF(SVT));
4906       continue;
4907     }
4908
4909     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4910     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4911     if (Opcode == ISD::SIGN_EXTEND)
4912       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4913                                      SVT));
4914     else
4915       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4916                                      SVT));
4917   }
4918
4919   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4920 }
4921
4922 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4923 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4924 // transformation. Returns true if extension are possible and the above
4925 // mentioned transformation is profitable.
4926 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4927                                     unsigned ExtOpc,
4928                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4929                                     const TargetLowering &TLI) {
4930   bool HasCopyToRegUses = false;
4931   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4932   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4933                             UE = N0.getNode()->use_end();
4934        UI != UE; ++UI) {
4935     SDNode *User = *UI;
4936     if (User == N)
4937       continue;
4938     if (UI.getUse().getResNo() != N0.getResNo())
4939       continue;
4940     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4941     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4942       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4943       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4944         // Sign bits will be lost after a zext.
4945         return false;
4946       bool Add = false;
4947       for (unsigned i = 0; i != 2; ++i) {
4948         SDValue UseOp = User->getOperand(i);
4949         if (UseOp == N0)
4950           continue;
4951         if (!isa<ConstantSDNode>(UseOp))
4952           return false;
4953         Add = true;
4954       }
4955       if (Add)
4956         ExtendNodes.push_back(User);
4957       continue;
4958     }
4959     // If truncates aren't free and there are users we can't
4960     // extend, it isn't worthwhile.
4961     if (!isTruncFree)
4962       return false;
4963     // Remember if this value is live-out.
4964     if (User->getOpcode() == ISD::CopyToReg)
4965       HasCopyToRegUses = true;
4966   }
4967
4968   if (HasCopyToRegUses) {
4969     bool BothLiveOut = false;
4970     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4971          UI != UE; ++UI) {
4972       SDUse &Use = UI.getUse();
4973       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4974         BothLiveOut = true;
4975         break;
4976       }
4977     }
4978     if (BothLiveOut)
4979       // Both unextended and extended values are live out. There had better be
4980       // a good reason for the transformation.
4981       return ExtendNodes.size();
4982   }
4983   return true;
4984 }
4985
4986 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4987                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4988                                   ISD::NodeType ExtType) {
4989   // Extend SetCC uses if necessary.
4990   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4991     SDNode *SetCC = SetCCs[i];
4992     SmallVector<SDValue, 4> Ops;
4993
4994     for (unsigned j = 0; j != 2; ++j) {
4995       SDValue SOp = SetCC->getOperand(j);
4996       if (SOp == Trunc)
4997         Ops.push_back(ExtLoad);
4998       else
4999         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5000     }
5001
5002     Ops.push_back(SetCC->getOperand(2));
5003     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5004   }
5005 }
5006
5007 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5008   SDValue N0 = N->getOperand(0);
5009   EVT VT = N->getValueType(0);
5010
5011   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5012                                               LegalOperations))
5013     return SDValue(Res, 0);
5014
5015   // fold (sext (sext x)) -> (sext x)
5016   // fold (sext (aext x)) -> (sext x)
5017   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5018     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5019                        N0.getOperand(0));
5020
5021   if (N0.getOpcode() == ISD::TRUNCATE) {
5022     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5023     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5024     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5025     if (NarrowLoad.getNode()) {
5026       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5027       if (NarrowLoad.getNode() != N0.getNode()) {
5028         CombineTo(N0.getNode(), NarrowLoad);
5029         // CombineTo deleted the truncate, if needed, but not what's under it.
5030         AddToWorklist(oye);
5031       }
5032       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5033     }
5034
5035     // See if the value being truncated is already sign extended.  If so, just
5036     // eliminate the trunc/sext pair.
5037     SDValue Op = N0.getOperand(0);
5038     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5039     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5040     unsigned DestBits = VT.getScalarType().getSizeInBits();
5041     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5042
5043     if (OpBits == DestBits) {
5044       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5045       // bits, it is already ready.
5046       if (NumSignBits > DestBits-MidBits)
5047         return Op;
5048     } else if (OpBits < DestBits) {
5049       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5050       // bits, just sext from i32.
5051       if (NumSignBits > OpBits-MidBits)
5052         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5053     } else {
5054       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5055       // bits, just truncate to i32.
5056       if (NumSignBits > OpBits-MidBits)
5057         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5058     }
5059
5060     // fold (sext (truncate x)) -> (sextinreg x).
5061     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5062                                                  N0.getValueType())) {
5063       if (OpBits < DestBits)
5064         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5065       else if (OpBits > DestBits)
5066         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5067       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5068                          DAG.getValueType(N0.getValueType()));
5069     }
5070   }
5071
5072   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5073   // None of the supported targets knows how to perform load and sign extend
5074   // on vectors in one instruction.  We only perform this transformation on
5075   // scalars.
5076   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5077       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5078       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5079        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5080     bool DoXform = true;
5081     SmallVector<SDNode*, 4> SetCCs;
5082     if (!N0.hasOneUse())
5083       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5084     if (DoXform) {
5085       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5086       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5087                                        LN0->getChain(),
5088                                        LN0->getBasePtr(), N0.getValueType(),
5089                                        LN0->getMemOperand());
5090       CombineTo(N, ExtLoad);
5091       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5092                                   N0.getValueType(), ExtLoad);
5093       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5094       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5095                       ISD::SIGN_EXTEND);
5096       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5097     }
5098   }
5099
5100   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5101   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5102   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5103       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5104     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5105     EVT MemVT = LN0->getMemoryVT();
5106     if ((!LegalOperations && !LN0->isVolatile()) ||
5107         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5108       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5109                                        LN0->getChain(),
5110                                        LN0->getBasePtr(), MemVT,
5111                                        LN0->getMemOperand());
5112       CombineTo(N, ExtLoad);
5113       CombineTo(N0.getNode(),
5114                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5115                             N0.getValueType(), ExtLoad),
5116                 ExtLoad.getValue(1));
5117       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5118     }
5119   }
5120
5121   // fold (sext (and/or/xor (load x), cst)) ->
5122   //      (and/or/xor (sextload x), (sext cst))
5123   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5124        N0.getOpcode() == ISD::XOR) &&
5125       isa<LoadSDNode>(N0.getOperand(0)) &&
5126       N0.getOperand(1).getOpcode() == ISD::Constant &&
5127       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5128       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5129     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5130     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5131       bool DoXform = true;
5132       SmallVector<SDNode*, 4> SetCCs;
5133       if (!N0.hasOneUse())
5134         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5135                                           SetCCs, TLI);
5136       if (DoXform) {
5137         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5138                                          LN0->getChain(), LN0->getBasePtr(),
5139                                          LN0->getMemoryVT(),
5140                                          LN0->getMemOperand());
5141         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5142         Mask = Mask.sext(VT.getSizeInBits());
5143         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5144                                   ExtLoad, DAG.getConstant(Mask, VT));
5145         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5146                                     SDLoc(N0.getOperand(0)),
5147                                     N0.getOperand(0).getValueType(), ExtLoad);
5148         CombineTo(N, And);
5149         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5150         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5151                         ISD::SIGN_EXTEND);
5152         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5153       }
5154     }
5155   }
5156
5157   if (N0.getOpcode() == ISD::SETCC) {
5158     EVT N0VT = N0.getOperand(0).getValueType();
5159     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5160     // Only do this before legalize for now.
5161     if (VT.isVector() && !LegalOperations &&
5162         TLI.getBooleanContents(N0VT) ==
5163             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5164       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5165       // of the same size as the compared operands. Only optimize sext(setcc())
5166       // if this is the case.
5167       EVT SVT = getSetCCResultType(N0VT);
5168
5169       // We know that the # elements of the results is the same as the
5170       // # elements of the compare (and the # elements of the compare result
5171       // for that matter).  Check to see that they are the same size.  If so,
5172       // we know that the element size of the sext'd result matches the
5173       // element size of the compare operands.
5174       if (VT.getSizeInBits() == SVT.getSizeInBits())
5175         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5176                              N0.getOperand(1),
5177                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5178
5179       // If the desired elements are smaller or larger than the source
5180       // elements we can use a matching integer vector type and then
5181       // truncate/sign extend
5182       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5183       if (SVT == MatchingVectorType) {
5184         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5185                                N0.getOperand(0), N0.getOperand(1),
5186                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5187         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5188       }
5189     }
5190
5191     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5192     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5193     SDValue NegOne =
5194       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5195     SDValue SCC =
5196       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5197                        NegOne, DAG.getConstant(0, VT),
5198                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5199     if (SCC.getNode()) return SCC;
5200
5201     if (!VT.isVector()) {
5202       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5203       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5204         SDLoc DL(N);
5205         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5206         SDValue SetCC = DAG.getSetCC(DL,
5207                                      SetCCVT,
5208                                      N0.getOperand(0), N0.getOperand(1), CC);
5209         EVT SelectVT = getSetCCResultType(VT);
5210         return DAG.getSelect(DL, VT,
5211                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5212                              NegOne, DAG.getConstant(0, VT));
5213
5214       }
5215     }
5216   }
5217
5218   // fold (sext x) -> (zext x) if the sign bit is known zero.
5219   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5220       DAG.SignBitIsZero(N0))
5221     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5222
5223   return SDValue();
5224 }
5225
5226 // isTruncateOf - If N is a truncate of some other value, return true, record
5227 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5228 // This function computes KnownZero to avoid a duplicated call to
5229 // computeKnownBits in the caller.
5230 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5231                          APInt &KnownZero) {
5232   APInt KnownOne;
5233   if (N->getOpcode() == ISD::TRUNCATE) {
5234     Op = N->getOperand(0);
5235     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5236     return true;
5237   }
5238
5239   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5240       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5241     return false;
5242
5243   SDValue Op0 = N->getOperand(0);
5244   SDValue Op1 = N->getOperand(1);
5245   assert(Op0.getValueType() == Op1.getValueType());
5246
5247   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5248   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5249   if (COp0 && COp0->isNullValue())
5250     Op = Op1;
5251   else if (COp1 && COp1->isNullValue())
5252     Op = Op0;
5253   else
5254     return false;
5255
5256   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5257
5258   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5259     return false;
5260
5261   return true;
5262 }
5263
5264 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5265   SDValue N0 = N->getOperand(0);
5266   EVT VT = N->getValueType(0);
5267
5268   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5269                                               LegalOperations))
5270     return SDValue(Res, 0);
5271
5272   // fold (zext (zext x)) -> (zext x)
5273   // fold (zext (aext x)) -> (zext x)
5274   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5275     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5276                        N0.getOperand(0));
5277
5278   // fold (zext (truncate x)) -> (zext x) or
5279   //      (zext (truncate x)) -> (truncate x)
5280   // This is valid when the truncated bits of x are already zero.
5281   // FIXME: We should extend this to work for vectors too.
5282   SDValue Op;
5283   APInt KnownZero;
5284   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5285     APInt TruncatedBits =
5286       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5287       APInt(Op.getValueSizeInBits(), 0) :
5288       APInt::getBitsSet(Op.getValueSizeInBits(),
5289                         N0.getValueSizeInBits(),
5290                         std::min(Op.getValueSizeInBits(),
5291                                  VT.getSizeInBits()));
5292     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5293       if (VT.bitsGT(Op.getValueType()))
5294         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5295       if (VT.bitsLT(Op.getValueType()))
5296         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5297
5298       return Op;
5299     }
5300   }
5301
5302   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5303   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5304   if (N0.getOpcode() == ISD::TRUNCATE) {
5305     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5306     if (NarrowLoad.getNode()) {
5307       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5308       if (NarrowLoad.getNode() != N0.getNode()) {
5309         CombineTo(N0.getNode(), NarrowLoad);
5310         // CombineTo deleted the truncate, if needed, but not what's under it.
5311         AddToWorklist(oye);
5312       }
5313       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5314     }
5315   }
5316
5317   // fold (zext (truncate x)) -> (and x, mask)
5318   if (N0.getOpcode() == ISD::TRUNCATE &&
5319       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5320
5321     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5322     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5323     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5324     if (NarrowLoad.getNode()) {
5325       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5326       if (NarrowLoad.getNode() != N0.getNode()) {
5327         CombineTo(N0.getNode(), NarrowLoad);
5328         // CombineTo deleted the truncate, if needed, but not what's under it.
5329         AddToWorklist(oye);
5330       }
5331       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5332     }
5333
5334     SDValue Op = N0.getOperand(0);
5335     if (Op.getValueType().bitsLT(VT)) {
5336       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5337       AddToWorklist(Op.getNode());
5338     } else if (Op.getValueType().bitsGT(VT)) {
5339       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5340       AddToWorklist(Op.getNode());
5341     }
5342     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5343                                   N0.getValueType().getScalarType());
5344   }
5345
5346   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5347   // if either of the casts is not free.
5348   if (N0.getOpcode() == ISD::AND &&
5349       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5350       N0.getOperand(1).getOpcode() == ISD::Constant &&
5351       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5352                            N0.getValueType()) ||
5353        !TLI.isZExtFree(N0.getValueType(), VT))) {
5354     SDValue X = N0.getOperand(0).getOperand(0);
5355     if (X.getValueType().bitsLT(VT)) {
5356       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5357     } else if (X.getValueType().bitsGT(VT)) {
5358       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5359     }
5360     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5361     Mask = Mask.zext(VT.getSizeInBits());
5362     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5363                        X, DAG.getConstant(Mask, VT));
5364   }
5365
5366   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5367   // None of the supported targets knows how to perform load and vector_zext
5368   // on vectors in one instruction.  We only perform this transformation on
5369   // scalars.
5370   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5371       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5372       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5373        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5374     bool DoXform = true;
5375     SmallVector<SDNode*, 4> SetCCs;
5376     if (!N0.hasOneUse())
5377       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5378     if (DoXform) {
5379       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5380       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5381                                        LN0->getChain(),
5382                                        LN0->getBasePtr(), N0.getValueType(),
5383                                        LN0->getMemOperand());
5384       CombineTo(N, ExtLoad);
5385       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5386                                   N0.getValueType(), ExtLoad);
5387       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5388
5389       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5390                       ISD::ZERO_EXTEND);
5391       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5392     }
5393   }
5394
5395   // fold (zext (and/or/xor (load x), cst)) ->
5396   //      (and/or/xor (zextload x), (zext cst))
5397   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5398        N0.getOpcode() == ISD::XOR) &&
5399       isa<LoadSDNode>(N0.getOperand(0)) &&
5400       N0.getOperand(1).getOpcode() == ISD::Constant &&
5401       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5402       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5403     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5404     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5405       bool DoXform = true;
5406       SmallVector<SDNode*, 4> SetCCs;
5407       if (!N0.hasOneUse())
5408         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5409                                           SetCCs, TLI);
5410       if (DoXform) {
5411         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5412                                          LN0->getChain(), LN0->getBasePtr(),
5413                                          LN0->getMemoryVT(),
5414                                          LN0->getMemOperand());
5415         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5416         Mask = Mask.zext(VT.getSizeInBits());
5417         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5418                                   ExtLoad, DAG.getConstant(Mask, VT));
5419         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5420                                     SDLoc(N0.getOperand(0)),
5421                                     N0.getOperand(0).getValueType(), ExtLoad);
5422         CombineTo(N, And);
5423         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5424         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5425                         ISD::ZERO_EXTEND);
5426         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5427       }
5428     }
5429   }
5430
5431   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5432   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5433   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5434       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5435     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5436     EVT MemVT = LN0->getMemoryVT();
5437     if ((!LegalOperations && !LN0->isVolatile()) ||
5438         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5439       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5440                                        LN0->getChain(),
5441                                        LN0->getBasePtr(), MemVT,
5442                                        LN0->getMemOperand());
5443       CombineTo(N, ExtLoad);
5444       CombineTo(N0.getNode(),
5445                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5446                             ExtLoad),
5447                 ExtLoad.getValue(1));
5448       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5449     }
5450   }
5451
5452   if (N0.getOpcode() == ISD::SETCC) {
5453     if (!LegalOperations && VT.isVector() &&
5454         N0.getValueType().getVectorElementType() == MVT::i1) {
5455       EVT N0VT = N0.getOperand(0).getValueType();
5456       if (getSetCCResultType(N0VT) == N0.getValueType())
5457         return SDValue();
5458
5459       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5460       // Only do this before legalize for now.
5461       EVT EltVT = VT.getVectorElementType();
5462       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5463                                     DAG.getConstant(1, EltVT));
5464       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5465         // We know that the # elements of the results is the same as the
5466         // # elements of the compare (and the # elements of the compare result
5467         // for that matter).  Check to see that they are the same size.  If so,
5468         // we know that the element size of the sext'd result matches the
5469         // element size of the compare operands.
5470         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5471                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5472                                          N0.getOperand(1),
5473                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5474                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5475                                        OneOps));
5476
5477       // If the desired elements are smaller or larger than the source
5478       // elements we can use a matching integer vector type and then
5479       // truncate/sign extend
5480       EVT MatchingElementType =
5481         EVT::getIntegerVT(*DAG.getContext(),
5482                           N0VT.getScalarType().getSizeInBits());
5483       EVT MatchingVectorType =
5484         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5485                          N0VT.getVectorNumElements());
5486       SDValue VsetCC =
5487         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5488                       N0.getOperand(1),
5489                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5490       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5491                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5492                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5493     }
5494
5495     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5496     SDValue SCC =
5497       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5498                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5499                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5500     if (SCC.getNode()) return SCC;
5501   }
5502
5503   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5504   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5505       isa<ConstantSDNode>(N0.getOperand(1)) &&
5506       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5507       N0.hasOneUse()) {
5508     SDValue ShAmt = N0.getOperand(1);
5509     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5510     if (N0.getOpcode() == ISD::SHL) {
5511       SDValue InnerZExt = N0.getOperand(0);
5512       // If the original shl may be shifting out bits, do not perform this
5513       // transformation.
5514       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5515         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5516       if (ShAmtVal > KnownZeroBits)
5517         return SDValue();
5518     }
5519
5520     SDLoc DL(N);
5521
5522     // Ensure that the shift amount is wide enough for the shifted value.
5523     if (VT.getSizeInBits() >= 256)
5524       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5525
5526     return DAG.getNode(N0.getOpcode(), DL, VT,
5527                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5528                        ShAmt);
5529   }
5530
5531   return SDValue();
5532 }
5533
5534 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5535   SDValue N0 = N->getOperand(0);
5536   EVT VT = N->getValueType(0);
5537
5538   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5539                                               LegalOperations))
5540     return SDValue(Res, 0);
5541
5542   // fold (aext (aext x)) -> (aext x)
5543   // fold (aext (zext x)) -> (zext x)
5544   // fold (aext (sext x)) -> (sext x)
5545   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5546       N0.getOpcode() == ISD::ZERO_EXTEND ||
5547       N0.getOpcode() == ISD::SIGN_EXTEND)
5548     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5549
5550   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5551   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5552   if (N0.getOpcode() == ISD::TRUNCATE) {
5553     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5554     if (NarrowLoad.getNode()) {
5555       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5556       if (NarrowLoad.getNode() != N0.getNode()) {
5557         CombineTo(N0.getNode(), NarrowLoad);
5558         // CombineTo deleted the truncate, if needed, but not what's under it.
5559         AddToWorklist(oye);
5560       }
5561       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5562     }
5563   }
5564
5565   // fold (aext (truncate x))
5566   if (N0.getOpcode() == ISD::TRUNCATE) {
5567     SDValue TruncOp = N0.getOperand(0);
5568     if (TruncOp.getValueType() == VT)
5569       return TruncOp; // x iff x size == zext size.
5570     if (TruncOp.getValueType().bitsGT(VT))
5571       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5572     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5573   }
5574
5575   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5576   // if the trunc is not free.
5577   if (N0.getOpcode() == ISD::AND &&
5578       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5579       N0.getOperand(1).getOpcode() == ISD::Constant &&
5580       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5581                           N0.getValueType())) {
5582     SDValue X = N0.getOperand(0).getOperand(0);
5583     if (X.getValueType().bitsLT(VT)) {
5584       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5585     } else if (X.getValueType().bitsGT(VT)) {
5586       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5587     }
5588     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5589     Mask = Mask.zext(VT.getSizeInBits());
5590     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5591                        X, DAG.getConstant(Mask, VT));
5592   }
5593
5594   // fold (aext (load x)) -> (aext (truncate (extload x)))
5595   // None of the supported targets knows how to perform load and any_ext
5596   // on vectors in one instruction.  We only perform this transformation on
5597   // scalars.
5598   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5599       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5600       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5601     bool DoXform = true;
5602     SmallVector<SDNode*, 4> SetCCs;
5603     if (!N0.hasOneUse())
5604       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5605     if (DoXform) {
5606       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5607       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5608                                        LN0->getChain(),
5609                                        LN0->getBasePtr(), N0.getValueType(),
5610                                        LN0->getMemOperand());
5611       CombineTo(N, ExtLoad);
5612       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5613                                   N0.getValueType(), ExtLoad);
5614       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5615       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5616                       ISD::ANY_EXTEND);
5617       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5618     }
5619   }
5620
5621   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5622   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5623   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5624   if (N0.getOpcode() == ISD::LOAD &&
5625       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5626       N0.hasOneUse()) {
5627     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5628     ISD::LoadExtType ExtType = LN0->getExtensionType();
5629     EVT MemVT = LN0->getMemoryVT();
5630     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5631       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5632                                        VT, LN0->getChain(), LN0->getBasePtr(),
5633                                        MemVT, LN0->getMemOperand());
5634       CombineTo(N, ExtLoad);
5635       CombineTo(N0.getNode(),
5636                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5637                             N0.getValueType(), ExtLoad),
5638                 ExtLoad.getValue(1));
5639       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5640     }
5641   }
5642
5643   if (N0.getOpcode() == ISD::SETCC) {
5644     // For vectors:
5645     // aext(setcc) -> vsetcc
5646     // aext(setcc) -> truncate(vsetcc)
5647     // aext(setcc) -> aext(vsetcc)
5648     // Only do this before legalize for now.
5649     if (VT.isVector() && !LegalOperations) {
5650       EVT N0VT = N0.getOperand(0).getValueType();
5651         // We know that the # elements of the results is the same as the
5652         // # elements of the compare (and the # elements of the compare result
5653         // for that matter).  Check to see that they are the same size.  If so,
5654         // we know that the element size of the sext'd result matches the
5655         // element size of the compare operands.
5656       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5657         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5658                              N0.getOperand(1),
5659                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5660       // If the desired elements are smaller or larger than the source
5661       // elements we can use a matching integer vector type and then
5662       // truncate/any extend
5663       else {
5664         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5665         SDValue VsetCC =
5666           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5667                         N0.getOperand(1),
5668                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5669         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5670       }
5671     }
5672
5673     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5674     SDValue SCC =
5675       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5676                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5677                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5678     if (SCC.getNode())
5679       return SCC;
5680   }
5681
5682   return SDValue();
5683 }
5684
5685 /// See if the specified operand can be simplified with the knowledge that only
5686 /// the bits specified by Mask are used.  If so, return the simpler operand,
5687 /// otherwise return a null SDValue.
5688 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5689   switch (V.getOpcode()) {
5690   default: break;
5691   case ISD::Constant: {
5692     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5693     assert(CV && "Const value should be ConstSDNode.");
5694     const APInt &CVal = CV->getAPIntValue();
5695     APInt NewVal = CVal & Mask;
5696     if (NewVal != CVal)
5697       return DAG.getConstant(NewVal, V.getValueType());
5698     break;
5699   }
5700   case ISD::OR:
5701   case ISD::XOR:
5702     // If the LHS or RHS don't contribute bits to the or, drop them.
5703     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5704       return V.getOperand(1);
5705     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5706       return V.getOperand(0);
5707     break;
5708   case ISD::SRL:
5709     // Only look at single-use SRLs.
5710     if (!V.getNode()->hasOneUse())
5711       break;
5712     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5713       // See if we can recursively simplify the LHS.
5714       unsigned Amt = RHSC->getZExtValue();
5715
5716       // Watch out for shift count overflow though.
5717       if (Amt >= Mask.getBitWidth()) break;
5718       APInt NewMask = Mask << Amt;
5719       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5720       if (SimplifyLHS.getNode())
5721         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5722                            SimplifyLHS, V.getOperand(1));
5723     }
5724   }
5725   return SDValue();
5726 }
5727
5728 /// If the result of a wider load is shifted to right of N  bits and then
5729 /// truncated to a narrower type and where N is a multiple of number of bits of
5730 /// the narrower type, transform it to a narrower load from address + N / num of
5731 /// bits of new type. If the result is to be extended, also fold the extension
5732 /// to form a extending load.
5733 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5734   unsigned Opc = N->getOpcode();
5735
5736   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5737   SDValue N0 = N->getOperand(0);
5738   EVT VT = N->getValueType(0);
5739   EVT ExtVT = VT;
5740
5741   // This transformation isn't valid for vector loads.
5742   if (VT.isVector())
5743     return SDValue();
5744
5745   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5746   // extended to VT.
5747   if (Opc == ISD::SIGN_EXTEND_INREG) {
5748     ExtType = ISD::SEXTLOAD;
5749     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5750   } else if (Opc == ISD::SRL) {
5751     // Another special-case: SRL is basically zero-extending a narrower value.
5752     ExtType = ISD::ZEXTLOAD;
5753     N0 = SDValue(N, 0);
5754     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5755     if (!N01) return SDValue();
5756     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5757                               VT.getSizeInBits() - N01->getZExtValue());
5758   }
5759   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5760     return SDValue();
5761
5762   unsigned EVTBits = ExtVT.getSizeInBits();
5763
5764   // Do not generate loads of non-round integer types since these can
5765   // be expensive (and would be wrong if the type is not byte sized).
5766   if (!ExtVT.isRound())
5767     return SDValue();
5768
5769   unsigned ShAmt = 0;
5770   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5771     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5772       ShAmt = N01->getZExtValue();
5773       // Is the shift amount a multiple of size of VT?
5774       if ((ShAmt & (EVTBits-1)) == 0) {
5775         N0 = N0.getOperand(0);
5776         // Is the load width a multiple of size of VT?
5777         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5778           return SDValue();
5779       }
5780
5781       // At this point, we must have a load or else we can't do the transform.
5782       if (!isa<LoadSDNode>(N0)) return SDValue();
5783
5784       // Because a SRL must be assumed to *need* to zero-extend the high bits
5785       // (as opposed to anyext the high bits), we can't combine the zextload
5786       // lowering of SRL and an sextload.
5787       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5788         return SDValue();
5789
5790       // If the shift amount is larger than the input type then we're not
5791       // accessing any of the loaded bytes.  If the load was a zextload/extload
5792       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5793       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5794         return SDValue();
5795     }
5796   }
5797
5798   // If the load is shifted left (and the result isn't shifted back right),
5799   // we can fold the truncate through the shift.
5800   unsigned ShLeftAmt = 0;
5801   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5802       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5803     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5804       ShLeftAmt = N01->getZExtValue();
5805       N0 = N0.getOperand(0);
5806     }
5807   }
5808
5809   // If we haven't found a load, we can't narrow it.  Don't transform one with
5810   // multiple uses, this would require adding a new load.
5811   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5812     return SDValue();
5813
5814   // Don't change the width of a volatile load.
5815   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5816   if (LN0->isVolatile())
5817     return SDValue();
5818
5819   // Verify that we are actually reducing a load width here.
5820   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5821     return SDValue();
5822
5823   // For the transform to be legal, the load must produce only two values
5824   // (the value loaded and the chain).  Don't transform a pre-increment
5825   // load, for example, which produces an extra value.  Otherwise the
5826   // transformation is not equivalent, and the downstream logic to replace
5827   // uses gets things wrong.
5828   if (LN0->getNumValues() > 2)
5829     return SDValue();
5830
5831   // If the load that we're shrinking is an extload and we're not just
5832   // discarding the extension we can't simply shrink the load. Bail.
5833   // TODO: It would be possible to merge the extensions in some cases.
5834   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5835       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5836     return SDValue();
5837
5838   EVT PtrType = N0.getOperand(1).getValueType();
5839
5840   if (PtrType == MVT::Untyped || PtrType.isExtended())
5841     // It's not possible to generate a constant of extended or untyped type.
5842     return SDValue();
5843
5844   // For big endian targets, we need to adjust the offset to the pointer to
5845   // load the correct bytes.
5846   if (TLI.isBigEndian()) {
5847     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5848     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5849     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5850   }
5851
5852   uint64_t PtrOff = ShAmt / 8;
5853   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5854   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5855                                PtrType, LN0->getBasePtr(),
5856                                DAG.getConstant(PtrOff, PtrType));
5857   AddToWorklist(NewPtr.getNode());
5858
5859   SDValue Load;
5860   if (ExtType == ISD::NON_EXTLOAD)
5861     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5862                         LN0->getPointerInfo().getWithOffset(PtrOff),
5863                         LN0->isVolatile(), LN0->isNonTemporal(),
5864                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5865   else
5866     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5867                           LN0->getPointerInfo().getWithOffset(PtrOff),
5868                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5869                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5870
5871   // Replace the old load's chain with the new load's chain.
5872   WorklistRemover DeadNodes(*this);
5873   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5874
5875   // Shift the result left, if we've swallowed a left shift.
5876   SDValue Result = Load;
5877   if (ShLeftAmt != 0) {
5878     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5879     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5880       ShImmTy = VT;
5881     // If the shift amount is as large as the result size (but, presumably,
5882     // no larger than the source) then the useful bits of the result are
5883     // zero; we can't simply return the shortened shift, because the result
5884     // of that operation is undefined.
5885     if (ShLeftAmt >= VT.getSizeInBits())
5886       Result = DAG.getConstant(0, VT);
5887     else
5888       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5889                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5890   }
5891
5892   // Return the new loaded value.
5893   return Result;
5894 }
5895
5896 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5897   SDValue N0 = N->getOperand(0);
5898   SDValue N1 = N->getOperand(1);
5899   EVT VT = N->getValueType(0);
5900   EVT EVT = cast<VTSDNode>(N1)->getVT();
5901   unsigned VTBits = VT.getScalarType().getSizeInBits();
5902   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5903
5904   // fold (sext_in_reg c1) -> c1
5905   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5906     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5907
5908   // If the input is already sign extended, just drop the extension.
5909   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5910     return N0;
5911
5912   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5913   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5914       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5915     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5916                        N0.getOperand(0), N1);
5917
5918   // fold (sext_in_reg (sext x)) -> (sext x)
5919   // fold (sext_in_reg (aext x)) -> (sext x)
5920   // if x is small enough.
5921   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5922     SDValue N00 = N0.getOperand(0);
5923     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5924         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5925       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5926   }
5927
5928   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5929   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5930     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5931
5932   // fold operands of sext_in_reg based on knowledge that the top bits are not
5933   // demanded.
5934   if (SimplifyDemandedBits(SDValue(N, 0)))
5935     return SDValue(N, 0);
5936
5937   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5938   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5939   SDValue NarrowLoad = ReduceLoadWidth(N);
5940   if (NarrowLoad.getNode())
5941     return NarrowLoad;
5942
5943   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5944   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5945   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5946   if (N0.getOpcode() == ISD::SRL) {
5947     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5948       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5949         // We can turn this into an SRA iff the input to the SRL is already sign
5950         // extended enough.
5951         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5952         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5953           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5954                              N0.getOperand(0), N0.getOperand(1));
5955       }
5956   }
5957
5958   // fold (sext_inreg (extload x)) -> (sextload x)
5959   if (ISD::isEXTLoad(N0.getNode()) &&
5960       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5961       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5962       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5963        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5964     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5965     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5966                                      LN0->getChain(),
5967                                      LN0->getBasePtr(), EVT,
5968                                      LN0->getMemOperand());
5969     CombineTo(N, ExtLoad);
5970     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5971     AddToWorklist(ExtLoad.getNode());
5972     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5973   }
5974   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5975   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5976       N0.hasOneUse() &&
5977       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5978       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5979        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5980     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5981     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5982                                      LN0->getChain(),
5983                                      LN0->getBasePtr(), EVT,
5984                                      LN0->getMemOperand());
5985     CombineTo(N, ExtLoad);
5986     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5987     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5988   }
5989
5990   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5991   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5992     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5993                                        N0.getOperand(1), false);
5994     if (BSwap.getNode())
5995       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5996                          BSwap, N1);
5997   }
5998
5999   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6000   // into a build_vector.
6001   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6002     SmallVector<SDValue, 8> Elts;
6003     unsigned NumElts = N0->getNumOperands();
6004     unsigned ShAmt = VTBits - EVTBits;
6005
6006     for (unsigned i = 0; i != NumElts; ++i) {
6007       SDValue Op = N0->getOperand(i);
6008       if (Op->getOpcode() == ISD::UNDEF) {
6009         Elts.push_back(Op);
6010         continue;
6011       }
6012
6013       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6014       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6015       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6016                                      Op.getValueType()));
6017     }
6018
6019     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6020   }
6021
6022   return SDValue();
6023 }
6024
6025 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6026   SDValue N0 = N->getOperand(0);
6027   EVT VT = N->getValueType(0);
6028   bool isLE = TLI.isLittleEndian();
6029
6030   // noop truncate
6031   if (N0.getValueType() == N->getValueType(0))
6032     return N0;
6033   // fold (truncate c1) -> c1
6034   if (isa<ConstantSDNode>(N0))
6035     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6036   // fold (truncate (truncate x)) -> (truncate x)
6037   if (N0.getOpcode() == ISD::TRUNCATE)
6038     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6039   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6040   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6041       N0.getOpcode() == ISD::SIGN_EXTEND ||
6042       N0.getOpcode() == ISD::ANY_EXTEND) {
6043     if (N0.getOperand(0).getValueType().bitsLT(VT))
6044       // if the source is smaller than the dest, we still need an extend
6045       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6046                          N0.getOperand(0));
6047     if (N0.getOperand(0).getValueType().bitsGT(VT))
6048       // if the source is larger than the dest, than we just need the truncate
6049       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6050     // if the source and dest are the same type, we can drop both the extend
6051     // and the truncate.
6052     return N0.getOperand(0);
6053   }
6054
6055   // Fold extract-and-trunc into a narrow extract. For example:
6056   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6057   //   i32 y = TRUNCATE(i64 x)
6058   //        -- becomes --
6059   //   v16i8 b = BITCAST (v2i64 val)
6060   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6061   //
6062   // Note: We only run this optimization after type legalization (which often
6063   // creates this pattern) and before operation legalization after which
6064   // we need to be more careful about the vector instructions that we generate.
6065   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6066       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6067
6068     EVT VecTy = N0.getOperand(0).getValueType();
6069     EVT ExTy = N0.getValueType();
6070     EVT TrTy = N->getValueType(0);
6071
6072     unsigned NumElem = VecTy.getVectorNumElements();
6073     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6074
6075     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6076     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6077
6078     SDValue EltNo = N0->getOperand(1);
6079     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6080       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6081       EVT IndexTy = TLI.getVectorIdxTy();
6082       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6083
6084       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6085                               NVT, N0.getOperand(0));
6086
6087       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6088                          SDLoc(N), TrTy, V,
6089                          DAG.getConstant(Index, IndexTy));
6090     }
6091   }
6092
6093   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6094   if (N0.getOpcode() == ISD::SELECT) {
6095     EVT SrcVT = N0.getValueType();
6096     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6097         TLI.isTruncateFree(SrcVT, VT)) {
6098       SDLoc SL(N0);
6099       SDValue Cond = N0.getOperand(0);
6100       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6101       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6102       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6103     }
6104   }
6105
6106   // Fold a series of buildvector, bitcast, and truncate if possible.
6107   // For example fold
6108   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6109   //   (2xi32 (buildvector x, y)).
6110   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6111       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6112       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6113       N0.getOperand(0).hasOneUse()) {
6114
6115     SDValue BuildVect = N0.getOperand(0);
6116     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6117     EVT TruncVecEltTy = VT.getVectorElementType();
6118
6119     // Check that the element types match.
6120     if (BuildVectEltTy == TruncVecEltTy) {
6121       // Now we only need to compute the offset of the truncated elements.
6122       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6123       unsigned TruncVecNumElts = VT.getVectorNumElements();
6124       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6125
6126       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6127              "Invalid number of elements");
6128
6129       SmallVector<SDValue, 8> Opnds;
6130       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6131         Opnds.push_back(BuildVect.getOperand(i));
6132
6133       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6134     }
6135   }
6136
6137   // See if we can simplify the input to this truncate through knowledge that
6138   // only the low bits are being used.
6139   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6140   // Currently we only perform this optimization on scalars because vectors
6141   // may have different active low bits.
6142   if (!VT.isVector()) {
6143     SDValue Shorter =
6144       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6145                                                VT.getSizeInBits()));
6146     if (Shorter.getNode())
6147       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6148   }
6149   // fold (truncate (load x)) -> (smaller load x)
6150   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6151   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6152     SDValue Reduced = ReduceLoadWidth(N);
6153     if (Reduced.getNode())
6154       return Reduced;
6155     // Handle the case where the load remains an extending load even
6156     // after truncation.
6157     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6158       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6159       if (!LN0->isVolatile() &&
6160           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6161         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6162                                          VT, LN0->getChain(), LN0->getBasePtr(),
6163                                          LN0->getMemoryVT(),
6164                                          LN0->getMemOperand());
6165         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6166         return NewLoad;
6167       }
6168     }
6169   }
6170   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6171   // where ... are all 'undef'.
6172   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6173     SmallVector<EVT, 8> VTs;
6174     SDValue V;
6175     unsigned Idx = 0;
6176     unsigned NumDefs = 0;
6177
6178     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6179       SDValue X = N0.getOperand(i);
6180       if (X.getOpcode() != ISD::UNDEF) {
6181         V = X;
6182         Idx = i;
6183         NumDefs++;
6184       }
6185       // Stop if more than one members are non-undef.
6186       if (NumDefs > 1)
6187         break;
6188       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6189                                      VT.getVectorElementType(),
6190                                      X.getValueType().getVectorNumElements()));
6191     }
6192
6193     if (NumDefs == 0)
6194       return DAG.getUNDEF(VT);
6195
6196     if (NumDefs == 1) {
6197       assert(V.getNode() && "The single defined operand is empty!");
6198       SmallVector<SDValue, 8> Opnds;
6199       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6200         if (i != Idx) {
6201           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6202           continue;
6203         }
6204         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6205         AddToWorklist(NV.getNode());
6206         Opnds.push_back(NV);
6207       }
6208       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6209     }
6210   }
6211
6212   // Simplify the operands using demanded-bits information.
6213   if (!VT.isVector() &&
6214       SimplifyDemandedBits(SDValue(N, 0)))
6215     return SDValue(N, 0);
6216
6217   return SDValue();
6218 }
6219
6220 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6221   SDValue Elt = N->getOperand(i);
6222   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6223     return Elt.getNode();
6224   return Elt.getOperand(Elt.getResNo()).getNode();
6225 }
6226
6227 /// build_pair (load, load) -> load
6228 /// if load locations are consecutive.
6229 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6230   assert(N->getOpcode() == ISD::BUILD_PAIR);
6231
6232   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6233   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6234   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6235       LD1->getAddressSpace() != LD2->getAddressSpace())
6236     return SDValue();
6237   EVT LD1VT = LD1->getValueType(0);
6238
6239   if (ISD::isNON_EXTLoad(LD2) &&
6240       LD2->hasOneUse() &&
6241       // If both are volatile this would reduce the number of volatile loads.
6242       // If one is volatile it might be ok, but play conservative and bail out.
6243       !LD1->isVolatile() &&
6244       !LD2->isVolatile() &&
6245       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6246     unsigned Align = LD1->getAlignment();
6247     unsigned NewAlign = TLI.getDataLayout()->
6248       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6249
6250     if (NewAlign <= Align &&
6251         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6252       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6253                          LD1->getBasePtr(), LD1->getPointerInfo(),
6254                          false, false, false, Align);
6255   }
6256
6257   return SDValue();
6258 }
6259
6260 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6261   SDValue N0 = N->getOperand(0);
6262   EVT VT = N->getValueType(0);
6263
6264   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6265   // Only do this before legalize, since afterward the target may be depending
6266   // on the bitconvert.
6267   // First check to see if this is all constant.
6268   if (!LegalTypes &&
6269       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6270       VT.isVector()) {
6271     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6272
6273     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6274     assert(!DestEltVT.isVector() &&
6275            "Element type of vector ValueType must not be vector!");
6276     if (isSimple)
6277       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6278   }
6279
6280   // If the input is a constant, let getNode fold it.
6281   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6282     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6283     if (Res.getNode() != N) {
6284       if (!LegalOperations ||
6285           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6286         return Res;
6287
6288       // Folding it resulted in an illegal node, and it's too late to
6289       // do that. Clean up the old node and forego the transformation.
6290       // Ideally this won't happen very often, because instcombine
6291       // and the earlier dagcombine runs (where illegal nodes are
6292       // permitted) should have folded most of them already.
6293       deleteAndRecombine(Res.getNode());
6294     }
6295   }
6296
6297   // (conv (conv x, t1), t2) -> (conv x, t2)
6298   if (N0.getOpcode() == ISD::BITCAST)
6299     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6300                        N0.getOperand(0));
6301
6302   // fold (conv (load x)) -> (load (conv*)x)
6303   // If the resultant load doesn't need a higher alignment than the original!
6304   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6305       // Do not change the width of a volatile load.
6306       !cast<LoadSDNode>(N0)->isVolatile() &&
6307       // Do not remove the cast if the types differ in endian layout.
6308       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6309       TLI.hasBigEndianPartOrdering(VT) &&
6310       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6311       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6312     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6313     unsigned Align = TLI.getDataLayout()->
6314       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6315     unsigned OrigAlign = LN0->getAlignment();
6316
6317     if (Align <= OrigAlign) {
6318       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6319                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6320                                  LN0->isVolatile(), LN0->isNonTemporal(),
6321                                  LN0->isInvariant(), OrigAlign,
6322                                  LN0->getAAInfo());
6323       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6324       return Load;
6325     }
6326   }
6327
6328   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6329   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6330   // This often reduces constant pool loads.
6331   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6332        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6333       N0.getNode()->hasOneUse() && VT.isInteger() &&
6334       !VT.isVector() && !N0.getValueType().isVector()) {
6335     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6336                                   N0.getOperand(0));
6337     AddToWorklist(NewConv.getNode());
6338
6339     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6340     if (N0.getOpcode() == ISD::FNEG)
6341       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6342                          NewConv, DAG.getConstant(SignBit, VT));
6343     assert(N0.getOpcode() == ISD::FABS);
6344     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6345                        NewConv, DAG.getConstant(~SignBit, VT));
6346   }
6347
6348   // fold (bitconvert (fcopysign cst, x)) ->
6349   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6350   // Note that we don't handle (copysign x, cst) because this can always be
6351   // folded to an fneg or fabs.
6352   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6353       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6354       VT.isInteger() && !VT.isVector()) {
6355     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6356     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6357     if (isTypeLegal(IntXVT)) {
6358       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6359                               IntXVT, N0.getOperand(1));
6360       AddToWorklist(X.getNode());
6361
6362       // If X has a different width than the result/lhs, sext it or truncate it.
6363       unsigned VTWidth = VT.getSizeInBits();
6364       if (OrigXWidth < VTWidth) {
6365         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6366         AddToWorklist(X.getNode());
6367       } else if (OrigXWidth > VTWidth) {
6368         // To get the sign bit in the right place, we have to shift it right
6369         // before truncating.
6370         X = DAG.getNode(ISD::SRL, SDLoc(X),
6371                         X.getValueType(), X,
6372                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6373         AddToWorklist(X.getNode());
6374         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6375         AddToWorklist(X.getNode());
6376       }
6377
6378       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6379       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6380                       X, DAG.getConstant(SignBit, VT));
6381       AddToWorklist(X.getNode());
6382
6383       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6384                                 VT, N0.getOperand(0));
6385       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6386                         Cst, DAG.getConstant(~SignBit, VT));
6387       AddToWorklist(Cst.getNode());
6388
6389       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6390     }
6391   }
6392
6393   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6394   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6395     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6396     if (CombineLD.getNode())
6397       return CombineLD;
6398   }
6399
6400   return SDValue();
6401 }
6402
6403 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6404   EVT VT = N->getValueType(0);
6405   return CombineConsecutiveLoads(N, VT);
6406 }
6407
6408 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6409 /// operands. DstEltVT indicates the destination element value type.
6410 SDValue DAGCombiner::
6411 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6412   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6413
6414   // If this is already the right type, we're done.
6415   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6416
6417   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6418   unsigned DstBitSize = DstEltVT.getSizeInBits();
6419
6420   // If this is a conversion of N elements of one type to N elements of another
6421   // type, convert each element.  This handles FP<->INT cases.
6422   if (SrcBitSize == DstBitSize) {
6423     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6424                               BV->getValueType(0).getVectorNumElements());
6425
6426     // Due to the FP element handling below calling this routine recursively,
6427     // we can end up with a scalar-to-vector node here.
6428     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6429       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6430                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6431                                      DstEltVT, BV->getOperand(0)));
6432
6433     SmallVector<SDValue, 8> Ops;
6434     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6435       SDValue Op = BV->getOperand(i);
6436       // If the vector element type is not legal, the BUILD_VECTOR operands
6437       // are promoted and implicitly truncated.  Make that explicit here.
6438       if (Op.getValueType() != SrcEltVT)
6439         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6440       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6441                                 DstEltVT, Op));
6442       AddToWorklist(Ops.back().getNode());
6443     }
6444     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6445   }
6446
6447   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6448   // handle annoying details of growing/shrinking FP values, we convert them to
6449   // int first.
6450   if (SrcEltVT.isFloatingPoint()) {
6451     // Convert the input float vector to a int vector where the elements are the
6452     // same sizes.
6453     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6454     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6455     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6456     SrcEltVT = IntVT;
6457   }
6458
6459   // Now we know the input is an integer vector.  If the output is a FP type,
6460   // convert to integer first, then to FP of the right size.
6461   if (DstEltVT.isFloatingPoint()) {
6462     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6463     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6464     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6465
6466     // Next, convert to FP elements of the same size.
6467     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6468   }
6469
6470   // Okay, we know the src/dst types are both integers of differing types.
6471   // Handling growing first.
6472   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6473   if (SrcBitSize < DstBitSize) {
6474     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6475
6476     SmallVector<SDValue, 8> Ops;
6477     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6478          i += NumInputsPerOutput) {
6479       bool isLE = TLI.isLittleEndian();
6480       APInt NewBits = APInt(DstBitSize, 0);
6481       bool EltIsUndef = true;
6482       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6483         // Shift the previously computed bits over.
6484         NewBits <<= SrcBitSize;
6485         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6486         if (Op.getOpcode() == ISD::UNDEF) continue;
6487         EltIsUndef = false;
6488
6489         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6490                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6491       }
6492
6493       if (EltIsUndef)
6494         Ops.push_back(DAG.getUNDEF(DstEltVT));
6495       else
6496         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6497     }
6498
6499     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6500     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6501   }
6502
6503   // Finally, this must be the case where we are shrinking elements: each input
6504   // turns into multiple outputs.
6505   bool isS2V = ISD::isScalarToVector(BV);
6506   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6507   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6508                             NumOutputsPerInput*BV->getNumOperands());
6509   SmallVector<SDValue, 8> Ops;
6510
6511   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6512     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6513       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6514         Ops.push_back(DAG.getUNDEF(DstEltVT));
6515       continue;
6516     }
6517
6518     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6519                   getAPIntValue().zextOrTrunc(SrcBitSize);
6520
6521     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6522       APInt ThisVal = OpVal.trunc(DstBitSize);
6523       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6524       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6525         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6526         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6527                            Ops[0]);
6528       OpVal = OpVal.lshr(DstBitSize);
6529     }
6530
6531     // For big endian targets, swap the order of the pieces of each element.
6532     if (TLI.isBigEndian())
6533       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6534   }
6535
6536   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6537 }
6538
6539 SDValue DAGCombiner::visitFADD(SDNode *N) {
6540   SDValue N0 = N->getOperand(0);
6541   SDValue N1 = N->getOperand(1);
6542   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6543   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6544   EVT VT = N->getValueType(0);
6545   const TargetOptions &Options = DAG.getTarget().Options;
6546   
6547   // fold vector ops
6548   if (VT.isVector()) {
6549     SDValue FoldedVOp = SimplifyVBinOp(N);
6550     if (FoldedVOp.getNode()) return FoldedVOp;
6551   }
6552
6553   // fold (fadd c1, c2) -> c1 + c2
6554   if (N0CFP && N1CFP)
6555     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6556
6557   // canonicalize constant to RHS
6558   if (N0CFP && !N1CFP)
6559     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6560
6561   // fold (fadd A, (fneg B)) -> (fsub A, B)
6562   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6563       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6564     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6565                        GetNegatedExpression(N1, DAG, LegalOperations));
6566   
6567   // fold (fadd (fneg A), B) -> (fsub B, A)
6568   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6569       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6570     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6571                        GetNegatedExpression(N0, DAG, LegalOperations));
6572
6573   // If 'unsafe math' is enabled, fold lots of things.
6574   if (Options.UnsafeFPMath) {
6575     // No FP constant should be created after legalization as Instruction
6576     // Selection pass has a hard time dealing with FP constants.
6577     bool AllowNewConst = (Level < AfterLegalizeDAG);
6578     
6579     // fold (fadd A, 0) -> A
6580     if (N1CFP && N1CFP->getValueAPF().isZero())
6581       return N0;
6582
6583     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6584     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6585         isa<ConstantFPSDNode>(N0.getOperand(1)))
6586       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6587                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6588                                      N0.getOperand(1), N1));
6589     
6590     // If allowed, fold (fadd (fneg x), x) -> 0.0
6591     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6592       return DAG.getConstantFP(0.0, VT);
6593     
6594     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6595     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6596       return DAG.getConstantFP(0.0, VT);
6597     
6598     // We can fold chains of FADD's of the same value into multiplications.
6599     // This transform is not safe in general because we are reducing the number
6600     // of rounding steps.
6601     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6602       if (N0.getOpcode() == ISD::FMUL) {
6603         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6604         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6605         
6606         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6607         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6608           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6609                                        SDValue(CFP01, 0),
6610                                        DAG.getConstantFP(1.0, VT));
6611           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6612         }
6613         
6614         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6615         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6616             N1.getOperand(0) == N1.getOperand(1) &&
6617             N0.getOperand(0) == N1.getOperand(0)) {
6618           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6619                                        SDValue(CFP01, 0),
6620                                        DAG.getConstantFP(2.0, VT));
6621           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622                              N0.getOperand(0), NewCFP);
6623         }
6624       }
6625       
6626       if (N1.getOpcode() == ISD::FMUL) {
6627         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6628         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6629         
6630         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6631         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6632           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6633                                        SDValue(CFP11, 0),
6634                                        DAG.getConstantFP(1.0, VT));
6635           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6636         }
6637
6638         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6639         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6640             N0.getOperand(0) == N0.getOperand(1) &&
6641             N1.getOperand(0) == N0.getOperand(0)) {
6642           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6643                                        SDValue(CFP11, 0),
6644                                        DAG.getConstantFP(2.0, VT));
6645           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6646         }
6647       }
6648
6649       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6650         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6651         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6652         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6653             (N0.getOperand(0) == N1))
6654           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6655                              N1, DAG.getConstantFP(3.0, VT));
6656       }
6657       
6658       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6659         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6660         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6661         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6662             N1.getOperand(0) == N0)
6663           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6664                              N0, DAG.getConstantFP(3.0, VT));
6665       }
6666       
6667       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6668       if (AllowNewConst &&
6669           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6670           N0.getOperand(0) == N0.getOperand(1) &&
6671           N1.getOperand(0) == N1.getOperand(1) &&
6672           N0.getOperand(0) == N1.getOperand(0))
6673         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6674                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6675     }
6676   } // enable-unsafe-fp-math
6677   
6678   // FADD -> FMA combines:
6679   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6680       DAG.getTarget()
6681           .getSubtargetImpl()
6682           ->getTargetLowering()
6683           ->isFMAFasterThanFMulAndFAdd(VT) &&
6684       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6685
6686     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6687     if (N0.getOpcode() == ISD::FMUL &&
6688         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6689       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6690                          N0.getOperand(0), N0.getOperand(1), N1);
6691
6692     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6693     // Note: Commutes FADD operands.
6694     if (N1.getOpcode() == ISD::FMUL &&
6695         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6696       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6697                          N1.getOperand(0), N1.getOperand(1), N0);
6698   }
6699
6700   return SDValue();
6701 }
6702
6703 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6704   SDValue N0 = N->getOperand(0);
6705   SDValue N1 = N->getOperand(1);
6706   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6707   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6708   EVT VT = N->getValueType(0);
6709   SDLoc dl(N);
6710   const TargetOptions &Options = DAG.getTarget().Options;
6711
6712   // fold vector ops
6713   if (VT.isVector()) {
6714     SDValue FoldedVOp = SimplifyVBinOp(N);
6715     if (FoldedVOp.getNode()) return FoldedVOp;
6716   }
6717
6718   // fold (fsub c1, c2) -> c1-c2
6719   if (N0CFP && N1CFP)
6720     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6721
6722   // fold (fsub A, (fneg B)) -> (fadd A, B)
6723   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6724     return DAG.getNode(ISD::FADD, dl, VT, N0,
6725                        GetNegatedExpression(N1, DAG, LegalOperations));
6726
6727   // If 'unsafe math' is enabled, fold lots of things.
6728   if (Options.UnsafeFPMath) {
6729     // (fsub A, 0) -> A
6730     if (N1CFP && N1CFP->getValueAPF().isZero())
6731       return N0;
6732
6733     // (fsub 0, B) -> -B
6734     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6735       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6736         return GetNegatedExpression(N1, DAG, LegalOperations);
6737       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6738         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6739     }
6740
6741     // (fsub x, x) -> 0.0
6742     if (N0 == N1)
6743       return DAG.getConstantFP(0.0f, VT);
6744
6745     // (fsub x, (fadd x, y)) -> (fneg y)
6746     // (fsub x, (fadd y, x)) -> (fneg y)
6747     if (N1.getOpcode() == ISD::FADD) {
6748       SDValue N10 = N1->getOperand(0);
6749       SDValue N11 = N1->getOperand(1);
6750
6751       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6752         return GetNegatedExpression(N11, DAG, LegalOperations);
6753
6754       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6755         return GetNegatedExpression(N10, DAG, LegalOperations);
6756     }
6757   }
6758
6759   // FSUB -> FMA combines:
6760   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6761       DAG.getTarget().getSubtargetImpl()
6762           ->getTargetLowering()
6763           ->isFMAFasterThanFMulAndFAdd(VT) &&
6764       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6765
6766     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6767     if (N0.getOpcode() == ISD::FMUL &&
6768         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6769       return DAG.getNode(ISD::FMA, dl, VT,
6770                          N0.getOperand(0), N0.getOperand(1),
6771                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6772
6773     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6774     // Note: Commutes FSUB operands.
6775     if (N1.getOpcode() == ISD::FMUL &&
6776         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6777       return DAG.getNode(ISD::FMA, dl, VT,
6778                          DAG.getNode(ISD::FNEG, dl, VT,
6779                          N1.getOperand(0)),
6780                          N1.getOperand(1), N0);
6781
6782     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6783     if (N0.getOpcode() == ISD::FNEG &&
6784         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6785         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6786             TLI.enableAggressiveFMAFusion(VT))) {
6787       SDValue N00 = N0.getOperand(0).getOperand(0);
6788       SDValue N01 = N0.getOperand(0).getOperand(1);
6789       return DAG.getNode(ISD::FMA, dl, VT,
6790                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6791                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6792     }
6793   }
6794
6795   return SDValue();
6796 }
6797
6798 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6799   SDValue N0 = N->getOperand(0);
6800   SDValue N1 = N->getOperand(1);
6801   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6802   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6803   EVT VT = N->getValueType(0);
6804   const TargetOptions &Options = DAG.getTarget().Options;
6805
6806   // fold vector ops
6807   if (VT.isVector()) {
6808     // This just handles C1 * C2 for vectors. Other vector folds are below.
6809     SDValue FoldedVOp = SimplifyVBinOp(N);
6810     if (FoldedVOp.getNode())
6811       return FoldedVOp;
6812     // Canonicalize vector constant to RHS.
6813     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6814         N1.getOpcode() != ISD::BUILD_VECTOR)
6815       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6816         if (BV0->isConstant())
6817           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6818   }
6819
6820   // fold (fmul c1, c2) -> c1*c2
6821   if (N0CFP && N1CFP)
6822     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6823
6824   // canonicalize constant to RHS
6825   if (N0CFP && !N1CFP)
6826     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6827
6828   // fold (fmul A, 1.0) -> A
6829   if (N1CFP && N1CFP->isExactlyValue(1.0))
6830     return N0;
6831
6832   if (Options.UnsafeFPMath) {
6833     // fold (fmul A, 0) -> 0
6834     if (N1CFP && N1CFP->getValueAPF().isZero())
6835       return N1;
6836
6837     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6838     if (N0.getOpcode() == ISD::FMUL) {
6839       // Fold scalars or any vector constants (not just splats).
6840       // This fold is done in general by InstCombine, but extra fmul insts
6841       // may have been generated during lowering.
6842       SDValue N01 = N0.getOperand(1);
6843       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6844       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6845       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6846           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6847         SDLoc SL(N);
6848         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6849         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6850       }
6851     }
6852
6853     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6854     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6855     // during an early run of DAGCombiner can prevent folding with fmuls
6856     // inserted during lowering.
6857     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6858       SDLoc SL(N);
6859       const SDValue Two = DAG.getConstantFP(2.0, VT);
6860       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6861       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6862     }
6863   }
6864
6865   // fold (fmul X, 2.0) -> (fadd X, X)
6866   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6867     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6868
6869   // fold (fmul X, -1.0) -> (fneg X)
6870   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6871     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6872       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6873
6874   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6875   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6876     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6877       // Both can be negated for free, check to see if at least one is cheaper
6878       // negated.
6879       if (LHSNeg == 2 || RHSNeg == 2)
6880         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6881                            GetNegatedExpression(N0, DAG, LegalOperations),
6882                            GetNegatedExpression(N1, DAG, LegalOperations));
6883     }
6884   }
6885
6886   return SDValue();
6887 }
6888
6889 SDValue DAGCombiner::visitFMA(SDNode *N) {
6890   SDValue N0 = N->getOperand(0);
6891   SDValue N1 = N->getOperand(1);
6892   SDValue N2 = N->getOperand(2);
6893   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6894   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6895   EVT VT = N->getValueType(0);
6896   SDLoc dl(N);
6897   const TargetOptions &Options = DAG.getTarget().Options;
6898
6899   // Constant fold FMA.
6900   if (isa<ConstantFPSDNode>(N0) &&
6901       isa<ConstantFPSDNode>(N1) &&
6902       isa<ConstantFPSDNode>(N2)) {
6903     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6904   }
6905
6906   if (Options.UnsafeFPMath) {
6907     if (N0CFP && N0CFP->isZero())
6908       return N2;
6909     if (N1CFP && N1CFP->isZero())
6910       return N2;
6911   }
6912   if (N0CFP && N0CFP->isExactlyValue(1.0))
6913     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6914   if (N1CFP && N1CFP->isExactlyValue(1.0))
6915     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6916
6917   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6918   if (N0CFP && !N1CFP)
6919     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6920
6921   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6922   if (Options.UnsafeFPMath && N1CFP &&
6923       N2.getOpcode() == ISD::FMUL &&
6924       N0 == N2.getOperand(0) &&
6925       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6926     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6927                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6928   }
6929
6930
6931   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6932   if (Options.UnsafeFPMath &&
6933       N0.getOpcode() == ISD::FMUL && N1CFP &&
6934       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6935     return DAG.getNode(ISD::FMA, dl, VT,
6936                        N0.getOperand(0),
6937                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6938                        N2);
6939   }
6940
6941   // (fma x, 1, y) -> (fadd x, y)
6942   // (fma x, -1, y) -> (fadd (fneg x), y)
6943   if (N1CFP) {
6944     if (N1CFP->isExactlyValue(1.0))
6945       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6946
6947     if (N1CFP->isExactlyValue(-1.0) &&
6948         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6949       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6950       AddToWorklist(RHSNeg.getNode());
6951       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6952     }
6953   }
6954
6955   // (fma x, c, x) -> (fmul x, (c+1))
6956   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6957     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6958                        DAG.getNode(ISD::FADD, dl, VT,
6959                                    N1, DAG.getConstantFP(1.0, VT)));
6960
6961   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6962   if (Options.UnsafeFPMath && N1CFP &&
6963       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6964     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6965                        DAG.getNode(ISD::FADD, dl, VT,
6966                                    N1, DAG.getConstantFP(-1.0, VT)));
6967
6968
6969   return SDValue();
6970 }
6971
6972 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6973   SDValue N0 = N->getOperand(0);
6974   SDValue N1 = N->getOperand(1);
6975   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6976   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6977   EVT VT = N->getValueType(0);
6978   const TargetOptions &Options = DAG.getTarget().Options;
6979
6980   // fold vector ops
6981   if (VT.isVector()) {
6982     SDValue FoldedVOp = SimplifyVBinOp(N);
6983     if (FoldedVOp.getNode()) return FoldedVOp;
6984   }
6985
6986   // fold (fdiv c1, c2) -> c1/c2
6987   if (N0CFP && N1CFP)
6988     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6989
6990   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6991   if (N1CFP && Options.UnsafeFPMath) {
6992     // Compute the reciprocal 1.0 / c2.
6993     APFloat N1APF = N1CFP->getValueAPF();
6994     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6995     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6996     // Only do the transform if the reciprocal is a legal fp immediate that
6997     // isn't too nasty (eg NaN, denormal, ...).
6998     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6999         (!LegalOperations ||
7000          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7001          // backend)... we should handle this gracefully after Legalize.
7002          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7003          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7004          TLI.isFPImmLegal(Recip, VT)))
7005       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7006                          DAG.getConstantFP(Recip, VT));
7007   }
7008
7009   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7010   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7011     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7012       // Both can be negated for free, check to see if at least one is cheaper
7013       // negated.
7014       if (LHSNeg == 2 || RHSNeg == 2)
7015         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7016                            GetNegatedExpression(N0, DAG, LegalOperations),
7017                            GetNegatedExpression(N1, DAG, LegalOperations));
7018     }
7019   }
7020
7021   return SDValue();
7022 }
7023
7024 SDValue DAGCombiner::visitFREM(SDNode *N) {
7025   SDValue N0 = N->getOperand(0);
7026   SDValue N1 = N->getOperand(1);
7027   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7028   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7029   EVT VT = N->getValueType(0);
7030
7031   // fold (frem c1, c2) -> fmod(c1,c2)
7032   if (N0CFP && N1CFP)
7033     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7034
7035   return SDValue();
7036 }
7037
7038 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7039   SDValue N0 = N->getOperand(0);
7040   SDValue N1 = N->getOperand(1);
7041   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7042   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7043   EVT VT = N->getValueType(0);
7044
7045   if (N0CFP && N1CFP)  // Constant fold
7046     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7047
7048   if (N1CFP) {
7049     const APFloat& V = N1CFP->getValueAPF();
7050     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7051     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7052     if (!V.isNegative()) {
7053       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7054         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7055     } else {
7056       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7057         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7058                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7059     }
7060   }
7061
7062   // copysign(fabs(x), y) -> copysign(x, y)
7063   // copysign(fneg(x), y) -> copysign(x, y)
7064   // copysign(copysign(x,z), y) -> copysign(x, y)
7065   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7066       N0.getOpcode() == ISD::FCOPYSIGN)
7067     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7068                        N0.getOperand(0), N1);
7069
7070   // copysign(x, abs(y)) -> abs(x)
7071   if (N1.getOpcode() == ISD::FABS)
7072     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7073
7074   // copysign(x, copysign(y,z)) -> copysign(x, z)
7075   if (N1.getOpcode() == ISD::FCOPYSIGN)
7076     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7077                        N0, N1.getOperand(1));
7078
7079   // copysign(x, fp_extend(y)) -> copysign(x, y)
7080   // copysign(x, fp_round(y)) -> copysign(x, y)
7081   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7082     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7083                        N0, N1.getOperand(0));
7084
7085   return SDValue();
7086 }
7087
7088 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7089   SDValue N0 = N->getOperand(0);
7090   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7091   EVT VT = N->getValueType(0);
7092   EVT OpVT = N0.getValueType();
7093
7094   // fold (sint_to_fp c1) -> c1fp
7095   if (N0C &&
7096       // ...but only if the target supports immediate floating-point values
7097       (!LegalOperations ||
7098        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7099     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7100
7101   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7102   // but UINT_TO_FP is legal on this target, try to convert.
7103   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7104       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7105     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7106     if (DAG.SignBitIsZero(N0))
7107       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7108   }
7109
7110   // The next optimizations are desirable only if SELECT_CC can be lowered.
7111   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7112     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7113     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7114         !VT.isVector() &&
7115         (!LegalOperations ||
7116          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7117       SDValue Ops[] =
7118         { N0.getOperand(0), N0.getOperand(1),
7119           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7120           N0.getOperand(2) };
7121       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7122     }
7123
7124     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7125     //      (select_cc x, y, 1.0, 0.0,, cc)
7126     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7127         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7128         (!LegalOperations ||
7129          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7130       SDValue Ops[] =
7131         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7132           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7133           N0.getOperand(0).getOperand(2) };
7134       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7135     }
7136   }
7137
7138   return SDValue();
7139 }
7140
7141 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7142   SDValue N0 = N->getOperand(0);
7143   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7144   EVT VT = N->getValueType(0);
7145   EVT OpVT = N0.getValueType();
7146
7147   // fold (uint_to_fp c1) -> c1fp
7148   if (N0C &&
7149       // ...but only if the target supports immediate floating-point values
7150       (!LegalOperations ||
7151        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7152     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7153
7154   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7155   // but SINT_TO_FP is legal on this target, try to convert.
7156   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7157       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7158     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7159     if (DAG.SignBitIsZero(N0))
7160       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7161   }
7162
7163   // The next optimizations are desirable only if SELECT_CC can be lowered.
7164   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7165     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7166
7167     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7168         (!LegalOperations ||
7169          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7170       SDValue Ops[] =
7171         { N0.getOperand(0), N0.getOperand(1),
7172           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7173           N0.getOperand(2) };
7174       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7175     }
7176   }
7177
7178   return SDValue();
7179 }
7180
7181 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7182   SDValue N0 = N->getOperand(0);
7183   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7184   EVT VT = N->getValueType(0);
7185
7186   // fold (fp_to_sint c1fp) -> c1
7187   if (N0CFP)
7188     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7189
7190   return SDValue();
7191 }
7192
7193 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7194   SDValue N0 = N->getOperand(0);
7195   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7196   EVT VT = N->getValueType(0);
7197
7198   // fold (fp_to_uint c1fp) -> c1
7199   if (N0CFP)
7200     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7201
7202   return SDValue();
7203 }
7204
7205 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7206   SDValue N0 = N->getOperand(0);
7207   SDValue N1 = N->getOperand(1);
7208   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7209   EVT VT = N->getValueType(0);
7210
7211   // fold (fp_round c1fp) -> c1fp
7212   if (N0CFP)
7213     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7214
7215   // fold (fp_round (fp_extend x)) -> x
7216   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7217     return N0.getOperand(0);
7218
7219   // fold (fp_round (fp_round x)) -> (fp_round x)
7220   if (N0.getOpcode() == ISD::FP_ROUND) {
7221     // This is a value preserving truncation if both round's are.
7222     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7223                    N0.getNode()->getConstantOperandVal(1) == 1;
7224     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7225                        DAG.getIntPtrConstant(IsTrunc));
7226   }
7227
7228   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7229   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7230     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7231                               N0.getOperand(0), N1);
7232     AddToWorklist(Tmp.getNode());
7233     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7234                        Tmp, N0.getOperand(1));
7235   }
7236
7237   return SDValue();
7238 }
7239
7240 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7241   SDValue N0 = N->getOperand(0);
7242   EVT VT = N->getValueType(0);
7243   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7244   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7245
7246   // fold (fp_round_inreg c1fp) -> c1fp
7247   if (N0CFP && isTypeLegal(EVT)) {
7248     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7249     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7250   }
7251
7252   return SDValue();
7253 }
7254
7255 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7256   SDValue N0 = N->getOperand(0);
7257   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7258   EVT VT = N->getValueType(0);
7259
7260   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7261   if (N->hasOneUse() &&
7262       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7263     return SDValue();
7264
7265   // fold (fp_extend c1fp) -> c1fp
7266   if (N0CFP)
7267     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7268
7269   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7270   // value of X.
7271   if (N0.getOpcode() == ISD::FP_ROUND
7272       && N0.getNode()->getConstantOperandVal(1) == 1) {
7273     SDValue In = N0.getOperand(0);
7274     if (In.getValueType() == VT) return In;
7275     if (VT.bitsLT(In.getValueType()))
7276       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7277                          In, N0.getOperand(1));
7278     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7279   }
7280
7281   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7282   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7283        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7284     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7285     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7286                                      LN0->getChain(),
7287                                      LN0->getBasePtr(), N0.getValueType(),
7288                                      LN0->getMemOperand());
7289     CombineTo(N, ExtLoad);
7290     CombineTo(N0.getNode(),
7291               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7292                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7293               ExtLoad.getValue(1));
7294     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7295   }
7296
7297   return SDValue();
7298 }
7299
7300 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7301   SDValue N0 = N->getOperand(0);
7302   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7303   EVT VT = N->getValueType(0);
7304
7305   // fold (fceil c1) -> fceil(c1)
7306   if (N0CFP)
7307     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7308
7309   return SDValue();
7310 }
7311
7312 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7313   SDValue N0 = N->getOperand(0);
7314   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7315   EVT VT = N->getValueType(0);
7316
7317   // fold (ftrunc c1) -> ftrunc(c1)
7318   if (N0CFP)
7319     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7320
7321   return SDValue();
7322 }
7323
7324 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7325   SDValue N0 = N->getOperand(0);
7326   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7327   EVT VT = N->getValueType(0);
7328
7329   // fold (ffloor c1) -> ffloor(c1)
7330   if (N0CFP)
7331     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7332
7333   return SDValue();
7334 }
7335
7336 // FIXME: FNEG and FABS have a lot in common; refactor.
7337 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7338   SDValue N0 = N->getOperand(0);
7339   EVT VT = N->getValueType(0);
7340
7341   if (VT.isVector()) {
7342     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7343     if (FoldedVOp.getNode()) return FoldedVOp;
7344   }
7345
7346   // Constant fold FNEG.
7347   if (isa<ConstantFPSDNode>(N0))
7348     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7349
7350   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7351                          &DAG.getTarget().Options))
7352     return GetNegatedExpression(N0, DAG, LegalOperations);
7353
7354   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7355   // constant pool values.
7356   if (!TLI.isFNegFree(VT) &&
7357       N0.getOpcode() == ISD::BITCAST &&
7358       N0.getNode()->hasOneUse()) {
7359     SDValue Int = N0.getOperand(0);
7360     EVT IntVT = Int.getValueType();
7361     if (IntVT.isInteger() && !IntVT.isVector()) {
7362       APInt SignMask;
7363       if (N0.getValueType().isVector()) {
7364         // For a vector, get a mask such as 0x80... per scalar element
7365         // and splat it.
7366         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7367         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7368       } else {
7369         // For a scalar, just generate 0x80...
7370         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7371       }
7372       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7373                         DAG.getConstant(SignMask, IntVT));
7374       AddToWorklist(Int.getNode());
7375       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7376     }
7377   }
7378
7379   // (fneg (fmul c, x)) -> (fmul -c, x)
7380   if (N0.getOpcode() == ISD::FMUL) {
7381     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7382     if (CFP1) {
7383       APFloat CVal = CFP1->getValueAPF();
7384       CVal.changeSign();
7385       if (Level >= AfterLegalizeDAG &&
7386           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7387            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7388         return DAG.getNode(
7389             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7390             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7391     }
7392   }
7393
7394   return SDValue();
7395 }
7396
7397 SDValue DAGCombiner::visitFABS(SDNode *N) {
7398   SDValue N0 = N->getOperand(0);
7399   EVT VT = N->getValueType(0);
7400
7401   if (VT.isVector()) {
7402     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7403     if (FoldedVOp.getNode()) return FoldedVOp;
7404   }
7405
7406   // fold (fabs c1) -> fabs(c1)
7407   if (isa<ConstantFPSDNode>(N0))
7408     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7409   
7410   // fold (fabs (fabs x)) -> (fabs x)
7411   if (N0.getOpcode() == ISD::FABS)
7412     return N->getOperand(0);
7413
7414   // fold (fabs (fneg x)) -> (fabs x)
7415   // fold (fabs (fcopysign x, y)) -> (fabs x)
7416   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7417     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7418
7419   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7420   // constant pool values.
7421   if (!TLI.isFAbsFree(VT) &&
7422       N0.getOpcode() == ISD::BITCAST &&
7423       N0.getNode()->hasOneUse()) {
7424     SDValue Int = N0.getOperand(0);
7425     EVT IntVT = Int.getValueType();
7426     if (IntVT.isInteger() && !IntVT.isVector()) {
7427       APInt SignMask;
7428       if (N0.getValueType().isVector()) {
7429         // For a vector, get a mask such as 0x7f... per scalar element
7430         // and splat it.
7431         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7432         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7433       } else {
7434         // For a scalar, just generate 0x7f...
7435         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7436       }
7437       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7438                         DAG.getConstant(SignMask, IntVT));
7439       AddToWorklist(Int.getNode());
7440       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7441     }
7442   }
7443
7444   return SDValue();
7445 }
7446
7447 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7448   SDValue Chain = N->getOperand(0);
7449   SDValue N1 = N->getOperand(1);
7450   SDValue N2 = N->getOperand(2);
7451
7452   // If N is a constant we could fold this into a fallthrough or unconditional
7453   // branch. However that doesn't happen very often in normal code, because
7454   // Instcombine/SimplifyCFG should have handled the available opportunities.
7455   // If we did this folding here, it would be necessary to update the
7456   // MachineBasicBlock CFG, which is awkward.
7457
7458   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7459   // on the target.
7460   if (N1.getOpcode() == ISD::SETCC &&
7461       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7462                                    N1.getOperand(0).getValueType())) {
7463     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7464                        Chain, N1.getOperand(2),
7465                        N1.getOperand(0), N1.getOperand(1), N2);
7466   }
7467
7468   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7469       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7470        (N1.getOperand(0).hasOneUse() &&
7471         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7472     SDNode *Trunc = nullptr;
7473     if (N1.getOpcode() == ISD::TRUNCATE) {
7474       // Look pass the truncate.
7475       Trunc = N1.getNode();
7476       N1 = N1.getOperand(0);
7477     }
7478
7479     // Match this pattern so that we can generate simpler code:
7480     //
7481     //   %a = ...
7482     //   %b = and i32 %a, 2
7483     //   %c = srl i32 %b, 1
7484     //   brcond i32 %c ...
7485     //
7486     // into
7487     //
7488     //   %a = ...
7489     //   %b = and i32 %a, 2
7490     //   %c = setcc eq %b, 0
7491     //   brcond %c ...
7492     //
7493     // This applies only when the AND constant value has one bit set and the
7494     // SRL constant is equal to the log2 of the AND constant. The back-end is
7495     // smart enough to convert the result into a TEST/JMP sequence.
7496     SDValue Op0 = N1.getOperand(0);
7497     SDValue Op1 = N1.getOperand(1);
7498
7499     if (Op0.getOpcode() == ISD::AND &&
7500         Op1.getOpcode() == ISD::Constant) {
7501       SDValue AndOp1 = Op0.getOperand(1);
7502
7503       if (AndOp1.getOpcode() == ISD::Constant) {
7504         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7505
7506         if (AndConst.isPowerOf2() &&
7507             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7508           SDValue SetCC =
7509             DAG.getSetCC(SDLoc(N),
7510                          getSetCCResultType(Op0.getValueType()),
7511                          Op0, DAG.getConstant(0, Op0.getValueType()),
7512                          ISD::SETNE);
7513
7514           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7515                                           MVT::Other, Chain, SetCC, N2);
7516           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7517           // will convert it back to (X & C1) >> C2.
7518           CombineTo(N, NewBRCond, false);
7519           // Truncate is dead.
7520           if (Trunc)
7521             deleteAndRecombine(Trunc);
7522           // Replace the uses of SRL with SETCC
7523           WorklistRemover DeadNodes(*this);
7524           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7525           deleteAndRecombine(N1.getNode());
7526           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7527         }
7528       }
7529     }
7530
7531     if (Trunc)
7532       // Restore N1 if the above transformation doesn't match.
7533       N1 = N->getOperand(1);
7534   }
7535
7536   // Transform br(xor(x, y)) -> br(x != y)
7537   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7538   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7539     SDNode *TheXor = N1.getNode();
7540     SDValue Op0 = TheXor->getOperand(0);
7541     SDValue Op1 = TheXor->getOperand(1);
7542     if (Op0.getOpcode() == Op1.getOpcode()) {
7543       // Avoid missing important xor optimizations.
7544       SDValue Tmp = visitXOR(TheXor);
7545       if (Tmp.getNode()) {
7546         if (Tmp.getNode() != TheXor) {
7547           DEBUG(dbgs() << "\nReplacing.8 ";
7548                 TheXor->dump(&DAG);
7549                 dbgs() << "\nWith: ";
7550                 Tmp.getNode()->dump(&DAG);
7551                 dbgs() << '\n');
7552           WorklistRemover DeadNodes(*this);
7553           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7554           deleteAndRecombine(TheXor);
7555           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7556                              MVT::Other, Chain, Tmp, N2);
7557         }
7558
7559         // visitXOR has changed XOR's operands or replaced the XOR completely,
7560         // bail out.
7561         return SDValue(N, 0);
7562       }
7563     }
7564
7565     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7566       bool Equal = false;
7567       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7568         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7569             Op0.getOpcode() == ISD::XOR) {
7570           TheXor = Op0.getNode();
7571           Equal = true;
7572         }
7573
7574       EVT SetCCVT = N1.getValueType();
7575       if (LegalTypes)
7576         SetCCVT = getSetCCResultType(SetCCVT);
7577       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7578                                    SetCCVT,
7579                                    Op0, Op1,
7580                                    Equal ? ISD::SETEQ : ISD::SETNE);
7581       // Replace the uses of XOR with SETCC
7582       WorklistRemover DeadNodes(*this);
7583       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7584       deleteAndRecombine(N1.getNode());
7585       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7586                          MVT::Other, Chain, SetCC, N2);
7587     }
7588   }
7589
7590   return SDValue();
7591 }
7592
7593 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7594 //
7595 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7596   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7597   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7598
7599   // If N is a constant we could fold this into a fallthrough or unconditional
7600   // branch. However that doesn't happen very often in normal code, because
7601   // Instcombine/SimplifyCFG should have handled the available opportunities.
7602   // If we did this folding here, it would be necessary to update the
7603   // MachineBasicBlock CFG, which is awkward.
7604
7605   // Use SimplifySetCC to simplify SETCC's.
7606   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7607                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7608                                false);
7609   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7610
7611   // fold to a simpler setcc
7612   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7613     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7614                        N->getOperand(0), Simp.getOperand(2),
7615                        Simp.getOperand(0), Simp.getOperand(1),
7616                        N->getOperand(4));
7617
7618   return SDValue();
7619 }
7620
7621 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7622 /// and that N may be folded in the load / store addressing mode.
7623 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7624                                     SelectionDAG &DAG,
7625                                     const TargetLowering &TLI) {
7626   EVT VT;
7627   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7628     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7629       return false;
7630     VT = Use->getValueType(0);
7631   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7632     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7633       return false;
7634     VT = ST->getValue().getValueType();
7635   } else
7636     return false;
7637
7638   TargetLowering::AddrMode AM;
7639   if (N->getOpcode() == ISD::ADD) {
7640     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7641     if (Offset)
7642       // [reg +/- imm]
7643       AM.BaseOffs = Offset->getSExtValue();
7644     else
7645       // [reg +/- reg]
7646       AM.Scale = 1;
7647   } else if (N->getOpcode() == ISD::SUB) {
7648     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7649     if (Offset)
7650       // [reg +/- imm]
7651       AM.BaseOffs = -Offset->getSExtValue();
7652     else
7653       // [reg +/- reg]
7654       AM.Scale = 1;
7655   } else
7656     return false;
7657
7658   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7659 }
7660
7661 /// Try turning a load/store into a pre-indexed load/store when the base
7662 /// pointer is an add or subtract and it has other uses besides the load/store.
7663 /// After the transformation, the new indexed load/store has effectively folded
7664 /// the add/subtract in and all of its other uses are redirected to the
7665 /// new load/store.
7666 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7667   if (Level < AfterLegalizeDAG)
7668     return false;
7669
7670   bool isLoad = true;
7671   SDValue Ptr;
7672   EVT VT;
7673   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7674     if (LD->isIndexed())
7675       return false;
7676     VT = LD->getMemoryVT();
7677     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7678         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7679       return false;
7680     Ptr = LD->getBasePtr();
7681   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7682     if (ST->isIndexed())
7683       return false;
7684     VT = ST->getMemoryVT();
7685     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7686         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7687       return false;
7688     Ptr = ST->getBasePtr();
7689     isLoad = false;
7690   } else {
7691     return false;
7692   }
7693
7694   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7695   // out.  There is no reason to make this a preinc/predec.
7696   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7697       Ptr.getNode()->hasOneUse())
7698     return false;
7699
7700   // Ask the target to do addressing mode selection.
7701   SDValue BasePtr;
7702   SDValue Offset;
7703   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7704   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7705     return false;
7706
7707   // Backends without true r+i pre-indexed forms may need to pass a
7708   // constant base with a variable offset so that constant coercion
7709   // will work with the patterns in canonical form.
7710   bool Swapped = false;
7711   if (isa<ConstantSDNode>(BasePtr)) {
7712     std::swap(BasePtr, Offset);
7713     Swapped = true;
7714   }
7715
7716   // Don't create a indexed load / store with zero offset.
7717   if (isa<ConstantSDNode>(Offset) &&
7718       cast<ConstantSDNode>(Offset)->isNullValue())
7719     return false;
7720
7721   // Try turning it into a pre-indexed load / store except when:
7722   // 1) The new base ptr is a frame index.
7723   // 2) If N is a store and the new base ptr is either the same as or is a
7724   //    predecessor of the value being stored.
7725   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7726   //    that would create a cycle.
7727   // 4) All uses are load / store ops that use it as old base ptr.
7728
7729   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7730   // (plus the implicit offset) to a register to preinc anyway.
7731   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7732     return false;
7733
7734   // Check #2.
7735   if (!isLoad) {
7736     SDValue Val = cast<StoreSDNode>(N)->getValue();
7737     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7738       return false;
7739   }
7740
7741   // If the offset is a constant, there may be other adds of constants that
7742   // can be folded with this one. We should do this to avoid having to keep
7743   // a copy of the original base pointer.
7744   SmallVector<SDNode *, 16> OtherUses;
7745   if (isa<ConstantSDNode>(Offset))
7746     for (SDNode *Use : BasePtr.getNode()->uses()) {
7747       if (Use == Ptr.getNode())
7748         continue;
7749
7750       if (Use->isPredecessorOf(N))
7751         continue;
7752
7753       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7754         OtherUses.clear();
7755         break;
7756       }
7757
7758       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7759       if (Op1.getNode() == BasePtr.getNode())
7760         std::swap(Op0, Op1);
7761       assert(Op0.getNode() == BasePtr.getNode() &&
7762              "Use of ADD/SUB but not an operand");
7763
7764       if (!isa<ConstantSDNode>(Op1)) {
7765         OtherUses.clear();
7766         break;
7767       }
7768
7769       // FIXME: In some cases, we can be smarter about this.
7770       if (Op1.getValueType() != Offset.getValueType()) {
7771         OtherUses.clear();
7772         break;
7773       }
7774
7775       OtherUses.push_back(Use);
7776     }
7777
7778   if (Swapped)
7779     std::swap(BasePtr, Offset);
7780
7781   // Now check for #3 and #4.
7782   bool RealUse = false;
7783
7784   // Caches for hasPredecessorHelper
7785   SmallPtrSet<const SDNode *, 32> Visited;
7786   SmallVector<const SDNode *, 16> Worklist;
7787
7788   for (SDNode *Use : Ptr.getNode()->uses()) {
7789     if (Use == N)
7790       continue;
7791     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7792       return false;
7793
7794     // If Ptr may be folded in addressing mode of other use, then it's
7795     // not profitable to do this transformation.
7796     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7797       RealUse = true;
7798   }
7799
7800   if (!RealUse)
7801     return false;
7802
7803   SDValue Result;
7804   if (isLoad)
7805     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7806                                 BasePtr, Offset, AM);
7807   else
7808     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7809                                  BasePtr, Offset, AM);
7810   ++PreIndexedNodes;
7811   ++NodesCombined;
7812   DEBUG(dbgs() << "\nReplacing.4 ";
7813         N->dump(&DAG);
7814         dbgs() << "\nWith: ";
7815         Result.getNode()->dump(&DAG);
7816         dbgs() << '\n');
7817   WorklistRemover DeadNodes(*this);
7818   if (isLoad) {
7819     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7820     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7821   } else {
7822     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7823   }
7824
7825   // Finally, since the node is now dead, remove it from the graph.
7826   deleteAndRecombine(N);
7827
7828   if (Swapped)
7829     std::swap(BasePtr, Offset);
7830
7831   // Replace other uses of BasePtr that can be updated to use Ptr
7832   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7833     unsigned OffsetIdx = 1;
7834     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7835       OffsetIdx = 0;
7836     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7837            BasePtr.getNode() && "Expected BasePtr operand");
7838
7839     // We need to replace ptr0 in the following expression:
7840     //   x0 * offset0 + y0 * ptr0 = t0
7841     // knowing that
7842     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7843     //
7844     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7845     // indexed load/store and the expresion that needs to be re-written.
7846     //
7847     // Therefore, we have:
7848     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7849
7850     ConstantSDNode *CN =
7851       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7852     int X0, X1, Y0, Y1;
7853     APInt Offset0 = CN->getAPIntValue();
7854     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7855
7856     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7857     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7858     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7859     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7860
7861     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7862
7863     APInt CNV = Offset0;
7864     if (X0 < 0) CNV = -CNV;
7865     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7866     else CNV = CNV - Offset1;
7867
7868     // We can now generate the new expression.
7869     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7870     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7871
7872     SDValue NewUse = DAG.getNode(Opcode,
7873                                  SDLoc(OtherUses[i]),
7874                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7875     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7876     deleteAndRecombine(OtherUses[i]);
7877   }
7878
7879   // Replace the uses of Ptr with uses of the updated base value.
7880   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7881   deleteAndRecombine(Ptr.getNode());
7882
7883   return true;
7884 }
7885
7886 /// Try to combine a load/store with a add/sub of the base pointer node into a
7887 /// post-indexed load/store. The transformation folded the add/subtract into the
7888 /// new indexed load/store effectively and all of its uses are redirected to the
7889 /// new load/store.
7890 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7891   if (Level < AfterLegalizeDAG)
7892     return false;
7893
7894   bool isLoad = true;
7895   SDValue Ptr;
7896   EVT VT;
7897   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7898     if (LD->isIndexed())
7899       return false;
7900     VT = LD->getMemoryVT();
7901     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7902         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7903       return false;
7904     Ptr = LD->getBasePtr();
7905   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7906     if (ST->isIndexed())
7907       return false;
7908     VT = ST->getMemoryVT();
7909     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7910         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7911       return false;
7912     Ptr = ST->getBasePtr();
7913     isLoad = false;
7914   } else {
7915     return false;
7916   }
7917
7918   if (Ptr.getNode()->hasOneUse())
7919     return false;
7920
7921   for (SDNode *Op : Ptr.getNode()->uses()) {
7922     if (Op == N ||
7923         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7924       continue;
7925
7926     SDValue BasePtr;
7927     SDValue Offset;
7928     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7929     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7930       // Don't create a indexed load / store with zero offset.
7931       if (isa<ConstantSDNode>(Offset) &&
7932           cast<ConstantSDNode>(Offset)->isNullValue())
7933         continue;
7934
7935       // Try turning it into a post-indexed load / store except when
7936       // 1) All uses are load / store ops that use it as base ptr (and
7937       //    it may be folded as addressing mmode).
7938       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7939       //    nor a successor of N. Otherwise, if Op is folded that would
7940       //    create a cycle.
7941
7942       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7943         continue;
7944
7945       // Check for #1.
7946       bool TryNext = false;
7947       for (SDNode *Use : BasePtr.getNode()->uses()) {
7948         if (Use == Ptr.getNode())
7949           continue;
7950
7951         // If all the uses are load / store addresses, then don't do the
7952         // transformation.
7953         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7954           bool RealUse = false;
7955           for (SDNode *UseUse : Use->uses()) {
7956             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7957               RealUse = true;
7958           }
7959
7960           if (!RealUse) {
7961             TryNext = true;
7962             break;
7963           }
7964         }
7965       }
7966
7967       if (TryNext)
7968         continue;
7969
7970       // Check for #2
7971       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7972         SDValue Result = isLoad
7973           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7974                                BasePtr, Offset, AM)
7975           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7976                                 BasePtr, Offset, AM);
7977         ++PostIndexedNodes;
7978         ++NodesCombined;
7979         DEBUG(dbgs() << "\nReplacing.5 ";
7980               N->dump(&DAG);
7981               dbgs() << "\nWith: ";
7982               Result.getNode()->dump(&DAG);
7983               dbgs() << '\n');
7984         WorklistRemover DeadNodes(*this);
7985         if (isLoad) {
7986           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7987           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7988         } else {
7989           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7990         }
7991
7992         // Finally, since the node is now dead, remove it from the graph.
7993         deleteAndRecombine(N);
7994
7995         // Replace the uses of Use with uses of the updated base value.
7996         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7997                                       Result.getValue(isLoad ? 1 : 0));
7998         deleteAndRecombine(Op);
7999         return true;
8000       }
8001     }
8002   }
8003
8004   return false;
8005 }
8006
8007 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8008 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8009   ISD::MemIndexedMode AM = LD->getAddressingMode();
8010   assert(AM != ISD::UNINDEXED);
8011   SDValue BP = LD->getOperand(1);
8012   SDValue Inc = LD->getOperand(2);
8013
8014   // Some backends use TargetConstants for load offsets, but don't expect
8015   // TargetConstants in general ADD nodes. We can convert these constants into
8016   // regular Constants (if the constant is not opaque).
8017   assert((Inc.getOpcode() != ISD::TargetConstant ||
8018           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8019          "Cannot split out indexing using opaque target constants");
8020   if (Inc.getOpcode() == ISD::TargetConstant) {
8021     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8022     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8023                           ConstInc->getValueType(0));
8024   }
8025
8026   unsigned Opc =
8027       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8028   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8029 }
8030
8031 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8032   LoadSDNode *LD  = cast<LoadSDNode>(N);
8033   SDValue Chain = LD->getChain();
8034   SDValue Ptr   = LD->getBasePtr();
8035
8036   // If load is not volatile and there are no uses of the loaded value (and
8037   // the updated indexed value in case of indexed loads), change uses of the
8038   // chain value into uses of the chain input (i.e. delete the dead load).
8039   if (!LD->isVolatile()) {
8040     if (N->getValueType(1) == MVT::Other) {
8041       // Unindexed loads.
8042       if (!N->hasAnyUseOfValue(0)) {
8043         // It's not safe to use the two value CombineTo variant here. e.g.
8044         // v1, chain2 = load chain1, loc
8045         // v2, chain3 = load chain2, loc
8046         // v3         = add v2, c
8047         // Now we replace use of chain2 with chain1.  This makes the second load
8048         // isomorphic to the one we are deleting, and thus makes this load live.
8049         DEBUG(dbgs() << "\nReplacing.6 ";
8050               N->dump(&DAG);
8051               dbgs() << "\nWith chain: ";
8052               Chain.getNode()->dump(&DAG);
8053               dbgs() << "\n");
8054         WorklistRemover DeadNodes(*this);
8055         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8056
8057         if (N->use_empty())
8058           deleteAndRecombine(N);
8059
8060         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8061       }
8062     } else {
8063       // Indexed loads.
8064       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8065
8066       // If this load has an opaque TargetConstant offset, then we cannot split
8067       // the indexing into an add/sub directly (that TargetConstant may not be
8068       // valid for a different type of node, and we cannot convert an opaque
8069       // target constant into a regular constant).
8070       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8071                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8072
8073       if (!N->hasAnyUseOfValue(0) &&
8074           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8075         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8076         SDValue Index;
8077         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8078           Index = SplitIndexingFromLoad(LD);
8079           // Try to fold the base pointer arithmetic into subsequent loads and
8080           // stores.
8081           AddUsersToWorklist(N);
8082         } else
8083           Index = DAG.getUNDEF(N->getValueType(1));
8084         DEBUG(dbgs() << "\nReplacing.7 ";
8085               N->dump(&DAG);
8086               dbgs() << "\nWith: ";
8087               Undef.getNode()->dump(&DAG);
8088               dbgs() << " and 2 other values\n");
8089         WorklistRemover DeadNodes(*this);
8090         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8091         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8092         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8093         deleteAndRecombine(N);
8094         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8095       }
8096     }
8097   }
8098
8099   // If this load is directly stored, replace the load value with the stored
8100   // value.
8101   // TODO: Handle store large -> read small portion.
8102   // TODO: Handle TRUNCSTORE/LOADEXT
8103   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8104     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8105       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8106       if (PrevST->getBasePtr() == Ptr &&
8107           PrevST->getValue().getValueType() == N->getValueType(0))
8108       return CombineTo(N, Chain.getOperand(1), Chain);
8109     }
8110   }
8111
8112   // Try to infer better alignment information than the load already has.
8113   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8114     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8115       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8116         SDValue NewLoad =
8117                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8118                               LD->getValueType(0),
8119                               Chain, Ptr, LD->getPointerInfo(),
8120                               LD->getMemoryVT(),
8121                               LD->isVolatile(), LD->isNonTemporal(),
8122                               LD->isInvariant(), Align, LD->getAAInfo());
8123         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8124       }
8125     }
8126   }
8127
8128   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8129     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8130 #ifndef NDEBUG
8131   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8132       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8133     UseAA = false;
8134 #endif
8135   if (UseAA && LD->isUnindexed()) {
8136     // Walk up chain skipping non-aliasing memory nodes.
8137     SDValue BetterChain = FindBetterChain(N, Chain);
8138
8139     // If there is a better chain.
8140     if (Chain != BetterChain) {
8141       SDValue ReplLoad;
8142
8143       // Replace the chain to void dependency.
8144       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8145         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8146                                BetterChain, Ptr, LD->getMemOperand());
8147       } else {
8148         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8149                                   LD->getValueType(0),
8150                                   BetterChain, Ptr, LD->getMemoryVT(),
8151                                   LD->getMemOperand());
8152       }
8153
8154       // Create token factor to keep old chain connected.
8155       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8156                                   MVT::Other, Chain, ReplLoad.getValue(1));
8157
8158       // Make sure the new and old chains are cleaned up.
8159       AddToWorklist(Token.getNode());
8160
8161       // Replace uses with load result and token factor. Don't add users
8162       // to work list.
8163       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8164     }
8165   }
8166
8167   // Try transforming N to an indexed load.
8168   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8169     return SDValue(N, 0);
8170
8171   // Try to slice up N to more direct loads if the slices are mapped to
8172   // different register banks or pairing can take place.
8173   if (SliceUpLoad(N))
8174     return SDValue(N, 0);
8175
8176   return SDValue();
8177 }
8178
8179 namespace {
8180 /// \brief Helper structure used to slice a load in smaller loads.
8181 /// Basically a slice is obtained from the following sequence:
8182 /// Origin = load Ty1, Base
8183 /// Shift = srl Ty1 Origin, CstTy Amount
8184 /// Inst = trunc Shift to Ty2
8185 ///
8186 /// Then, it will be rewriten into:
8187 /// Slice = load SliceTy, Base + SliceOffset
8188 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8189 ///
8190 /// SliceTy is deduced from the number of bits that are actually used to
8191 /// build Inst.
8192 struct LoadedSlice {
8193   /// \brief Helper structure used to compute the cost of a slice.
8194   struct Cost {
8195     /// Are we optimizing for code size.
8196     bool ForCodeSize;
8197     /// Various cost.
8198     unsigned Loads;
8199     unsigned Truncates;
8200     unsigned CrossRegisterBanksCopies;
8201     unsigned ZExts;
8202     unsigned Shift;
8203
8204     Cost(bool ForCodeSize = false)
8205         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8206           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8207
8208     /// \brief Get the cost of one isolated slice.
8209     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8210         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8211           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8212       EVT TruncType = LS.Inst->getValueType(0);
8213       EVT LoadedType = LS.getLoadedType();
8214       if (TruncType != LoadedType &&
8215           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8216         ZExts = 1;
8217     }
8218
8219     /// \brief Account for slicing gain in the current cost.
8220     /// Slicing provide a few gains like removing a shift or a
8221     /// truncate. This method allows to grow the cost of the original
8222     /// load with the gain from this slice.
8223     void addSliceGain(const LoadedSlice &LS) {
8224       // Each slice saves a truncate.
8225       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8226       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8227                               LS.Inst->getOperand(0).getValueType()))
8228         ++Truncates;
8229       // If there is a shift amount, this slice gets rid of it.
8230       if (LS.Shift)
8231         ++Shift;
8232       // If this slice can merge a cross register bank copy, account for it.
8233       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8234         ++CrossRegisterBanksCopies;
8235     }
8236
8237     Cost &operator+=(const Cost &RHS) {
8238       Loads += RHS.Loads;
8239       Truncates += RHS.Truncates;
8240       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8241       ZExts += RHS.ZExts;
8242       Shift += RHS.Shift;
8243       return *this;
8244     }
8245
8246     bool operator==(const Cost &RHS) const {
8247       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8248              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8249              ZExts == RHS.ZExts && Shift == RHS.Shift;
8250     }
8251
8252     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8253
8254     bool operator<(const Cost &RHS) const {
8255       // Assume cross register banks copies are as expensive as loads.
8256       // FIXME: Do we want some more target hooks?
8257       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8258       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8259       // Unless we are optimizing for code size, consider the
8260       // expensive operation first.
8261       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8262         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8263       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8264              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8265     }
8266
8267     bool operator>(const Cost &RHS) const { return RHS < *this; }
8268
8269     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8270
8271     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8272   };
8273   // The last instruction that represent the slice. This should be a
8274   // truncate instruction.
8275   SDNode *Inst;
8276   // The original load instruction.
8277   LoadSDNode *Origin;
8278   // The right shift amount in bits from the original load.
8279   unsigned Shift;
8280   // The DAG from which Origin came from.
8281   // This is used to get some contextual information about legal types, etc.
8282   SelectionDAG *DAG;
8283
8284   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8285               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8286       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8287
8288   LoadedSlice(const LoadedSlice &LS)
8289       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8290
8291   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8292   /// \return Result is \p BitWidth and has used bits set to 1 and
8293   ///         not used bits set to 0.
8294   APInt getUsedBits() const {
8295     // Reproduce the trunc(lshr) sequence:
8296     // - Start from the truncated value.
8297     // - Zero extend to the desired bit width.
8298     // - Shift left.
8299     assert(Origin && "No original load to compare against.");
8300     unsigned BitWidth = Origin->getValueSizeInBits(0);
8301     assert(Inst && "This slice is not bound to an instruction");
8302     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8303            "Extracted slice is bigger than the whole type!");
8304     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8305     UsedBits.setAllBits();
8306     UsedBits = UsedBits.zext(BitWidth);
8307     UsedBits <<= Shift;
8308     return UsedBits;
8309   }
8310
8311   /// \brief Get the size of the slice to be loaded in bytes.
8312   unsigned getLoadedSize() const {
8313     unsigned SliceSize = getUsedBits().countPopulation();
8314     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8315     return SliceSize / 8;
8316   }
8317
8318   /// \brief Get the type that will be loaded for this slice.
8319   /// Note: This may not be the final type for the slice.
8320   EVT getLoadedType() const {
8321     assert(DAG && "Missing context");
8322     LLVMContext &Ctxt = *DAG->getContext();
8323     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8324   }
8325
8326   /// \brief Get the alignment of the load used for this slice.
8327   unsigned getAlignment() const {
8328     unsigned Alignment = Origin->getAlignment();
8329     unsigned Offset = getOffsetFromBase();
8330     if (Offset != 0)
8331       Alignment = MinAlign(Alignment, Alignment + Offset);
8332     return Alignment;
8333   }
8334
8335   /// \brief Check if this slice can be rewritten with legal operations.
8336   bool isLegal() const {
8337     // An invalid slice is not legal.
8338     if (!Origin || !Inst || !DAG)
8339       return false;
8340
8341     // Offsets are for indexed load only, we do not handle that.
8342     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8343       return false;
8344
8345     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8346
8347     // Check that the type is legal.
8348     EVT SliceType = getLoadedType();
8349     if (!TLI.isTypeLegal(SliceType))
8350       return false;
8351
8352     // Check that the load is legal for this type.
8353     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8354       return false;
8355
8356     // Check that the offset can be computed.
8357     // 1. Check its type.
8358     EVT PtrType = Origin->getBasePtr().getValueType();
8359     if (PtrType == MVT::Untyped || PtrType.isExtended())
8360       return false;
8361
8362     // 2. Check that it fits in the immediate.
8363     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8364       return false;
8365
8366     // 3. Check that the computation is legal.
8367     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8368       return false;
8369
8370     // Check that the zext is legal if it needs one.
8371     EVT TruncateType = Inst->getValueType(0);
8372     if (TruncateType != SliceType &&
8373         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8374       return false;
8375
8376     return true;
8377   }
8378
8379   /// \brief Get the offset in bytes of this slice in the original chunk of
8380   /// bits.
8381   /// \pre DAG != nullptr.
8382   uint64_t getOffsetFromBase() const {
8383     assert(DAG && "Missing context.");
8384     bool IsBigEndian =
8385         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8386     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8387     uint64_t Offset = Shift / 8;
8388     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8389     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8390            "The size of the original loaded type is not a multiple of a"
8391            " byte.");
8392     // If Offset is bigger than TySizeInBytes, it means we are loading all
8393     // zeros. This should have been optimized before in the process.
8394     assert(TySizeInBytes > Offset &&
8395            "Invalid shift amount for given loaded size");
8396     if (IsBigEndian)
8397       Offset = TySizeInBytes - Offset - getLoadedSize();
8398     return Offset;
8399   }
8400
8401   /// \brief Generate the sequence of instructions to load the slice
8402   /// represented by this object and redirect the uses of this slice to
8403   /// this new sequence of instructions.
8404   /// \pre this->Inst && this->Origin are valid Instructions and this
8405   /// object passed the legal check: LoadedSlice::isLegal returned true.
8406   /// \return The last instruction of the sequence used to load the slice.
8407   SDValue loadSlice() const {
8408     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8409     const SDValue &OldBaseAddr = Origin->getBasePtr();
8410     SDValue BaseAddr = OldBaseAddr;
8411     // Get the offset in that chunk of bytes w.r.t. the endianess.
8412     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8413     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8414     if (Offset) {
8415       // BaseAddr = BaseAddr + Offset.
8416       EVT ArithType = BaseAddr.getValueType();
8417       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8418                               DAG->getConstant(Offset, ArithType));
8419     }
8420
8421     // Create the type of the loaded slice according to its size.
8422     EVT SliceType = getLoadedType();
8423
8424     // Create the load for the slice.
8425     SDValue LastInst = DAG->getLoad(
8426         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8427         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8428         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8429     // If the final type is not the same as the loaded type, this means that
8430     // we have to pad with zero. Create a zero extend for that.
8431     EVT FinalType = Inst->getValueType(0);
8432     if (SliceType != FinalType)
8433       LastInst =
8434           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8435     return LastInst;
8436   }
8437
8438   /// \brief Check if this slice can be merged with an expensive cross register
8439   /// bank copy. E.g.,
8440   /// i = load i32
8441   /// f = bitcast i32 i to float
8442   bool canMergeExpensiveCrossRegisterBankCopy() const {
8443     if (!Inst || !Inst->hasOneUse())
8444       return false;
8445     SDNode *Use = *Inst->use_begin();
8446     if (Use->getOpcode() != ISD::BITCAST)
8447       return false;
8448     assert(DAG && "Missing context");
8449     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8450     EVT ResVT = Use->getValueType(0);
8451     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8452     const TargetRegisterClass *ArgRC =
8453         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8454     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8455       return false;
8456
8457     // At this point, we know that we perform a cross-register-bank copy.
8458     // Check if it is expensive.
8459     const TargetRegisterInfo *TRI =
8460         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8461     // Assume bitcasts are cheap, unless both register classes do not
8462     // explicitly share a common sub class.
8463     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8464       return false;
8465
8466     // Check if it will be merged with the load.
8467     // 1. Check the alignment constraint.
8468     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8469         ResVT.getTypeForEVT(*DAG->getContext()));
8470
8471     if (RequiredAlignment > getAlignment())
8472       return false;
8473
8474     // 2. Check that the load is a legal operation for that type.
8475     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8476       return false;
8477
8478     // 3. Check that we do not have a zext in the way.
8479     if (Inst->getValueType(0) != getLoadedType())
8480       return false;
8481
8482     return true;
8483   }
8484 };
8485 }
8486
8487 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8488 /// \p UsedBits looks like 0..0 1..1 0..0.
8489 static bool areUsedBitsDense(const APInt &UsedBits) {
8490   // If all the bits are one, this is dense!
8491   if (UsedBits.isAllOnesValue())
8492     return true;
8493
8494   // Get rid of the unused bits on the right.
8495   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8496   // Get rid of the unused bits on the left.
8497   if (NarrowedUsedBits.countLeadingZeros())
8498     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8499   // Check that the chunk of bits is completely used.
8500   return NarrowedUsedBits.isAllOnesValue();
8501 }
8502
8503 /// \brief Check whether or not \p First and \p Second are next to each other
8504 /// in memory. This means that there is no hole between the bits loaded
8505 /// by \p First and the bits loaded by \p Second.
8506 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8507                                      const LoadedSlice &Second) {
8508   assert(First.Origin == Second.Origin && First.Origin &&
8509          "Unable to match different memory origins.");
8510   APInt UsedBits = First.getUsedBits();
8511   assert((UsedBits & Second.getUsedBits()) == 0 &&
8512          "Slices are not supposed to overlap.");
8513   UsedBits |= Second.getUsedBits();
8514   return areUsedBitsDense(UsedBits);
8515 }
8516
8517 /// \brief Adjust the \p GlobalLSCost according to the target
8518 /// paring capabilities and the layout of the slices.
8519 /// \pre \p GlobalLSCost should account for at least as many loads as
8520 /// there is in the slices in \p LoadedSlices.
8521 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8522                                  LoadedSlice::Cost &GlobalLSCost) {
8523   unsigned NumberOfSlices = LoadedSlices.size();
8524   // If there is less than 2 elements, no pairing is possible.
8525   if (NumberOfSlices < 2)
8526     return;
8527
8528   // Sort the slices so that elements that are likely to be next to each
8529   // other in memory are next to each other in the list.
8530   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8531             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8532     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8533     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8534   });
8535   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8536   // First (resp. Second) is the first (resp. Second) potentially candidate
8537   // to be placed in a paired load.
8538   const LoadedSlice *First = nullptr;
8539   const LoadedSlice *Second = nullptr;
8540   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8541                 // Set the beginning of the pair.
8542                                                            First = Second) {
8543
8544     Second = &LoadedSlices[CurrSlice];
8545
8546     // If First is NULL, it means we start a new pair.
8547     // Get to the next slice.
8548     if (!First)
8549       continue;
8550
8551     EVT LoadedType = First->getLoadedType();
8552
8553     // If the types of the slices are different, we cannot pair them.
8554     if (LoadedType != Second->getLoadedType())
8555       continue;
8556
8557     // Check if the target supplies paired loads for this type.
8558     unsigned RequiredAlignment = 0;
8559     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8560       // move to the next pair, this type is hopeless.
8561       Second = nullptr;
8562       continue;
8563     }
8564     // Check if we meet the alignment requirement.
8565     if (RequiredAlignment > First->getAlignment())
8566       continue;
8567
8568     // Check that both loads are next to each other in memory.
8569     if (!areSlicesNextToEachOther(*First, *Second))
8570       continue;
8571
8572     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8573     --GlobalLSCost.Loads;
8574     // Move to the next pair.
8575     Second = nullptr;
8576   }
8577 }
8578
8579 /// \brief Check the profitability of all involved LoadedSlice.
8580 /// Currently, it is considered profitable if there is exactly two
8581 /// involved slices (1) which are (2) next to each other in memory, and
8582 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8583 ///
8584 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8585 /// the elements themselves.
8586 ///
8587 /// FIXME: When the cost model will be mature enough, we can relax
8588 /// constraints (1) and (2).
8589 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8590                                 const APInt &UsedBits, bool ForCodeSize) {
8591   unsigned NumberOfSlices = LoadedSlices.size();
8592   if (StressLoadSlicing)
8593     return NumberOfSlices > 1;
8594
8595   // Check (1).
8596   if (NumberOfSlices != 2)
8597     return false;
8598
8599   // Check (2).
8600   if (!areUsedBitsDense(UsedBits))
8601     return false;
8602
8603   // Check (3).
8604   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8605   // The original code has one big load.
8606   OrigCost.Loads = 1;
8607   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8608     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8609     // Accumulate the cost of all the slices.
8610     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8611     GlobalSlicingCost += SliceCost;
8612
8613     // Account as cost in the original configuration the gain obtained
8614     // with the current slices.
8615     OrigCost.addSliceGain(LS);
8616   }
8617
8618   // If the target supports paired load, adjust the cost accordingly.
8619   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8620   return OrigCost > GlobalSlicingCost;
8621 }
8622
8623 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8624 /// operations, split it in the various pieces being extracted.
8625 ///
8626 /// This sort of thing is introduced by SROA.
8627 /// This slicing takes care not to insert overlapping loads.
8628 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8629 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8630   if (Level < AfterLegalizeDAG)
8631     return false;
8632
8633   LoadSDNode *LD = cast<LoadSDNode>(N);
8634   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8635       !LD->getValueType(0).isInteger())
8636     return false;
8637
8638   // Keep track of already used bits to detect overlapping values.
8639   // In that case, we will just abort the transformation.
8640   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8641
8642   SmallVector<LoadedSlice, 4> LoadedSlices;
8643
8644   // Check if this load is used as several smaller chunks of bits.
8645   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8646   // of computation for each trunc.
8647   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8648        UI != UIEnd; ++UI) {
8649     // Skip the uses of the chain.
8650     if (UI.getUse().getResNo() != 0)
8651       continue;
8652
8653     SDNode *User = *UI;
8654     unsigned Shift = 0;
8655
8656     // Check if this is a trunc(lshr).
8657     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8658         isa<ConstantSDNode>(User->getOperand(1))) {
8659       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8660       User = *User->use_begin();
8661     }
8662
8663     // At this point, User is a Truncate, iff we encountered, trunc or
8664     // trunc(lshr).
8665     if (User->getOpcode() != ISD::TRUNCATE)
8666       return false;
8667
8668     // The width of the type must be a power of 2 and greater than 8-bits.
8669     // Otherwise the load cannot be represented in LLVM IR.
8670     // Moreover, if we shifted with a non-8-bits multiple, the slice
8671     // will be across several bytes. We do not support that.
8672     unsigned Width = User->getValueSizeInBits(0);
8673     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8674       return 0;
8675
8676     // Build the slice for this chain of computations.
8677     LoadedSlice LS(User, LD, Shift, &DAG);
8678     APInt CurrentUsedBits = LS.getUsedBits();
8679
8680     // Check if this slice overlaps with another.
8681     if ((CurrentUsedBits & UsedBits) != 0)
8682       return false;
8683     // Update the bits used globally.
8684     UsedBits |= CurrentUsedBits;
8685
8686     // Check if the new slice would be legal.
8687     if (!LS.isLegal())
8688       return false;
8689
8690     // Record the slice.
8691     LoadedSlices.push_back(LS);
8692   }
8693
8694   // Abort slicing if it does not seem to be profitable.
8695   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8696     return false;
8697
8698   ++SlicedLoads;
8699
8700   // Rewrite each chain to use an independent load.
8701   // By construction, each chain can be represented by a unique load.
8702
8703   // Prepare the argument for the new token factor for all the slices.
8704   SmallVector<SDValue, 8> ArgChains;
8705   for (SmallVectorImpl<LoadedSlice>::const_iterator
8706            LSIt = LoadedSlices.begin(),
8707            LSItEnd = LoadedSlices.end();
8708        LSIt != LSItEnd; ++LSIt) {
8709     SDValue SliceInst = LSIt->loadSlice();
8710     CombineTo(LSIt->Inst, SliceInst, true);
8711     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8712       SliceInst = SliceInst.getOperand(0);
8713     assert(SliceInst->getOpcode() == ISD::LOAD &&
8714            "It takes more than a zext to get to the loaded slice!!");
8715     ArgChains.push_back(SliceInst.getValue(1));
8716   }
8717
8718   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8719                               ArgChains);
8720   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8721   return true;
8722 }
8723
8724 /// Check to see if V is (and load (ptr), imm), where the load is having
8725 /// specific bytes cleared out.  If so, return the byte size being masked out
8726 /// and the shift amount.
8727 static std::pair<unsigned, unsigned>
8728 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8729   std::pair<unsigned, unsigned> Result(0, 0);
8730
8731   // Check for the structure we're looking for.
8732   if (V->getOpcode() != ISD::AND ||
8733       !isa<ConstantSDNode>(V->getOperand(1)) ||
8734       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8735     return Result;
8736
8737   // Check the chain and pointer.
8738   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8739   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8740
8741   // The store should be chained directly to the load or be an operand of a
8742   // tokenfactor.
8743   if (LD == Chain.getNode())
8744     ; // ok.
8745   else if (Chain->getOpcode() != ISD::TokenFactor)
8746     return Result; // Fail.
8747   else {
8748     bool isOk = false;
8749     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8750       if (Chain->getOperand(i).getNode() == LD) {
8751         isOk = true;
8752         break;
8753       }
8754     if (!isOk) return Result;
8755   }
8756
8757   // This only handles simple types.
8758   if (V.getValueType() != MVT::i16 &&
8759       V.getValueType() != MVT::i32 &&
8760       V.getValueType() != MVT::i64)
8761     return Result;
8762
8763   // Check the constant mask.  Invert it so that the bits being masked out are
8764   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8765   // follow the sign bit for uniformity.
8766   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8767   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8768   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8769   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8770   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8771   if (NotMaskLZ == 64) return Result;  // All zero mask.
8772
8773   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8774   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8775     return Result;
8776
8777   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8778   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8779     NotMaskLZ -= 64-V.getValueSizeInBits();
8780
8781   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8782   switch (MaskedBytes) {
8783   case 1:
8784   case 2:
8785   case 4: break;
8786   default: return Result; // All one mask, or 5-byte mask.
8787   }
8788
8789   // Verify that the first bit starts at a multiple of mask so that the access
8790   // is aligned the same as the access width.
8791   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8792
8793   Result.first = MaskedBytes;
8794   Result.second = NotMaskTZ/8;
8795   return Result;
8796 }
8797
8798
8799 /// Check to see if IVal is something that provides a value as specified by
8800 /// MaskInfo. If so, replace the specified store with a narrower store of
8801 /// truncated IVal.
8802 static SDNode *
8803 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8804                                 SDValue IVal, StoreSDNode *St,
8805                                 DAGCombiner *DC) {
8806   unsigned NumBytes = MaskInfo.first;
8807   unsigned ByteShift = MaskInfo.second;
8808   SelectionDAG &DAG = DC->getDAG();
8809
8810   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8811   // that uses this.  If not, this is not a replacement.
8812   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8813                                   ByteShift*8, (ByteShift+NumBytes)*8);
8814   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8815
8816   // Check that it is legal on the target to do this.  It is legal if the new
8817   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8818   // legalization.
8819   MVT VT = MVT::getIntegerVT(NumBytes*8);
8820   if (!DC->isTypeLegal(VT))
8821     return nullptr;
8822
8823   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8824   // shifted by ByteShift and truncated down to NumBytes.
8825   if (ByteShift)
8826     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8827                        DAG.getConstant(ByteShift*8,
8828                                     DC->getShiftAmountTy(IVal.getValueType())));
8829
8830   // Figure out the offset for the store and the alignment of the access.
8831   unsigned StOffset;
8832   unsigned NewAlign = St->getAlignment();
8833
8834   if (DAG.getTargetLoweringInfo().isLittleEndian())
8835     StOffset = ByteShift;
8836   else
8837     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8838
8839   SDValue Ptr = St->getBasePtr();
8840   if (StOffset) {
8841     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8842                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8843     NewAlign = MinAlign(NewAlign, StOffset);
8844   }
8845
8846   // Truncate down to the new size.
8847   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8848
8849   ++OpsNarrowed;
8850   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8851                       St->getPointerInfo().getWithOffset(StOffset),
8852                       false, false, NewAlign).getNode();
8853 }
8854
8855
8856 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8857 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8858 /// narrowing the load and store if it would end up being a win for performance
8859 /// or code size.
8860 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8861   StoreSDNode *ST  = cast<StoreSDNode>(N);
8862   if (ST->isVolatile())
8863     return SDValue();
8864
8865   SDValue Chain = ST->getChain();
8866   SDValue Value = ST->getValue();
8867   SDValue Ptr   = ST->getBasePtr();
8868   EVT VT = Value.getValueType();
8869
8870   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8871     return SDValue();
8872
8873   unsigned Opc = Value.getOpcode();
8874
8875   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8876   // is a byte mask indicating a consecutive number of bytes, check to see if
8877   // Y is known to provide just those bytes.  If so, we try to replace the
8878   // load + replace + store sequence with a single (narrower) store, which makes
8879   // the load dead.
8880   if (Opc == ISD::OR) {
8881     std::pair<unsigned, unsigned> MaskedLoad;
8882     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8883     if (MaskedLoad.first)
8884       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8885                                                   Value.getOperand(1), ST,this))
8886         return SDValue(NewST, 0);
8887
8888     // Or is commutative, so try swapping X and Y.
8889     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8890     if (MaskedLoad.first)
8891       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8892                                                   Value.getOperand(0), ST,this))
8893         return SDValue(NewST, 0);
8894   }
8895
8896   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8897       Value.getOperand(1).getOpcode() != ISD::Constant)
8898     return SDValue();
8899
8900   SDValue N0 = Value.getOperand(0);
8901   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8902       Chain == SDValue(N0.getNode(), 1)) {
8903     LoadSDNode *LD = cast<LoadSDNode>(N0);
8904     if (LD->getBasePtr() != Ptr ||
8905         LD->getPointerInfo().getAddrSpace() !=
8906         ST->getPointerInfo().getAddrSpace())
8907       return SDValue();
8908
8909     // Find the type to narrow it the load / op / store to.
8910     SDValue N1 = Value.getOperand(1);
8911     unsigned BitWidth = N1.getValueSizeInBits();
8912     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8913     if (Opc == ISD::AND)
8914       Imm ^= APInt::getAllOnesValue(BitWidth);
8915     if (Imm == 0 || Imm.isAllOnesValue())
8916       return SDValue();
8917     unsigned ShAmt = Imm.countTrailingZeros();
8918     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8919     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8920     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8921     while (NewBW < BitWidth &&
8922            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8923              TLI.isNarrowingProfitable(VT, NewVT))) {
8924       NewBW = NextPowerOf2(NewBW);
8925       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8926     }
8927     if (NewBW >= BitWidth)
8928       return SDValue();
8929
8930     // If the lsb changed does not start at the type bitwidth boundary,
8931     // start at the previous one.
8932     if (ShAmt % NewBW)
8933       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8934     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8935                                    std::min(BitWidth, ShAmt + NewBW));
8936     if ((Imm & Mask) == Imm) {
8937       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8938       if (Opc == ISD::AND)
8939         NewImm ^= APInt::getAllOnesValue(NewBW);
8940       uint64_t PtrOff = ShAmt / 8;
8941       // For big endian targets, we need to adjust the offset to the pointer to
8942       // load the correct bytes.
8943       if (TLI.isBigEndian())
8944         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8945
8946       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8947       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8948       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8949         return SDValue();
8950
8951       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8952                                    Ptr.getValueType(), Ptr,
8953                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8954       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8955                                   LD->getChain(), NewPtr,
8956                                   LD->getPointerInfo().getWithOffset(PtrOff),
8957                                   LD->isVolatile(), LD->isNonTemporal(),
8958                                   LD->isInvariant(), NewAlign,
8959                                   LD->getAAInfo());
8960       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8961                                    DAG.getConstant(NewImm, NewVT));
8962       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8963                                    NewVal, NewPtr,
8964                                    ST->getPointerInfo().getWithOffset(PtrOff),
8965                                    false, false, NewAlign);
8966
8967       AddToWorklist(NewPtr.getNode());
8968       AddToWorklist(NewLD.getNode());
8969       AddToWorklist(NewVal.getNode());
8970       WorklistRemover DeadNodes(*this);
8971       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8972       ++OpsNarrowed;
8973       return NewST;
8974     }
8975   }
8976
8977   return SDValue();
8978 }
8979
8980 /// For a given floating point load / store pair, if the load value isn't used
8981 /// by any other operations, then consider transforming the pair to integer
8982 /// load / store operations if the target deems the transformation profitable.
8983 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8984   StoreSDNode *ST  = cast<StoreSDNode>(N);
8985   SDValue Chain = ST->getChain();
8986   SDValue Value = ST->getValue();
8987   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8988       Value.hasOneUse() &&
8989       Chain == SDValue(Value.getNode(), 1)) {
8990     LoadSDNode *LD = cast<LoadSDNode>(Value);
8991     EVT VT = LD->getMemoryVT();
8992     if (!VT.isFloatingPoint() ||
8993         VT != ST->getMemoryVT() ||
8994         LD->isNonTemporal() ||
8995         ST->isNonTemporal() ||
8996         LD->getPointerInfo().getAddrSpace() != 0 ||
8997         ST->getPointerInfo().getAddrSpace() != 0)
8998       return SDValue();
8999
9000     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9001     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9002         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9003         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9004         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9005       return SDValue();
9006
9007     unsigned LDAlign = LD->getAlignment();
9008     unsigned STAlign = ST->getAlignment();
9009     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9010     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9011     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9012       return SDValue();
9013
9014     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9015                                 LD->getChain(), LD->getBasePtr(),
9016                                 LD->getPointerInfo(),
9017                                 false, false, false, LDAlign);
9018
9019     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9020                                  NewLD, ST->getBasePtr(),
9021                                  ST->getPointerInfo(),
9022                                  false, false, STAlign);
9023
9024     AddToWorklist(NewLD.getNode());
9025     AddToWorklist(NewST.getNode());
9026     WorklistRemover DeadNodes(*this);
9027     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9028     ++LdStFP2Int;
9029     return NewST;
9030   }
9031
9032   return SDValue();
9033 }
9034
9035 /// Helper struct to parse and store a memory address as base + index + offset.
9036 /// We ignore sign extensions when it is safe to do so.
9037 /// The following two expressions are not equivalent. To differentiate we need
9038 /// to store whether there was a sign extension involved in the index
9039 /// computation.
9040 ///  (load (i64 add (i64 copyfromreg %c)
9041 ///                 (i64 signextend (add (i8 load %index)
9042 ///                                      (i8 1))))
9043 /// vs
9044 ///
9045 /// (load (i64 add (i64 copyfromreg %c)
9046 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9047 ///                                         (i32 1)))))
9048 struct BaseIndexOffset {
9049   SDValue Base;
9050   SDValue Index;
9051   int64_t Offset;
9052   bool IsIndexSignExt;
9053
9054   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9055
9056   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9057                   bool IsIndexSignExt) :
9058     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9059
9060   bool equalBaseIndex(const BaseIndexOffset &Other) {
9061     return Other.Base == Base && Other.Index == Index &&
9062       Other.IsIndexSignExt == IsIndexSignExt;
9063   }
9064
9065   /// Parses tree in Ptr for base, index, offset addresses.
9066   static BaseIndexOffset match(SDValue Ptr) {
9067     bool IsIndexSignExt = false;
9068
9069     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9070     // instruction, then it could be just the BASE or everything else we don't
9071     // know how to handle. Just use Ptr as BASE and give up.
9072     if (Ptr->getOpcode() != ISD::ADD)
9073       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9074
9075     // We know that we have at least an ADD instruction. Try to pattern match
9076     // the simple case of BASE + OFFSET.
9077     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9078       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9079       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9080                               IsIndexSignExt);
9081     }
9082
9083     // Inside a loop the current BASE pointer is calculated using an ADD and a
9084     // MUL instruction. In this case Ptr is the actual BASE pointer.
9085     // (i64 add (i64 %array_ptr)
9086     //          (i64 mul (i64 %induction_var)
9087     //                   (i64 %element_size)))
9088     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9089       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9090
9091     // Look at Base + Index + Offset cases.
9092     SDValue Base = Ptr->getOperand(0);
9093     SDValue IndexOffset = Ptr->getOperand(1);
9094
9095     // Skip signextends.
9096     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9097       IndexOffset = IndexOffset->getOperand(0);
9098       IsIndexSignExt = true;
9099     }
9100
9101     // Either the case of Base + Index (no offset) or something else.
9102     if (IndexOffset->getOpcode() != ISD::ADD)
9103       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9104
9105     // Now we have the case of Base + Index + offset.
9106     SDValue Index = IndexOffset->getOperand(0);
9107     SDValue Offset = IndexOffset->getOperand(1);
9108
9109     if (!isa<ConstantSDNode>(Offset))
9110       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9111
9112     // Ignore signextends.
9113     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9114       Index = Index->getOperand(0);
9115       IsIndexSignExt = true;
9116     } else IsIndexSignExt = false;
9117
9118     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9119     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9120   }
9121 };
9122
9123 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9124 /// is located in a sequence of memory operations connected by a chain.
9125 struct MemOpLink {
9126   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9127     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9128   // Ptr to the mem node.
9129   LSBaseSDNode *MemNode;
9130   // Offset from the base ptr.
9131   int64_t OffsetFromBase;
9132   // What is the sequence number of this mem node.
9133   // Lowest mem operand in the DAG starts at zero.
9134   unsigned SequenceNum;
9135 };
9136
9137 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9138   EVT MemVT = St->getMemoryVT();
9139   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9140   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9141     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9142
9143   // Don't merge vectors into wider inputs.
9144   if (MemVT.isVector() || !MemVT.isSimple())
9145     return false;
9146
9147   // Perform an early exit check. Do not bother looking at stored values that
9148   // are not constants or loads.
9149   SDValue StoredVal = St->getValue();
9150   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9151   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9152       !IsLoadSrc)
9153     return false;
9154
9155   // Only look at ends of store sequences.
9156   SDValue Chain = SDValue(St, 0);
9157   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9158     return false;
9159
9160   // This holds the base pointer, index, and the offset in bytes from the base
9161   // pointer.
9162   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9163
9164   // We must have a base and an offset.
9165   if (!BasePtr.Base.getNode())
9166     return false;
9167
9168   // Do not handle stores to undef base pointers.
9169   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9170     return false;
9171
9172   // Save the LoadSDNodes that we find in the chain.
9173   // We need to make sure that these nodes do not interfere with
9174   // any of the store nodes.
9175   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9176
9177   // Save the StoreSDNodes that we find in the chain.
9178   SmallVector<MemOpLink, 8> StoreNodes;
9179
9180   // Walk up the chain and look for nodes with offsets from the same
9181   // base pointer. Stop when reaching an instruction with a different kind
9182   // or instruction which has a different base pointer.
9183   unsigned Seq = 0;
9184   StoreSDNode *Index = St;
9185   while (Index) {
9186     // If the chain has more than one use, then we can't reorder the mem ops.
9187     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9188       break;
9189
9190     // Find the base pointer and offset for this memory node.
9191     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9192
9193     // Check that the base pointer is the same as the original one.
9194     if (!Ptr.equalBaseIndex(BasePtr))
9195       break;
9196
9197     // Check that the alignment is the same.
9198     if (Index->getAlignment() != St->getAlignment())
9199       break;
9200
9201     // The memory operands must not be volatile.
9202     if (Index->isVolatile() || Index->isIndexed())
9203       break;
9204
9205     // No truncation.
9206     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9207       if (St->isTruncatingStore())
9208         break;
9209
9210     // The stored memory type must be the same.
9211     if (Index->getMemoryVT() != MemVT)
9212       break;
9213
9214     // We do not allow unaligned stores because we want to prevent overriding
9215     // stores.
9216     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9217       break;
9218
9219     // We found a potential memory operand to merge.
9220     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9221
9222     // Find the next memory operand in the chain. If the next operand in the
9223     // chain is a store then move up and continue the scan with the next
9224     // memory operand. If the next operand is a load save it and use alias
9225     // information to check if it interferes with anything.
9226     SDNode *NextInChain = Index->getChain().getNode();
9227     while (1) {
9228       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9229         // We found a store node. Use it for the next iteration.
9230         Index = STn;
9231         break;
9232       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9233         if (Ldn->isVolatile()) {
9234           Index = nullptr;
9235           break;
9236         }
9237
9238         // Save the load node for later. Continue the scan.
9239         AliasLoadNodes.push_back(Ldn);
9240         NextInChain = Ldn->getChain().getNode();
9241         continue;
9242       } else {
9243         Index = nullptr;
9244         break;
9245       }
9246     }
9247   }
9248
9249   // Check if there is anything to merge.
9250   if (StoreNodes.size() < 2)
9251     return false;
9252
9253   // Sort the memory operands according to their distance from the base pointer.
9254   std::sort(StoreNodes.begin(), StoreNodes.end(),
9255             [](MemOpLink LHS, MemOpLink RHS) {
9256     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9257            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9258             LHS.SequenceNum > RHS.SequenceNum);
9259   });
9260
9261   // Scan the memory operations on the chain and find the first non-consecutive
9262   // store memory address.
9263   unsigned LastConsecutiveStore = 0;
9264   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9265   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9266
9267     // Check that the addresses are consecutive starting from the second
9268     // element in the list of stores.
9269     if (i > 0) {
9270       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9271       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9272         break;
9273     }
9274
9275     bool Alias = false;
9276     // Check if this store interferes with any of the loads that we found.
9277     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9278       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9279         Alias = true;
9280         break;
9281       }
9282     // We found a load that alias with this store. Stop the sequence.
9283     if (Alias)
9284       break;
9285
9286     // Mark this node as useful.
9287     LastConsecutiveStore = i;
9288   }
9289
9290   // The node with the lowest store address.
9291   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9292
9293   // Store the constants into memory as one consecutive store.
9294   if (!IsLoadSrc) {
9295     unsigned LastLegalType = 0;
9296     unsigned LastLegalVectorType = 0;
9297     bool NonZero = false;
9298     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9299       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9300       SDValue StoredVal = St->getValue();
9301
9302       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9303         NonZero |= !C->isNullValue();
9304       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9305         NonZero |= !C->getConstantFPValue()->isNullValue();
9306       } else {
9307         // Non-constant.
9308         break;
9309       }
9310
9311       // Find a legal type for the constant store.
9312       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9313       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9314       if (TLI.isTypeLegal(StoreTy))
9315         LastLegalType = i+1;
9316       // Or check whether a truncstore is legal.
9317       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9318                TargetLowering::TypePromoteInteger) {
9319         EVT LegalizedStoredValueTy =
9320           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9321         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9322           LastLegalType = i+1;
9323       }
9324
9325       // Find a legal type for the vector store.
9326       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9327       if (TLI.isTypeLegal(Ty))
9328         LastLegalVectorType = i + 1;
9329     }
9330
9331     // We only use vectors if the constant is known to be zero and the
9332     // function is not marked with the noimplicitfloat attribute.
9333     if (NonZero || NoVectors)
9334       LastLegalVectorType = 0;
9335
9336     // Check if we found a legal integer type to store.
9337     if (LastLegalType == 0 && LastLegalVectorType == 0)
9338       return false;
9339
9340     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9341     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9342
9343     // Make sure we have something to merge.
9344     if (NumElem < 2)
9345       return false;
9346
9347     unsigned EarliestNodeUsed = 0;
9348     for (unsigned i=0; i < NumElem; ++i) {
9349       // Find a chain for the new wide-store operand. Notice that some
9350       // of the store nodes that we found may not be selected for inclusion
9351       // in the wide store. The chain we use needs to be the chain of the
9352       // earliest store node which is *used* and replaced by the wide store.
9353       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9354         EarliestNodeUsed = i;
9355     }
9356
9357     // The earliest Node in the DAG.
9358     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9359     SDLoc DL(StoreNodes[0].MemNode);
9360
9361     SDValue StoredVal;
9362     if (UseVector) {
9363       // Find a legal type for the vector store.
9364       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9365       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9366       StoredVal = DAG.getConstant(0, Ty);
9367     } else {
9368       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9369       APInt StoreInt(StoreBW, 0);
9370
9371       // Construct a single integer constant which is made of the smaller
9372       // constant inputs.
9373       bool IsLE = TLI.isLittleEndian();
9374       for (unsigned i = 0; i < NumElem ; ++i) {
9375         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9376         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9377         SDValue Val = St->getValue();
9378         StoreInt<<=ElementSizeBytes*8;
9379         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9380           StoreInt|=C->getAPIntValue().zext(StoreBW);
9381         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9382           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9383         } else {
9384           assert(false && "Invalid constant element type");
9385         }
9386       }
9387
9388       // Create the new Load and Store operations.
9389       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9390       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9391     }
9392
9393     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9394                                     FirstInChain->getBasePtr(),
9395                                     FirstInChain->getPointerInfo(),
9396                                     false, false,
9397                                     FirstInChain->getAlignment());
9398
9399     // Replace the first store with the new store
9400     CombineTo(EarliestOp, NewStore);
9401     // Erase all other stores.
9402     for (unsigned i = 0; i < NumElem ; ++i) {
9403       if (StoreNodes[i].MemNode == EarliestOp)
9404         continue;
9405       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9406       // ReplaceAllUsesWith will replace all uses that existed when it was
9407       // called, but graph optimizations may cause new ones to appear. For
9408       // example, the case in pr14333 looks like
9409       //
9410       //  St's chain -> St -> another store -> X
9411       //
9412       // And the only difference from St to the other store is the chain.
9413       // When we change it's chain to be St's chain they become identical,
9414       // get CSEed and the net result is that X is now a use of St.
9415       // Since we know that St is redundant, just iterate.
9416       while (!St->use_empty())
9417         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9418       deleteAndRecombine(St);
9419     }
9420
9421     return true;
9422   }
9423
9424   // Below we handle the case of multiple consecutive stores that
9425   // come from multiple consecutive loads. We merge them into a single
9426   // wide load and a single wide store.
9427
9428   // Look for load nodes which are used by the stored values.
9429   SmallVector<MemOpLink, 8> LoadNodes;
9430
9431   // Find acceptable loads. Loads need to have the same chain (token factor),
9432   // must not be zext, volatile, indexed, and they must be consecutive.
9433   BaseIndexOffset LdBasePtr;
9434   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9435     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9436     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9437     if (!Ld) break;
9438
9439     // Loads must only have one use.
9440     if (!Ld->hasNUsesOfValue(1, 0))
9441       break;
9442
9443     // Check that the alignment is the same as the stores.
9444     if (Ld->getAlignment() != St->getAlignment())
9445       break;
9446
9447     // The memory operands must not be volatile.
9448     if (Ld->isVolatile() || Ld->isIndexed())
9449       break;
9450
9451     // We do not accept ext loads.
9452     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9453       break;
9454
9455     // The stored memory type must be the same.
9456     if (Ld->getMemoryVT() != MemVT)
9457       break;
9458
9459     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9460     // If this is not the first ptr that we check.
9461     if (LdBasePtr.Base.getNode()) {
9462       // The base ptr must be the same.
9463       if (!LdPtr.equalBaseIndex(LdBasePtr))
9464         break;
9465     } else {
9466       // Check that all other base pointers are the same as this one.
9467       LdBasePtr = LdPtr;
9468     }
9469
9470     // We found a potential memory operand to merge.
9471     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9472   }
9473
9474   if (LoadNodes.size() < 2)
9475     return false;
9476
9477   // If we have load/store pair instructions and we only have two values,
9478   // don't bother.
9479   unsigned RequiredAlignment;
9480   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9481       St->getAlignment() >= RequiredAlignment)
9482     return false;
9483
9484   // Scan the memory operations on the chain and find the first non-consecutive
9485   // load memory address. These variables hold the index in the store node
9486   // array.
9487   unsigned LastConsecutiveLoad = 0;
9488   // This variable refers to the size and not index in the array.
9489   unsigned LastLegalVectorType = 0;
9490   unsigned LastLegalIntegerType = 0;
9491   StartAddress = LoadNodes[0].OffsetFromBase;
9492   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9493   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9494     // All loads much share the same chain.
9495     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9496       break;
9497
9498     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9499     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9500       break;
9501     LastConsecutiveLoad = i;
9502
9503     // Find a legal type for the vector store.
9504     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9505     if (TLI.isTypeLegal(StoreTy))
9506       LastLegalVectorType = i + 1;
9507
9508     // Find a legal type for the integer store.
9509     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9510     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9511     if (TLI.isTypeLegal(StoreTy))
9512       LastLegalIntegerType = i + 1;
9513     // Or check whether a truncstore and extload is legal.
9514     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9515              TargetLowering::TypePromoteInteger) {
9516       EVT LegalizedStoredValueTy =
9517         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9518       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9519           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9520           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9521           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9522         LastLegalIntegerType = i+1;
9523     }
9524   }
9525
9526   // Only use vector types if the vector type is larger than the integer type.
9527   // If they are the same, use integers.
9528   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9529   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9530
9531   // We add +1 here because the LastXXX variables refer to location while
9532   // the NumElem refers to array/index size.
9533   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9534   NumElem = std::min(LastLegalType, NumElem);
9535
9536   if (NumElem < 2)
9537     return false;
9538
9539   // The earliest Node in the DAG.
9540   unsigned EarliestNodeUsed = 0;
9541   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9542   for (unsigned i=1; i<NumElem; ++i) {
9543     // Find a chain for the new wide-store operand. Notice that some
9544     // of the store nodes that we found may not be selected for inclusion
9545     // in the wide store. The chain we use needs to be the chain of the
9546     // earliest store node which is *used* and replaced by the wide store.
9547     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9548       EarliestNodeUsed = i;
9549   }
9550
9551   // Find if it is better to use vectors or integers to load and store
9552   // to memory.
9553   EVT JointMemOpVT;
9554   if (UseVectorTy) {
9555     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9556   } else {
9557     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9558     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9559   }
9560
9561   SDLoc LoadDL(LoadNodes[0].MemNode);
9562   SDLoc StoreDL(StoreNodes[0].MemNode);
9563
9564   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9565   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9566                                 FirstLoad->getChain(),
9567                                 FirstLoad->getBasePtr(),
9568                                 FirstLoad->getPointerInfo(),
9569                                 false, false, false,
9570                                 FirstLoad->getAlignment());
9571
9572   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9573                                   FirstInChain->getBasePtr(),
9574                                   FirstInChain->getPointerInfo(), false, false,
9575                                   FirstInChain->getAlignment());
9576
9577   // Replace one of the loads with the new load.
9578   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9579   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9580                                 SDValue(NewLoad.getNode(), 1));
9581
9582   // Remove the rest of the load chains.
9583   for (unsigned i = 1; i < NumElem ; ++i) {
9584     // Replace all chain users of the old load nodes with the chain of the new
9585     // load node.
9586     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9587     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9588   }
9589
9590   // Replace the first store with the new store.
9591   CombineTo(EarliestOp, NewStore);
9592   // Erase all other stores.
9593   for (unsigned i = 0; i < NumElem ; ++i) {
9594     // Remove all Store nodes.
9595     if (StoreNodes[i].MemNode == EarliestOp)
9596       continue;
9597     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9598     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9599     deleteAndRecombine(St);
9600   }
9601
9602   return true;
9603 }
9604
9605 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9606   StoreSDNode *ST  = cast<StoreSDNode>(N);
9607   SDValue Chain = ST->getChain();
9608   SDValue Value = ST->getValue();
9609   SDValue Ptr   = ST->getBasePtr();
9610
9611   // If this is a store of a bit convert, store the input value if the
9612   // resultant store does not need a higher alignment than the original.
9613   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9614       ST->isUnindexed()) {
9615     unsigned OrigAlign = ST->getAlignment();
9616     EVT SVT = Value.getOperand(0).getValueType();
9617     unsigned Align = TLI.getDataLayout()->
9618       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9619     if (Align <= OrigAlign &&
9620         ((!LegalOperations && !ST->isVolatile()) ||
9621          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9622       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9623                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9624                           ST->isNonTemporal(), OrigAlign,
9625                           ST->getAAInfo());
9626   }
9627
9628   // Turn 'store undef, Ptr' -> nothing.
9629   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9630     return Chain;
9631
9632   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9633   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9634     // NOTE: If the original store is volatile, this transform must not increase
9635     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9636     // processor operation but an i64 (which is not legal) requires two.  So the
9637     // transform should not be done in this case.
9638     if (Value.getOpcode() != ISD::TargetConstantFP) {
9639       SDValue Tmp;
9640       switch (CFP->getSimpleValueType(0).SimpleTy) {
9641       default: llvm_unreachable("Unknown FP type");
9642       case MVT::f16:    // We don't do this for these yet.
9643       case MVT::f80:
9644       case MVT::f128:
9645       case MVT::ppcf128:
9646         break;
9647       case MVT::f32:
9648         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9649             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9650           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9651                               bitcastToAPInt().getZExtValue(), MVT::i32);
9652           return DAG.getStore(Chain, SDLoc(N), Tmp,
9653                               Ptr, ST->getMemOperand());
9654         }
9655         break;
9656       case MVT::f64:
9657         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9658              !ST->isVolatile()) ||
9659             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9660           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9661                                 getZExtValue(), MVT::i64);
9662           return DAG.getStore(Chain, SDLoc(N), Tmp,
9663                               Ptr, ST->getMemOperand());
9664         }
9665
9666         if (!ST->isVolatile() &&
9667             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9668           // Many FP stores are not made apparent until after legalize, e.g. for
9669           // argument passing.  Since this is so common, custom legalize the
9670           // 64-bit integer store into two 32-bit stores.
9671           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9672           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9673           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9674           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9675
9676           unsigned Alignment = ST->getAlignment();
9677           bool isVolatile = ST->isVolatile();
9678           bool isNonTemporal = ST->isNonTemporal();
9679           AAMDNodes AAInfo = ST->getAAInfo();
9680
9681           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9682                                      Ptr, ST->getPointerInfo(),
9683                                      isVolatile, isNonTemporal,
9684                                      ST->getAlignment(), AAInfo);
9685           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9686                             DAG.getConstant(4, Ptr.getValueType()));
9687           Alignment = MinAlign(Alignment, 4U);
9688           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9689                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9690                                      isVolatile, isNonTemporal,
9691                                      Alignment, AAInfo);
9692           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9693                              St0, St1);
9694         }
9695
9696         break;
9697       }
9698     }
9699   }
9700
9701   // Try to infer better alignment information than the store already has.
9702   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9703     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9704       if (Align > ST->getAlignment())
9705         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9706                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9707                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9708                                  ST->getAAInfo());
9709     }
9710   }
9711
9712   // Try transforming a pair floating point load / store ops to integer
9713   // load / store ops.
9714   SDValue NewST = TransformFPLoadStorePair(N);
9715   if (NewST.getNode())
9716     return NewST;
9717
9718   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9719     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9720 #ifndef NDEBUG
9721   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9722       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9723     UseAA = false;
9724 #endif
9725   if (UseAA && ST->isUnindexed()) {
9726     // Walk up chain skipping non-aliasing memory nodes.
9727     SDValue BetterChain = FindBetterChain(N, Chain);
9728
9729     // If there is a better chain.
9730     if (Chain != BetterChain) {
9731       SDValue ReplStore;
9732
9733       // Replace the chain to avoid dependency.
9734       if (ST->isTruncatingStore()) {
9735         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9736                                       ST->getMemoryVT(), ST->getMemOperand());
9737       } else {
9738         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9739                                  ST->getMemOperand());
9740       }
9741
9742       // Create token to keep both nodes around.
9743       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9744                                   MVT::Other, Chain, ReplStore);
9745
9746       // Make sure the new and old chains are cleaned up.
9747       AddToWorklist(Token.getNode());
9748
9749       // Don't add users to work list.
9750       return CombineTo(N, Token, false);
9751     }
9752   }
9753
9754   // Try transforming N to an indexed store.
9755   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9756     return SDValue(N, 0);
9757
9758   // FIXME: is there such a thing as a truncating indexed store?
9759   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9760       Value.getValueType().isInteger()) {
9761     // See if we can simplify the input to this truncstore with knowledge that
9762     // only the low bits are being used.  For example:
9763     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9764     SDValue Shorter =
9765       GetDemandedBits(Value,
9766                       APInt::getLowBitsSet(
9767                         Value.getValueType().getScalarType().getSizeInBits(),
9768                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9769     AddToWorklist(Value.getNode());
9770     if (Shorter.getNode())
9771       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9772                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9773
9774     // Otherwise, see if we can simplify the operation with
9775     // SimplifyDemandedBits, which only works if the value has a single use.
9776     if (SimplifyDemandedBits(Value,
9777                         APInt::getLowBitsSet(
9778                           Value.getValueType().getScalarType().getSizeInBits(),
9779                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9780       return SDValue(N, 0);
9781   }
9782
9783   // If this is a load followed by a store to the same location, then the store
9784   // is dead/noop.
9785   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9786     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9787         ST->isUnindexed() && !ST->isVolatile() &&
9788         // There can't be any side effects between the load and store, such as
9789         // a call or store.
9790         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9791       // The store is dead, remove it.
9792       return Chain;
9793     }
9794   }
9795
9796   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9797   // truncating store.  We can do this even if this is already a truncstore.
9798   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9799       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9800       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9801                             ST->getMemoryVT())) {
9802     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9803                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9804   }
9805
9806   // Only perform this optimization before the types are legal, because we
9807   // don't want to perform this optimization on every DAGCombine invocation.
9808   if (!LegalTypes) {
9809     bool EverChanged = false;
9810
9811     do {
9812       // There can be multiple store sequences on the same chain.
9813       // Keep trying to merge store sequences until we are unable to do so
9814       // or until we merge the last store on the chain.
9815       bool Changed = MergeConsecutiveStores(ST);
9816       EverChanged |= Changed;
9817       if (!Changed) break;
9818     } while (ST->getOpcode() != ISD::DELETED_NODE);
9819
9820     if (EverChanged)
9821       return SDValue(N, 0);
9822   }
9823
9824   return ReduceLoadOpStoreWidth(N);
9825 }
9826
9827 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9828   SDValue InVec = N->getOperand(0);
9829   SDValue InVal = N->getOperand(1);
9830   SDValue EltNo = N->getOperand(2);
9831   SDLoc dl(N);
9832
9833   // If the inserted element is an UNDEF, just use the input vector.
9834   if (InVal.getOpcode() == ISD::UNDEF)
9835     return InVec;
9836
9837   EVT VT = InVec.getValueType();
9838
9839   // If we can't generate a legal BUILD_VECTOR, exit
9840   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9841     return SDValue();
9842
9843   // Check that we know which element is being inserted
9844   if (!isa<ConstantSDNode>(EltNo))
9845     return SDValue();
9846   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9847
9848   // Canonicalize insert_vector_elt dag nodes.
9849   // Example:
9850   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9851   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9852   //
9853   // Do this only if the child insert_vector node has one use; also
9854   // do this only if indices are both constants and Idx1 < Idx0.
9855   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9856       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9857     unsigned OtherElt =
9858       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9859     if (Elt < OtherElt) {
9860       // Swap nodes.
9861       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9862                                   InVec.getOperand(0), InVal, EltNo);
9863       AddToWorklist(NewOp.getNode());
9864       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9865                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9866     }
9867   }
9868
9869   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9870   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9871   // vector elements.
9872   SmallVector<SDValue, 8> Ops;
9873   // Do not combine these two vectors if the output vector will not replace
9874   // the input vector.
9875   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9876     Ops.append(InVec.getNode()->op_begin(),
9877                InVec.getNode()->op_end());
9878   } else if (InVec.getOpcode() == ISD::UNDEF) {
9879     unsigned NElts = VT.getVectorNumElements();
9880     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9881   } else {
9882     return SDValue();
9883   }
9884
9885   // Insert the element
9886   if (Elt < Ops.size()) {
9887     // All the operands of BUILD_VECTOR must have the same type;
9888     // we enforce that here.
9889     EVT OpVT = Ops[0].getValueType();
9890     if (InVal.getValueType() != OpVT)
9891       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9892                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9893                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9894     Ops[Elt] = InVal;
9895   }
9896
9897   // Return the new vector
9898   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9899 }
9900
9901 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9902     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9903   EVT ResultVT = EVE->getValueType(0);
9904   EVT VecEltVT = InVecVT.getVectorElementType();
9905   unsigned Align = OriginalLoad->getAlignment();
9906   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9907       VecEltVT.getTypeForEVT(*DAG.getContext()));
9908
9909   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9910     return SDValue();
9911
9912   Align = NewAlign;
9913
9914   SDValue NewPtr = OriginalLoad->getBasePtr();
9915   SDValue Offset;
9916   EVT PtrType = NewPtr.getValueType();
9917   MachinePointerInfo MPI;
9918   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9919     int Elt = ConstEltNo->getZExtValue();
9920     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9921     if (TLI.isBigEndian())
9922       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9923     Offset = DAG.getConstant(PtrOff, PtrType);
9924     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9925   } else {
9926     Offset = DAG.getNode(
9927         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9928         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9929     if (TLI.isBigEndian())
9930       Offset = DAG.getNode(
9931           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9932           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9933     MPI = OriginalLoad->getPointerInfo();
9934   }
9935   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9936
9937   // The replacement we need to do here is a little tricky: we need to
9938   // replace an extractelement of a load with a load.
9939   // Use ReplaceAllUsesOfValuesWith to do the replacement.
9940   // Note that this replacement assumes that the extractvalue is the only
9941   // use of the load; that's okay because we don't want to perform this
9942   // transformation in other cases anyway.
9943   SDValue Load;
9944   SDValue Chain;
9945   if (ResultVT.bitsGT(VecEltVT)) {
9946     // If the result type of vextract is wider than the load, then issue an
9947     // extending load instead.
9948     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9949                                    ? ISD::ZEXTLOAD
9950                                    : ISD::EXTLOAD;
9951     Load = DAG.getExtLoad(
9952         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9953         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9954         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9955     Chain = Load.getValue(1);
9956   } else {
9957     Load = DAG.getLoad(
9958         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9959         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9960         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9961     Chain = Load.getValue(1);
9962     if (ResultVT.bitsLT(VecEltVT))
9963       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9964     else
9965       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9966   }
9967   WorklistRemover DeadNodes(*this);
9968   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9969   SDValue To[] = { Load, Chain };
9970   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9971   // Since we're explicitly calling ReplaceAllUses, add the new node to the
9972   // worklist explicitly as well.
9973   AddToWorklist(Load.getNode());
9974   AddUsersToWorklist(Load.getNode()); // Add users too
9975   // Make sure to revisit this node to clean it up; it will usually be dead.
9976   AddToWorklist(EVE);
9977   ++OpsNarrowed;
9978   return SDValue(EVE, 0);
9979 }
9980
9981 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9982   // (vextract (scalar_to_vector val, 0) -> val
9983   SDValue InVec = N->getOperand(0);
9984   EVT VT = InVec.getValueType();
9985   EVT NVT = N->getValueType(0);
9986
9987   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9988     // Check if the result type doesn't match the inserted element type. A
9989     // SCALAR_TO_VECTOR may truncate the inserted element and the
9990     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9991     SDValue InOp = InVec.getOperand(0);
9992     if (InOp.getValueType() != NVT) {
9993       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9994       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9995     }
9996     return InOp;
9997   }
9998
9999   SDValue EltNo = N->getOperand(1);
10000   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10001
10002   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10003   // We only perform this optimization before the op legalization phase because
10004   // we may introduce new vector instructions which are not backed by TD
10005   // patterns. For example on AVX, extracting elements from a wide vector
10006   // without using extract_subvector. However, if we can find an underlying
10007   // scalar value, then we can always use that.
10008   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10009       && ConstEltNo) {
10010     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10011     int NumElem = VT.getVectorNumElements();
10012     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10013     // Find the new index to extract from.
10014     int OrigElt = SVOp->getMaskElt(Elt);
10015
10016     // Extracting an undef index is undef.
10017     if (OrigElt == -1)
10018       return DAG.getUNDEF(NVT);
10019
10020     // Select the right vector half to extract from.
10021     SDValue SVInVec;
10022     if (OrigElt < NumElem) {
10023       SVInVec = InVec->getOperand(0);
10024     } else {
10025       SVInVec = InVec->getOperand(1);
10026       OrigElt -= NumElem;
10027     }
10028
10029     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10030       SDValue InOp = SVInVec.getOperand(OrigElt);
10031       if (InOp.getValueType() != NVT) {
10032         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10033         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10034       }
10035
10036       return InOp;
10037     }
10038
10039     // FIXME: We should handle recursing on other vector shuffles and
10040     // scalar_to_vector here as well.
10041
10042     if (!LegalOperations) {
10043       EVT IndexTy = TLI.getVectorIdxTy();
10044       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10045                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10046     }
10047   }
10048
10049   bool BCNumEltsChanged = false;
10050   EVT ExtVT = VT.getVectorElementType();
10051   EVT LVT = ExtVT;
10052
10053   // If the result of load has to be truncated, then it's not necessarily
10054   // profitable.
10055   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10056     return SDValue();
10057
10058   if (InVec.getOpcode() == ISD::BITCAST) {
10059     // Don't duplicate a load with other uses.
10060     if (!InVec.hasOneUse())
10061       return SDValue();
10062
10063     EVT BCVT = InVec.getOperand(0).getValueType();
10064     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10065       return SDValue();
10066     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10067       BCNumEltsChanged = true;
10068     InVec = InVec.getOperand(0);
10069     ExtVT = BCVT.getVectorElementType();
10070   }
10071
10072   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10073   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10074       ISD::isNormalLoad(InVec.getNode()) &&
10075       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10076     SDValue Index = N->getOperand(1);
10077     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10078       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10079                                                            OrigLoad);
10080   }
10081
10082   // Perform only after legalization to ensure build_vector / vector_shuffle
10083   // optimizations have already been done.
10084   if (!LegalOperations) return SDValue();
10085
10086   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10087   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10088   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10089
10090   if (ConstEltNo) {
10091     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10092
10093     LoadSDNode *LN0 = nullptr;
10094     const ShuffleVectorSDNode *SVN = nullptr;
10095     if (ISD::isNormalLoad(InVec.getNode())) {
10096       LN0 = cast<LoadSDNode>(InVec);
10097     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10098                InVec.getOperand(0).getValueType() == ExtVT &&
10099                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10100       // Don't duplicate a load with other uses.
10101       if (!InVec.hasOneUse())
10102         return SDValue();
10103
10104       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10105     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10106       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10107       // =>
10108       // (load $addr+1*size)
10109
10110       // Don't duplicate a load with other uses.
10111       if (!InVec.hasOneUse())
10112         return SDValue();
10113
10114       // If the bit convert changed the number of elements, it is unsafe
10115       // to examine the mask.
10116       if (BCNumEltsChanged)
10117         return SDValue();
10118
10119       // Select the input vector, guarding against out of range extract vector.
10120       unsigned NumElems = VT.getVectorNumElements();
10121       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10122       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10123
10124       if (InVec.getOpcode() == ISD::BITCAST) {
10125         // Don't duplicate a load with other uses.
10126         if (!InVec.hasOneUse())
10127           return SDValue();
10128
10129         InVec = InVec.getOperand(0);
10130       }
10131       if (ISD::isNormalLoad(InVec.getNode())) {
10132         LN0 = cast<LoadSDNode>(InVec);
10133         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10134         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10135       }
10136     }
10137
10138     // Make sure we found a non-volatile load and the extractelement is
10139     // the only use.
10140     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10141       return SDValue();
10142
10143     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10144     if (Elt == -1)
10145       return DAG.getUNDEF(LVT);
10146
10147     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10148   }
10149
10150   return SDValue();
10151 }
10152
10153 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10154 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10155   // We perform this optimization post type-legalization because
10156   // the type-legalizer often scalarizes integer-promoted vectors.
10157   // Performing this optimization before may create bit-casts which
10158   // will be type-legalized to complex code sequences.
10159   // We perform this optimization only before the operation legalizer because we
10160   // may introduce illegal operations.
10161   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10162     return SDValue();
10163
10164   unsigned NumInScalars = N->getNumOperands();
10165   SDLoc dl(N);
10166   EVT VT = N->getValueType(0);
10167
10168   // Check to see if this is a BUILD_VECTOR of a bunch of values
10169   // which come from any_extend or zero_extend nodes. If so, we can create
10170   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10171   // optimizations. We do not handle sign-extend because we can't fill the sign
10172   // using shuffles.
10173   EVT SourceType = MVT::Other;
10174   bool AllAnyExt = true;
10175
10176   for (unsigned i = 0; i != NumInScalars; ++i) {
10177     SDValue In = N->getOperand(i);
10178     // Ignore undef inputs.
10179     if (In.getOpcode() == ISD::UNDEF) continue;
10180
10181     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10182     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10183
10184     // Abort if the element is not an extension.
10185     if (!ZeroExt && !AnyExt) {
10186       SourceType = MVT::Other;
10187       break;
10188     }
10189
10190     // The input is a ZeroExt or AnyExt. Check the original type.
10191     EVT InTy = In.getOperand(0).getValueType();
10192
10193     // Check that all of the widened source types are the same.
10194     if (SourceType == MVT::Other)
10195       // First time.
10196       SourceType = InTy;
10197     else if (InTy != SourceType) {
10198       // Multiple income types. Abort.
10199       SourceType = MVT::Other;
10200       break;
10201     }
10202
10203     // Check if all of the extends are ANY_EXTENDs.
10204     AllAnyExt &= AnyExt;
10205   }
10206
10207   // In order to have valid types, all of the inputs must be extended from the
10208   // same source type and all of the inputs must be any or zero extend.
10209   // Scalar sizes must be a power of two.
10210   EVT OutScalarTy = VT.getScalarType();
10211   bool ValidTypes = SourceType != MVT::Other &&
10212                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10213                  isPowerOf2_32(SourceType.getSizeInBits());
10214
10215   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10216   // turn into a single shuffle instruction.
10217   if (!ValidTypes)
10218     return SDValue();
10219
10220   bool isLE = TLI.isLittleEndian();
10221   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10222   assert(ElemRatio > 1 && "Invalid element size ratio");
10223   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10224                                DAG.getConstant(0, SourceType);
10225
10226   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10227   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10228
10229   // Populate the new build_vector
10230   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10231     SDValue Cast = N->getOperand(i);
10232     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10233             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10234             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10235     SDValue In;
10236     if (Cast.getOpcode() == ISD::UNDEF)
10237       In = DAG.getUNDEF(SourceType);
10238     else
10239       In = Cast->getOperand(0);
10240     unsigned Index = isLE ? (i * ElemRatio) :
10241                             (i * ElemRatio + (ElemRatio - 1));
10242
10243     assert(Index < Ops.size() && "Invalid index");
10244     Ops[Index] = In;
10245   }
10246
10247   // The type of the new BUILD_VECTOR node.
10248   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10249   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10250          "Invalid vector size");
10251   // Check if the new vector type is legal.
10252   if (!isTypeLegal(VecVT)) return SDValue();
10253
10254   // Make the new BUILD_VECTOR.
10255   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10256
10257   // The new BUILD_VECTOR node has the potential to be further optimized.
10258   AddToWorklist(BV.getNode());
10259   // Bitcast to the desired type.
10260   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10261 }
10262
10263 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10264   EVT VT = N->getValueType(0);
10265
10266   unsigned NumInScalars = N->getNumOperands();
10267   SDLoc dl(N);
10268
10269   EVT SrcVT = MVT::Other;
10270   unsigned Opcode = ISD::DELETED_NODE;
10271   unsigned NumDefs = 0;
10272
10273   for (unsigned i = 0; i != NumInScalars; ++i) {
10274     SDValue In = N->getOperand(i);
10275     unsigned Opc = In.getOpcode();
10276
10277     if (Opc == ISD::UNDEF)
10278       continue;
10279
10280     // If all scalar values are floats and converted from integers.
10281     if (Opcode == ISD::DELETED_NODE &&
10282         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10283       Opcode = Opc;
10284     }
10285
10286     if (Opc != Opcode)
10287       return SDValue();
10288
10289     EVT InVT = In.getOperand(0).getValueType();
10290
10291     // If all scalar values are typed differently, bail out. It's chosen to
10292     // simplify BUILD_VECTOR of integer types.
10293     if (SrcVT == MVT::Other)
10294       SrcVT = InVT;
10295     if (SrcVT != InVT)
10296       return SDValue();
10297     NumDefs++;
10298   }
10299
10300   // If the vector has just one element defined, it's not worth to fold it into
10301   // a vectorized one.
10302   if (NumDefs < 2)
10303     return SDValue();
10304
10305   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10306          && "Should only handle conversion from integer to float.");
10307   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10308
10309   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10310
10311   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10312     return SDValue();
10313
10314   SmallVector<SDValue, 8> Opnds;
10315   for (unsigned i = 0; i != NumInScalars; ++i) {
10316     SDValue In = N->getOperand(i);
10317
10318     if (In.getOpcode() == ISD::UNDEF)
10319       Opnds.push_back(DAG.getUNDEF(SrcVT));
10320     else
10321       Opnds.push_back(In.getOperand(0));
10322   }
10323   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10324   AddToWorklist(BV.getNode());
10325
10326   return DAG.getNode(Opcode, dl, VT, BV);
10327 }
10328
10329 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10330   unsigned NumInScalars = N->getNumOperands();
10331   SDLoc dl(N);
10332   EVT VT = N->getValueType(0);
10333
10334   // A vector built entirely of undefs is undef.
10335   if (ISD::allOperandsUndef(N))
10336     return DAG.getUNDEF(VT);
10337
10338   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10339   if (V.getNode())
10340     return V;
10341
10342   V = reduceBuildVecConvertToConvertBuildVec(N);
10343   if (V.getNode())
10344     return V;
10345
10346   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10347   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10348   // at most two distinct vectors, turn this into a shuffle node.
10349
10350   // May only combine to shuffle after legalize if shuffle is legal.
10351   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10352     return SDValue();
10353
10354   SDValue VecIn1, VecIn2;
10355   for (unsigned i = 0; i != NumInScalars; ++i) {
10356     // Ignore undef inputs.
10357     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10358
10359     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10360     // constant index, bail out.
10361     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10362         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10363       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10364       break;
10365     }
10366
10367     // We allow up to two distinct input vectors.
10368     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10369     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10370       continue;
10371
10372     if (!VecIn1.getNode()) {
10373       VecIn1 = ExtractedFromVec;
10374     } else if (!VecIn2.getNode()) {
10375       VecIn2 = ExtractedFromVec;
10376     } else {
10377       // Too many inputs.
10378       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10379       break;
10380     }
10381   }
10382
10383   // If everything is good, we can make a shuffle operation.
10384   if (VecIn1.getNode()) {
10385     SmallVector<int, 8> Mask;
10386     for (unsigned i = 0; i != NumInScalars; ++i) {
10387       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10388         Mask.push_back(-1);
10389         continue;
10390       }
10391
10392       // If extracting from the first vector, just use the index directly.
10393       SDValue Extract = N->getOperand(i);
10394       SDValue ExtVal = Extract.getOperand(1);
10395       if (Extract.getOperand(0) == VecIn1) {
10396         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10397         if (ExtIndex > VT.getVectorNumElements())
10398           return SDValue();
10399
10400         Mask.push_back(ExtIndex);
10401         continue;
10402       }
10403
10404       // Otherwise, use InIdx + VecSize
10405       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10406       Mask.push_back(Idx+NumInScalars);
10407     }
10408
10409     // We can't generate a shuffle node with mismatched input and output types.
10410     // Attempt to transform a single input vector to the correct type.
10411     if ((VT != VecIn1.getValueType())) {
10412       // We don't support shuffeling between TWO values of different types.
10413       if (VecIn2.getNode())
10414         return SDValue();
10415
10416       // We only support widening of vectors which are half the size of the
10417       // output registers. For example XMM->YMM widening on X86 with AVX.
10418       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10419         return SDValue();
10420
10421       // If the input vector type has a different base type to the output
10422       // vector type, bail out.
10423       if (VecIn1.getValueType().getVectorElementType() !=
10424           VT.getVectorElementType())
10425         return SDValue();
10426
10427       // Widen the input vector by adding undef values.
10428       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10429                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10430     }
10431
10432     // If VecIn2 is unused then change it to undef.
10433     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10434
10435     // Check that we were able to transform all incoming values to the same
10436     // type.
10437     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10438         VecIn1.getValueType() != VT)
10439           return SDValue();
10440
10441     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10442     if (!isTypeLegal(VT))
10443       return SDValue();
10444
10445     // Return the new VECTOR_SHUFFLE node.
10446     SDValue Ops[2];
10447     Ops[0] = VecIn1;
10448     Ops[1] = VecIn2;
10449     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10450   }
10451
10452   return SDValue();
10453 }
10454
10455 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10456   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10457   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10458   // inputs come from at most two distinct vectors, turn this into a shuffle
10459   // node.
10460
10461   // If we only have one input vector, we don't need to do any concatenation.
10462   if (N->getNumOperands() == 1)
10463     return N->getOperand(0);
10464
10465   // Check if all of the operands are undefs.
10466   EVT VT = N->getValueType(0);
10467   if (ISD::allOperandsUndef(N))
10468     return DAG.getUNDEF(VT);
10469
10470   // Optimize concat_vectors where one of the vectors is undef.
10471   if (N->getNumOperands() == 2 &&
10472       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10473     SDValue In = N->getOperand(0);
10474     assert(In.getValueType().isVector() && "Must concat vectors");
10475
10476     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10477     if (In->getOpcode() == ISD::BITCAST &&
10478         !In->getOperand(0)->getValueType(0).isVector()) {
10479       SDValue Scalar = In->getOperand(0);
10480       EVT SclTy = Scalar->getValueType(0);
10481
10482       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10483         return SDValue();
10484
10485       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10486                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10487       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10488         return SDValue();
10489
10490       SDLoc dl = SDLoc(N);
10491       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10492       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10493     }
10494   }
10495
10496   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10497   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10498   if (N->getNumOperands() == 2 &&
10499       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10500       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10501     EVT VT = N->getValueType(0);
10502     SDValue N0 = N->getOperand(0);
10503     SDValue N1 = N->getOperand(1);
10504     SmallVector<SDValue, 8> Opnds;
10505     unsigned BuildVecNumElts =  N0.getNumOperands();
10506
10507     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10508     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10509     if (SclTy0.isFloatingPoint()) {
10510       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10511         Opnds.push_back(N0.getOperand(i));
10512       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10513         Opnds.push_back(N1.getOperand(i));
10514     } else {
10515       // If BUILD_VECTOR are from built from integer, they may have different
10516       // operand types. Get the smaller type and truncate all operands to it.
10517       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10518       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10519         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10520                         N0.getOperand(i)));
10521       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10522         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10523                         N1.getOperand(i)));
10524     }
10525
10526     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10527   }
10528
10529   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10530   // nodes often generate nop CONCAT_VECTOR nodes.
10531   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10532   // place the incoming vectors at the exact same location.
10533   SDValue SingleSource = SDValue();
10534   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10535
10536   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10537     SDValue Op = N->getOperand(i);
10538
10539     if (Op.getOpcode() == ISD::UNDEF)
10540       continue;
10541
10542     // Check if this is the identity extract:
10543     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10544       return SDValue();
10545
10546     // Find the single incoming vector for the extract_subvector.
10547     if (SingleSource.getNode()) {
10548       if (Op.getOperand(0) != SingleSource)
10549         return SDValue();
10550     } else {
10551       SingleSource = Op.getOperand(0);
10552
10553       // Check the source type is the same as the type of the result.
10554       // If not, this concat may extend the vector, so we can not
10555       // optimize it away.
10556       if (SingleSource.getValueType() != N->getValueType(0))
10557         return SDValue();
10558     }
10559
10560     unsigned IdentityIndex = i * PartNumElem;
10561     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10562     // The extract index must be constant.
10563     if (!CS)
10564       return SDValue();
10565
10566     // Check that we are reading from the identity index.
10567     if (CS->getZExtValue() != IdentityIndex)
10568       return SDValue();
10569   }
10570
10571   if (SingleSource.getNode())
10572     return SingleSource;
10573
10574   return SDValue();
10575 }
10576
10577 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10578   EVT NVT = N->getValueType(0);
10579   SDValue V = N->getOperand(0);
10580
10581   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10582     // Combine:
10583     //    (extract_subvec (concat V1, V2, ...), i)
10584     // Into:
10585     //    Vi if possible
10586     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10587     // type.
10588     if (V->getOperand(0).getValueType() != NVT)
10589       return SDValue();
10590     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10591     unsigned NumElems = NVT.getVectorNumElements();
10592     assert((Idx % NumElems) == 0 &&
10593            "IDX in concat is not a multiple of the result vector length.");
10594     return V->getOperand(Idx / NumElems);
10595   }
10596
10597   // Skip bitcasting
10598   if (V->getOpcode() == ISD::BITCAST)
10599     V = V.getOperand(0);
10600
10601   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10602     SDLoc dl(N);
10603     // Handle only simple case where vector being inserted and vector
10604     // being extracted are of same type, and are half size of larger vectors.
10605     EVT BigVT = V->getOperand(0).getValueType();
10606     EVT SmallVT = V->getOperand(1).getValueType();
10607     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10608       return SDValue();
10609
10610     // Only handle cases where both indexes are constants with the same type.
10611     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10612     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10613
10614     if (InsIdx && ExtIdx &&
10615         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10616         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10617       // Combine:
10618       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10619       // Into:
10620       //    indices are equal or bit offsets are equal => V1
10621       //    otherwise => (extract_subvec V1, ExtIdx)
10622       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10623           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10624         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10625       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10626                          DAG.getNode(ISD::BITCAST, dl,
10627                                      N->getOperand(0).getValueType(),
10628                                      V->getOperand(0)), N->getOperand(1));
10629     }
10630   }
10631
10632   return SDValue();
10633 }
10634
10635 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10636 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10637   EVT VT = N->getValueType(0);
10638   unsigned NumElts = VT.getVectorNumElements();
10639
10640   SDValue N0 = N->getOperand(0);
10641   SDValue N1 = N->getOperand(1);
10642   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10643
10644   SmallVector<SDValue, 4> Ops;
10645   EVT ConcatVT = N0.getOperand(0).getValueType();
10646   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10647   unsigned NumConcats = NumElts / NumElemsPerConcat;
10648
10649   // Look at every vector that's inserted. We're looking for exact
10650   // subvector-sized copies from a concatenated vector
10651   for (unsigned I = 0; I != NumConcats; ++I) {
10652     // Make sure we're dealing with a copy.
10653     unsigned Begin = I * NumElemsPerConcat;
10654     bool AllUndef = true, NoUndef = true;
10655     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10656       if (SVN->getMaskElt(J) >= 0)
10657         AllUndef = false;
10658       else
10659         NoUndef = false;
10660     }
10661
10662     if (NoUndef) {
10663       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10664         return SDValue();
10665
10666       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10667         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10668           return SDValue();
10669
10670       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10671       if (FirstElt < N0.getNumOperands())
10672         Ops.push_back(N0.getOperand(FirstElt));
10673       else
10674         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10675
10676     } else if (AllUndef) {
10677       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10678     } else { // Mixed with general masks and undefs, can't do optimization.
10679       return SDValue();
10680     }
10681   }
10682
10683   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10684 }
10685
10686 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10687   EVT VT = N->getValueType(0);
10688   unsigned NumElts = VT.getVectorNumElements();
10689
10690   SDValue N0 = N->getOperand(0);
10691   SDValue N1 = N->getOperand(1);
10692
10693   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10694
10695   // Canonicalize shuffle undef, undef -> undef
10696   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10697     return DAG.getUNDEF(VT);
10698
10699   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10700
10701   // Canonicalize shuffle v, v -> v, undef
10702   if (N0 == N1) {
10703     SmallVector<int, 8> NewMask;
10704     for (unsigned i = 0; i != NumElts; ++i) {
10705       int Idx = SVN->getMaskElt(i);
10706       if (Idx >= (int)NumElts) Idx -= NumElts;
10707       NewMask.push_back(Idx);
10708     }
10709     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10710                                 &NewMask[0]);
10711   }
10712
10713   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10714   if (N0.getOpcode() == ISD::UNDEF) {
10715     SmallVector<int, 8> NewMask;
10716     for (unsigned i = 0; i != NumElts; ++i) {
10717       int Idx = SVN->getMaskElt(i);
10718       if (Idx >= 0) {
10719         if (Idx >= (int)NumElts)
10720           Idx -= NumElts;
10721         else
10722           Idx = -1; // remove reference to lhs
10723       }
10724       NewMask.push_back(Idx);
10725     }
10726     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10727                                 &NewMask[0]);
10728   }
10729
10730   // Remove references to rhs if it is undef
10731   if (N1.getOpcode() == ISD::UNDEF) {
10732     bool Changed = false;
10733     SmallVector<int, 8> NewMask;
10734     for (unsigned i = 0; i != NumElts; ++i) {
10735       int Idx = SVN->getMaskElt(i);
10736       if (Idx >= (int)NumElts) {
10737         Idx = -1;
10738         Changed = true;
10739       }
10740       NewMask.push_back(Idx);
10741     }
10742     if (Changed)
10743       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10744   }
10745
10746   // If it is a splat, check if the argument vector is another splat or a
10747   // build_vector with all scalar elements the same.
10748   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10749     SDNode *V = N0.getNode();
10750
10751     // If this is a bit convert that changes the element type of the vector but
10752     // not the number of vector elements, look through it.  Be careful not to
10753     // look though conversions that change things like v4f32 to v2f64.
10754     if (V->getOpcode() == ISD::BITCAST) {
10755       SDValue ConvInput = V->getOperand(0);
10756       if (ConvInput.getValueType().isVector() &&
10757           ConvInput.getValueType().getVectorNumElements() == NumElts)
10758         V = ConvInput.getNode();
10759     }
10760
10761     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10762       assert(V->getNumOperands() == NumElts &&
10763              "BUILD_VECTOR has wrong number of operands");
10764       SDValue Base;
10765       bool AllSame = true;
10766       for (unsigned i = 0; i != NumElts; ++i) {
10767         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10768           Base = V->getOperand(i);
10769           break;
10770         }
10771       }
10772       // Splat of <u, u, u, u>, return <u, u, u, u>
10773       if (!Base.getNode())
10774         return N0;
10775       for (unsigned i = 0; i != NumElts; ++i) {
10776         if (V->getOperand(i) != Base) {
10777           AllSame = false;
10778           break;
10779         }
10780       }
10781       // Splat of <x, x, x, x>, return <x, x, x, x>
10782       if (AllSame)
10783         return N0;
10784     }
10785   }
10786
10787   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10788       Level < AfterLegalizeVectorOps &&
10789       (N1.getOpcode() == ISD::UNDEF ||
10790       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10791        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10792     SDValue V = partitionShuffleOfConcats(N, DAG);
10793
10794     if (V.getNode())
10795       return V;
10796   }
10797
10798   // If this shuffle node is simply a swizzle of another shuffle node,
10799   // then try to simplify it.
10800   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10801       N1.getOpcode() == ISD::UNDEF) {
10802
10803     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10804
10805     // The incoming shuffle must be of the same type as the result of the
10806     // current shuffle.
10807     assert(OtherSV->getOperand(0).getValueType() == VT &&
10808            "Shuffle types don't match");
10809
10810     SmallVector<int, 4> Mask;
10811     // Compute the combined shuffle mask.
10812     for (unsigned i = 0; i != NumElts; ++i) {
10813       int Idx = SVN->getMaskElt(i);
10814       assert(Idx < (int)NumElts && "Index references undef operand");
10815       // Next, this index comes from the first value, which is the incoming
10816       // shuffle. Adopt the incoming index.
10817       if (Idx >= 0)
10818         Idx = OtherSV->getMaskElt(Idx);
10819       Mask.push_back(Idx);
10820     }
10821
10822     // Check if all indices in Mask are Undef. In case, propagate Undef.
10823     bool isUndefMask = true;
10824     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10825       isUndefMask &= Mask[i] < 0;
10826
10827     if (isUndefMask)
10828       return DAG.getUNDEF(VT);
10829     
10830     bool CommuteOperands = false;
10831     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10832       // To be valid, the combine shuffle mask should only reference elements
10833       // from one of the two vectors in input to the inner shufflevector.
10834       bool IsValidMask = true;
10835       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10836         // See if the combined mask only reference undefs or elements coming
10837         // from the first shufflevector operand.
10838         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10839
10840       if (!IsValidMask) {
10841         IsValidMask = true;
10842         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10843           // Check that all the elements come from the second shuffle operand.
10844           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10845         CommuteOperands = IsValidMask;
10846       }
10847
10848       // Early exit if the combined shuffle mask is not valid.
10849       if (!IsValidMask)
10850         return SDValue();
10851     }
10852
10853     // See if this pair of shuffles can be safely folded according to either
10854     // of the following rules:
10855     //   shuffle(shuffle(x, y), undef) -> x
10856     //   shuffle(shuffle(x, undef), undef) -> x
10857     //   shuffle(shuffle(x, y), undef) -> y
10858     bool IsIdentityMask = true;
10859     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10860     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10861       // Skip Undefs.
10862       if (Mask[i] < 0)
10863         continue;
10864
10865       // The combined shuffle must map each index to itself.
10866       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10867     }
10868     
10869     if (IsIdentityMask) {
10870       if (CommuteOperands)
10871         // optimize shuffle(shuffle(x, y), undef) -> y.
10872         return OtherSV->getOperand(1);
10873       
10874       // optimize shuffle(shuffle(x, undef), undef) -> x
10875       // optimize shuffle(shuffle(x, y), undef) -> x
10876       return OtherSV->getOperand(0);
10877     }
10878
10879     // It may still be beneficial to combine the two shuffles if the
10880     // resulting shuffle is legal.
10881     if (TLI.isTypeLegal(VT)) {
10882       if (!CommuteOperands) {
10883         if (TLI.isShuffleMaskLegal(Mask, VT))
10884           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10885           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10886           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10887                                       &Mask[0]);
10888       } else {
10889         // Compute the commuted shuffle mask.
10890         for (unsigned i = 0; i != NumElts; ++i) {
10891           int idx = Mask[i];
10892           if (idx < 0)
10893             continue;
10894           else if (idx < (int)NumElts)
10895             Mask[i] = idx + NumElts;
10896           else
10897             Mask[i] = idx - NumElts;
10898         }
10899
10900         if (TLI.isShuffleMaskLegal(Mask, VT))
10901           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10902           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10903                                       &Mask[0]);
10904       }
10905     }
10906   }
10907
10908   // Canonicalize shuffles according to rules:
10909   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10910   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10911   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10912   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10913       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10914       TLI.isTypeLegal(VT)) {
10915     // The incoming shuffle must be of the same type as the result of the
10916     // current shuffle.
10917     assert(N1->getOperand(0).getValueType() == VT &&
10918            "Shuffle types don't match");
10919
10920     SDValue SV0 = N1->getOperand(0);
10921     SDValue SV1 = N1->getOperand(1);
10922     bool HasSameOp0 = N0 == SV0;
10923     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10924     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10925       // Commute the operands of this shuffle so that next rule
10926       // will trigger.
10927       return DAG.getCommutedVectorShuffle(*SVN);
10928   }
10929
10930   // Try to fold according to rules:
10931   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10932   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10933   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10934   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10935   // Don't try to fold shuffles with illegal type.
10936   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10937       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10938     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10939
10940     // The incoming shuffle must be of the same type as the result of the
10941     // current shuffle.
10942     assert(OtherSV->getOperand(0).getValueType() == VT &&
10943            "Shuffle types don't match");
10944
10945     SDValue SV0 = OtherSV->getOperand(0);
10946     SDValue SV1 = OtherSV->getOperand(1);
10947     bool HasSameOp0 = N1 == SV0;
10948     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10949     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10950       // Early exit.
10951       return SDValue();
10952
10953     SmallVector<int, 4> Mask;
10954     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10955     // operand, and SV1 as the second operand.
10956     for (unsigned i = 0; i != NumElts; ++i) {
10957       int Idx = SVN->getMaskElt(i);
10958       if (Idx < 0) {
10959         // Propagate Undef.
10960         Mask.push_back(Idx);
10961         continue;
10962       }
10963
10964       if (Idx < (int)NumElts) {
10965         Idx = OtherSV->getMaskElt(Idx);
10966         if (IsSV1Undef && Idx >= (int) NumElts)
10967           Idx = -1;  // Propagate Undef.
10968       } else
10969         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10970
10971       Mask.push_back(Idx);
10972     }
10973
10974     // Check if all indices in Mask are Undef. In case, propagate Undef.
10975     bool isUndefMask = true;
10976     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10977       isUndefMask &= Mask[i] < 0;
10978
10979     if (isUndefMask)
10980       return DAG.getUNDEF(VT);
10981
10982     // Avoid introducing shuffles with illegal mask.
10983     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10984       if (IsSV1Undef)
10985         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10986         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10987         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10988       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10989     }
10990   }
10991
10992   return SDValue();
10993 }
10994
10995 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10996   SDValue N0 = N->getOperand(0);
10997   SDValue N2 = N->getOperand(2);
10998
10999   // If the input vector is a concatenation, and the insert replaces
11000   // one of the halves, we can optimize into a single concat_vectors.
11001   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11002       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11003     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11004     EVT VT = N->getValueType(0);
11005
11006     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11007     // (concat_vectors Z, Y)
11008     if (InsIdx == 0)
11009       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11010                          N->getOperand(1), N0.getOperand(1));
11011
11012     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11013     // (concat_vectors X, Z)
11014     if (InsIdx == VT.getVectorNumElements()/2)
11015       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11016                          N0.getOperand(0), N->getOperand(1));
11017   }
11018
11019   return SDValue();
11020 }
11021
11022 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11023 /// with the destination vector and a zero vector.
11024 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11025 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11026 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11027   EVT VT = N->getValueType(0);
11028   SDLoc dl(N);
11029   SDValue LHS = N->getOperand(0);
11030   SDValue RHS = N->getOperand(1);
11031   if (N->getOpcode() == ISD::AND) {
11032     if (RHS.getOpcode() == ISD::BITCAST)
11033       RHS = RHS.getOperand(0);
11034     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11035       SmallVector<int, 8> Indices;
11036       unsigned NumElts = RHS.getNumOperands();
11037       for (unsigned i = 0; i != NumElts; ++i) {
11038         SDValue Elt = RHS.getOperand(i);
11039         if (!isa<ConstantSDNode>(Elt))
11040           return SDValue();
11041
11042         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11043           Indices.push_back(i);
11044         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11045           Indices.push_back(NumElts);
11046         else
11047           return SDValue();
11048       }
11049
11050       // Let's see if the target supports this vector_shuffle.
11051       EVT RVT = RHS.getValueType();
11052       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11053         return SDValue();
11054
11055       // Return the new VECTOR_SHUFFLE node.
11056       EVT EltVT = RVT.getVectorElementType();
11057       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11058                                      DAG.getConstant(0, EltVT));
11059       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11060       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11061       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11062       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11063     }
11064   }
11065
11066   return SDValue();
11067 }
11068
11069 /// Visit a binary vector operation, like ADD.
11070 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11071   assert(N->getValueType(0).isVector() &&
11072          "SimplifyVBinOp only works on vectors!");
11073
11074   SDValue LHS = N->getOperand(0);
11075   SDValue RHS = N->getOperand(1);
11076   SDValue Shuffle = XformToShuffleWithZero(N);
11077   if (Shuffle.getNode()) return Shuffle;
11078
11079   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11080   // this operation.
11081   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11082       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11083     // Check if both vectors are constants. If not bail out.
11084     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11085           cast<BuildVectorSDNode>(RHS)->isConstant()))
11086       return SDValue();
11087
11088     SmallVector<SDValue, 8> Ops;
11089     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11090       SDValue LHSOp = LHS.getOperand(i);
11091       SDValue RHSOp = RHS.getOperand(i);
11092
11093       // Can't fold divide by zero.
11094       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11095           N->getOpcode() == ISD::FDIV) {
11096         if ((RHSOp.getOpcode() == ISD::Constant &&
11097              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11098             (RHSOp.getOpcode() == ISD::ConstantFP &&
11099              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11100           break;
11101       }
11102
11103       EVT VT = LHSOp.getValueType();
11104       EVT RVT = RHSOp.getValueType();
11105       if (RVT != VT) {
11106         // Integer BUILD_VECTOR operands may have types larger than the element
11107         // size (e.g., when the element type is not legal).  Prior to type
11108         // legalization, the types may not match between the two BUILD_VECTORS.
11109         // Truncate one of the operands to make them match.
11110         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11111           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11112         } else {
11113           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11114           VT = RVT;
11115         }
11116       }
11117       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11118                                    LHSOp, RHSOp);
11119       if (FoldOp.getOpcode() != ISD::UNDEF &&
11120           FoldOp.getOpcode() != ISD::Constant &&
11121           FoldOp.getOpcode() != ISD::ConstantFP)
11122         break;
11123       Ops.push_back(FoldOp);
11124       AddToWorklist(FoldOp.getNode());
11125     }
11126
11127     if (Ops.size() == LHS.getNumOperands())
11128       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11129   }
11130
11131   // Type legalization might introduce new shuffles in the DAG.
11132   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11133   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11134   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11135       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11136       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11137       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11138     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11139     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11140
11141     if (SVN0->getMask().equals(SVN1->getMask())) {
11142       EVT VT = N->getValueType(0);
11143       SDValue UndefVector = LHS.getOperand(1);
11144       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11145                                      LHS.getOperand(0), RHS.getOperand(0));
11146       AddUsersToWorklist(N);
11147       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11148                                   &SVN0->getMask()[0]);
11149     }
11150   }
11151
11152   return SDValue();
11153 }
11154
11155 /// Visit a binary vector operation, like FABS/FNEG.
11156 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11157   assert(N->getValueType(0).isVector() &&
11158          "SimplifyVUnaryOp only works on vectors!");
11159
11160   SDValue N0 = N->getOperand(0);
11161
11162   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11163     return SDValue();
11164
11165   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11166   SmallVector<SDValue, 8> Ops;
11167   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11168     SDValue Op = N0.getOperand(i);
11169     if (Op.getOpcode() != ISD::UNDEF &&
11170         Op.getOpcode() != ISD::ConstantFP)
11171       break;
11172     EVT EltVT = Op.getValueType();
11173     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11174     if (FoldOp.getOpcode() != ISD::UNDEF &&
11175         FoldOp.getOpcode() != ISD::ConstantFP)
11176       break;
11177     Ops.push_back(FoldOp);
11178     AddToWorklist(FoldOp.getNode());
11179   }
11180
11181   if (Ops.size() != N0.getNumOperands())
11182     return SDValue();
11183
11184   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11185 }
11186
11187 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11188                                     SDValue N1, SDValue N2){
11189   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11190
11191   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11192                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11193
11194   // If we got a simplified select_cc node back from SimplifySelectCC, then
11195   // break it down into a new SETCC node, and a new SELECT node, and then return
11196   // the SELECT node, since we were called with a SELECT node.
11197   if (SCC.getNode()) {
11198     // Check to see if we got a select_cc back (to turn into setcc/select).
11199     // Otherwise, just return whatever node we got back, like fabs.
11200     if (SCC.getOpcode() == ISD::SELECT_CC) {
11201       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11202                                   N0.getValueType(),
11203                                   SCC.getOperand(0), SCC.getOperand(1),
11204                                   SCC.getOperand(4));
11205       AddToWorklist(SETCC.getNode());
11206       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11207                            SCC.getOperand(2), SCC.getOperand(3));
11208     }
11209
11210     return SCC;
11211   }
11212   return SDValue();
11213 }
11214
11215 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11216 /// being selected between, see if we can simplify the select.  Callers of this
11217 /// should assume that TheSelect is deleted if this returns true.  As such, they
11218 /// should return the appropriate thing (e.g. the node) back to the top-level of
11219 /// the DAG combiner loop to avoid it being looked at.
11220 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11221                                     SDValue RHS) {
11222
11223   // Cannot simplify select with vector condition
11224   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11225
11226   // If this is a select from two identical things, try to pull the operation
11227   // through the select.
11228   if (LHS.getOpcode() != RHS.getOpcode() ||
11229       !LHS.hasOneUse() || !RHS.hasOneUse())
11230     return false;
11231
11232   // If this is a load and the token chain is identical, replace the select
11233   // of two loads with a load through a select of the address to load from.
11234   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11235   // constants have been dropped into the constant pool.
11236   if (LHS.getOpcode() == ISD::LOAD) {
11237     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11238     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11239
11240     // Token chains must be identical.
11241     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11242         // Do not let this transformation reduce the number of volatile loads.
11243         LLD->isVolatile() || RLD->isVolatile() ||
11244         // If this is an EXTLOAD, the VT's must match.
11245         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11246         // If this is an EXTLOAD, the kind of extension must match.
11247         (LLD->getExtensionType() != RLD->getExtensionType() &&
11248          // The only exception is if one of the extensions is anyext.
11249          LLD->getExtensionType() != ISD::EXTLOAD &&
11250          RLD->getExtensionType() != ISD::EXTLOAD) ||
11251         // FIXME: this discards src value information.  This is
11252         // over-conservative. It would be beneficial to be able to remember
11253         // both potential memory locations.  Since we are discarding
11254         // src value info, don't do the transformation if the memory
11255         // locations are not in the default address space.
11256         LLD->getPointerInfo().getAddrSpace() != 0 ||
11257         RLD->getPointerInfo().getAddrSpace() != 0 ||
11258         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11259                                       LLD->getBasePtr().getValueType()))
11260       return false;
11261
11262     // Check that the select condition doesn't reach either load.  If so,
11263     // folding this will induce a cycle into the DAG.  If not, this is safe to
11264     // xform, so create a select of the addresses.
11265     SDValue Addr;
11266     if (TheSelect->getOpcode() == ISD::SELECT) {
11267       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11268       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11269           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11270         return false;
11271       // The loads must not depend on one another.
11272       if (LLD->isPredecessorOf(RLD) ||
11273           RLD->isPredecessorOf(LLD))
11274         return false;
11275       Addr = DAG.getSelect(SDLoc(TheSelect),
11276                            LLD->getBasePtr().getValueType(),
11277                            TheSelect->getOperand(0), LLD->getBasePtr(),
11278                            RLD->getBasePtr());
11279     } else {  // Otherwise SELECT_CC
11280       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11281       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11282
11283       if ((LLD->hasAnyUseOfValue(1) &&
11284            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11285           (RLD->hasAnyUseOfValue(1) &&
11286            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11287         return false;
11288
11289       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11290                          LLD->getBasePtr().getValueType(),
11291                          TheSelect->getOperand(0),
11292                          TheSelect->getOperand(1),
11293                          LLD->getBasePtr(), RLD->getBasePtr(),
11294                          TheSelect->getOperand(4));
11295     }
11296
11297     SDValue Load;
11298     // It is safe to replace the two loads if they have different alignments,
11299     // but the new load must be the minimum (most restrictive) alignment of the
11300     // inputs.
11301     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11302     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11303     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11304       Load = DAG.getLoad(TheSelect->getValueType(0),
11305                          SDLoc(TheSelect),
11306                          // FIXME: Discards pointer and AA info.
11307                          LLD->getChain(), Addr, MachinePointerInfo(),
11308                          LLD->isVolatile(), LLD->isNonTemporal(),
11309                          isInvariant, Alignment);
11310     } else {
11311       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11312                             RLD->getExtensionType() : LLD->getExtensionType(),
11313                             SDLoc(TheSelect),
11314                             TheSelect->getValueType(0),
11315                             // FIXME: Discards pointer and AA info.
11316                             LLD->getChain(), Addr, MachinePointerInfo(),
11317                             LLD->getMemoryVT(), LLD->isVolatile(),
11318                             LLD->isNonTemporal(), isInvariant, Alignment);
11319     }
11320
11321     // Users of the select now use the result of the load.
11322     CombineTo(TheSelect, Load);
11323
11324     // Users of the old loads now use the new load's chain.  We know the
11325     // old-load value is dead now.
11326     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11327     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11328     return true;
11329   }
11330
11331   return false;
11332 }
11333
11334 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11335 /// where 'cond' is the comparison specified by CC.
11336 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11337                                       SDValue N2, SDValue N3,
11338                                       ISD::CondCode CC, bool NotExtCompare) {
11339   // (x ? y : y) -> y.
11340   if (N2 == N3) return N2;
11341
11342   EVT VT = N2.getValueType();
11343   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11344   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11345   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11346
11347   // Determine if the condition we're dealing with is constant
11348   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11349                               N0, N1, CC, DL, false);
11350   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11351   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11352
11353   // fold select_cc true, x, y -> x
11354   if (SCCC && !SCCC->isNullValue())
11355     return N2;
11356   // fold select_cc false, x, y -> y
11357   if (SCCC && SCCC->isNullValue())
11358     return N3;
11359
11360   // Check to see if we can simplify the select into an fabs node
11361   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11362     // Allow either -0.0 or 0.0
11363     if (CFP->getValueAPF().isZero()) {
11364       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11365       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11366           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11367           N2 == N3.getOperand(0))
11368         return DAG.getNode(ISD::FABS, DL, VT, N0);
11369
11370       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11371       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11372           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11373           N2.getOperand(0) == N3)
11374         return DAG.getNode(ISD::FABS, DL, VT, N3);
11375     }
11376   }
11377
11378   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11379   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11380   // in it.  This is a win when the constant is not otherwise available because
11381   // it replaces two constant pool loads with one.  We only do this if the FP
11382   // type is known to be legal, because if it isn't, then we are before legalize
11383   // types an we want the other legalization to happen first (e.g. to avoid
11384   // messing with soft float) and if the ConstantFP is not legal, because if
11385   // it is legal, we may not need to store the FP constant in a constant pool.
11386   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11387     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11388       if (TLI.isTypeLegal(N2.getValueType()) &&
11389           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11390                TargetLowering::Legal &&
11391            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11392            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11393           // If both constants have multiple uses, then we won't need to do an
11394           // extra load, they are likely around in registers for other users.
11395           (TV->hasOneUse() || FV->hasOneUse())) {
11396         Constant *Elts[] = {
11397           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11398           const_cast<ConstantFP*>(TV->getConstantFPValue())
11399         };
11400         Type *FPTy = Elts[0]->getType();
11401         const DataLayout &TD = *TLI.getDataLayout();
11402
11403         // Create a ConstantArray of the two constants.
11404         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11405         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11406                                             TD.getPrefTypeAlignment(FPTy));
11407         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11408
11409         // Get the offsets to the 0 and 1 element of the array so that we can
11410         // select between them.
11411         SDValue Zero = DAG.getIntPtrConstant(0);
11412         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11413         SDValue One = DAG.getIntPtrConstant(EltSize);
11414
11415         SDValue Cond = DAG.getSetCC(DL,
11416                                     getSetCCResultType(N0.getValueType()),
11417                                     N0, N1, CC);
11418         AddToWorklist(Cond.getNode());
11419         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11420                                           Cond, One, Zero);
11421         AddToWorklist(CstOffset.getNode());
11422         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11423                             CstOffset);
11424         AddToWorklist(CPIdx.getNode());
11425         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11426                            MachinePointerInfo::getConstantPool(), false,
11427                            false, false, Alignment);
11428
11429       }
11430     }
11431
11432   // Check to see if we can perform the "gzip trick", transforming
11433   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11434   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11435       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11436        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11437     EVT XType = N0.getValueType();
11438     EVT AType = N2.getValueType();
11439     if (XType.bitsGE(AType)) {
11440       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11441       // single-bit constant.
11442       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11443         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11444         ShCtV = XType.getSizeInBits()-ShCtV-1;
11445         SDValue ShCt = DAG.getConstant(ShCtV,
11446                                        getShiftAmountTy(N0.getValueType()));
11447         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11448                                     XType, N0, ShCt);
11449         AddToWorklist(Shift.getNode());
11450
11451         if (XType.bitsGT(AType)) {
11452           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11453           AddToWorklist(Shift.getNode());
11454         }
11455
11456         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11457       }
11458
11459       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11460                                   XType, N0,
11461                                   DAG.getConstant(XType.getSizeInBits()-1,
11462                                          getShiftAmountTy(N0.getValueType())));
11463       AddToWorklist(Shift.getNode());
11464
11465       if (XType.bitsGT(AType)) {
11466         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11467         AddToWorklist(Shift.getNode());
11468       }
11469
11470       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11471     }
11472   }
11473
11474   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11475   // where y is has a single bit set.
11476   // A plaintext description would be, we can turn the SELECT_CC into an AND
11477   // when the condition can be materialized as an all-ones register.  Any
11478   // single bit-test can be materialized as an all-ones register with
11479   // shift-left and shift-right-arith.
11480   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11481       N0->getValueType(0) == VT &&
11482       N1C && N1C->isNullValue() &&
11483       N2C && N2C->isNullValue()) {
11484     SDValue AndLHS = N0->getOperand(0);
11485     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11486     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11487       // Shift the tested bit over the sign bit.
11488       APInt AndMask = ConstAndRHS->getAPIntValue();
11489       SDValue ShlAmt =
11490         DAG.getConstant(AndMask.countLeadingZeros(),
11491                         getShiftAmountTy(AndLHS.getValueType()));
11492       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11493
11494       // Now arithmetic right shift it all the way over, so the result is either
11495       // all-ones, or zero.
11496       SDValue ShrAmt =
11497         DAG.getConstant(AndMask.getBitWidth()-1,
11498                         getShiftAmountTy(Shl.getValueType()));
11499       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11500
11501       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11502     }
11503   }
11504
11505   // fold select C, 16, 0 -> shl C, 4
11506   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11507       TLI.getBooleanContents(N0.getValueType()) ==
11508           TargetLowering::ZeroOrOneBooleanContent) {
11509
11510     // If the caller doesn't want us to simplify this into a zext of a compare,
11511     // don't do it.
11512     if (NotExtCompare && N2C->getAPIntValue() == 1)
11513       return SDValue();
11514
11515     // Get a SetCC of the condition
11516     // NOTE: Don't create a SETCC if it's not legal on this target.
11517     if (!LegalOperations ||
11518         TLI.isOperationLegal(ISD::SETCC,
11519           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11520       SDValue Temp, SCC;
11521       // cast from setcc result type to select result type
11522       if (LegalTypes) {
11523         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11524                             N0, N1, CC);
11525         if (N2.getValueType().bitsLT(SCC.getValueType()))
11526           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11527                                         N2.getValueType());
11528         else
11529           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11530                              N2.getValueType(), SCC);
11531       } else {
11532         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11533         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11534                            N2.getValueType(), SCC);
11535       }
11536
11537       AddToWorklist(SCC.getNode());
11538       AddToWorklist(Temp.getNode());
11539
11540       if (N2C->getAPIntValue() == 1)
11541         return Temp;
11542
11543       // shl setcc result by log2 n2c
11544       return DAG.getNode(
11545           ISD::SHL, DL, N2.getValueType(), Temp,
11546           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11547                           getShiftAmountTy(Temp.getValueType())));
11548     }
11549   }
11550
11551   // Check to see if this is the equivalent of setcc
11552   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11553   // otherwise, go ahead with the folds.
11554   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11555     EVT XType = N0.getValueType();
11556     if (!LegalOperations ||
11557         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11558       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11559       if (Res.getValueType() != VT)
11560         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11561       return Res;
11562     }
11563
11564     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11565     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11566         (!LegalOperations ||
11567          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11568       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11569       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11570                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11571                                        getShiftAmountTy(Ctlz.getValueType())));
11572     }
11573     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11574     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11575       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11576                                   XType, DAG.getConstant(0, XType), N0);
11577       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11578       return DAG.getNode(ISD::SRL, DL, XType,
11579                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11580                          DAG.getConstant(XType.getSizeInBits()-1,
11581                                          getShiftAmountTy(XType)));
11582     }
11583     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11584     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11585       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11586                                  DAG.getConstant(XType.getSizeInBits()-1,
11587                                          getShiftAmountTy(N0.getValueType())));
11588       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11589     }
11590   }
11591
11592   // Check to see if this is an integer abs.
11593   // select_cc setg[te] X,  0,  X, -X ->
11594   // select_cc setgt    X, -1,  X, -X ->
11595   // select_cc setl[te] X,  0, -X,  X ->
11596   // select_cc setlt    X,  1, -X,  X ->
11597   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11598   if (N1C) {
11599     ConstantSDNode *SubC = nullptr;
11600     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11601          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11602         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11603       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11604     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11605               (N1C->isOne() && CC == ISD::SETLT)) &&
11606              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11607       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11608
11609     EVT XType = N0.getValueType();
11610     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11611       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11612                                   N0,
11613                                   DAG.getConstant(XType.getSizeInBits()-1,
11614                                          getShiftAmountTy(N0.getValueType())));
11615       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11616                                 XType, N0, Shift);
11617       AddToWorklist(Shift.getNode());
11618       AddToWorklist(Add.getNode());
11619       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11620     }
11621   }
11622
11623   return SDValue();
11624 }
11625
11626 /// This is a stub for TargetLowering::SimplifySetCC.
11627 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11628                                    SDValue N1, ISD::CondCode Cond,
11629                                    SDLoc DL, bool foldBooleans) {
11630   TargetLowering::DAGCombinerInfo
11631     DagCombineInfo(DAG, Level, false, this);
11632   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11633 }
11634
11635 /// Given an ISD::SDIV node expressing a divide by constant, return
11636 /// a DAG expression to select that will generate the same value by multiplying
11637 /// by a magic number.
11638 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11639 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11640   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11641   if (!C)
11642     return SDValue();
11643
11644   // Avoid division by zero.
11645   if (!C->getAPIntValue())
11646     return SDValue();
11647
11648   std::vector<SDNode*> Built;
11649   SDValue S =
11650       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11651
11652   for (SDNode *N : Built)
11653     AddToWorklist(N);
11654   return S;
11655 }
11656
11657 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11658 /// DAG expression that will generate the same value by right shifting.
11659 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11660   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11661   if (!C)
11662     return SDValue();
11663
11664   // Avoid division by zero.
11665   if (!C->getAPIntValue())
11666     return SDValue();
11667
11668   std::vector<SDNode *> Built;
11669   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11670
11671   for (SDNode *N : Built)
11672     AddToWorklist(N);
11673   return S;
11674 }
11675
11676 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11677 /// expression that will generate the same value by multiplying by a magic
11678 /// number.
11679 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11680 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11681   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11682   if (!C)
11683     return SDValue();
11684
11685   // Avoid division by zero.
11686   if (!C->getAPIntValue())
11687     return SDValue();
11688
11689   std::vector<SDNode*> Built;
11690   SDValue S =
11691       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11692
11693   for (SDNode *N : Built)
11694     AddToWorklist(N);
11695   return S;
11696 }
11697
11698 /// Return true if base is a frame index, which is known not to alias with
11699 /// anything but itself.  Provides base object and offset as results.
11700 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11701                            const GlobalValue *&GV, const void *&CV) {
11702   // Assume it is a primitive operation.
11703   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11704
11705   // If it's an adding a simple constant then integrate the offset.
11706   if (Base.getOpcode() == ISD::ADD) {
11707     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11708       Base = Base.getOperand(0);
11709       Offset += C->getZExtValue();
11710     }
11711   }
11712
11713   // Return the underlying GlobalValue, and update the Offset.  Return false
11714   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11715   // by multiple nodes with different offsets.
11716   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11717     GV = G->getGlobal();
11718     Offset += G->getOffset();
11719     return false;
11720   }
11721
11722   // Return the underlying Constant value, and update the Offset.  Return false
11723   // for ConstantSDNodes since the same constant pool entry may be represented
11724   // by multiple nodes with different offsets.
11725   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11726     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11727                                          : (const void *)C->getConstVal();
11728     Offset += C->getOffset();
11729     return false;
11730   }
11731   // If it's any of the following then it can't alias with anything but itself.
11732   return isa<FrameIndexSDNode>(Base);
11733 }
11734
11735 /// Return true if there is any possibility that the two addresses overlap.
11736 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11737   // If they are the same then they must be aliases.
11738   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11739
11740   // If they are both volatile then they cannot be reordered.
11741   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11742
11743   // Gather base node and offset information.
11744   SDValue Base1, Base2;
11745   int64_t Offset1, Offset2;
11746   const GlobalValue *GV1, *GV2;
11747   const void *CV1, *CV2;
11748   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11749                                       Base1, Offset1, GV1, CV1);
11750   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11751                                       Base2, Offset2, GV2, CV2);
11752
11753   // If they have a same base address then check to see if they overlap.
11754   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11755     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11756              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11757
11758   // It is possible for different frame indices to alias each other, mostly
11759   // when tail call optimization reuses return address slots for arguments.
11760   // To catch this case, look up the actual index of frame indices to compute
11761   // the real alias relationship.
11762   if (isFrameIndex1 && isFrameIndex2) {
11763     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11764     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11765     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11766     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11767              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11768   }
11769
11770   // Otherwise, if we know what the bases are, and they aren't identical, then
11771   // we know they cannot alias.
11772   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11773     return false;
11774
11775   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11776   // compared to the size and offset of the access, we may be able to prove they
11777   // do not alias.  This check is conservative for now to catch cases created by
11778   // splitting vector types.
11779   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11780       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11781       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11782        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11783       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11784     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11785     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11786
11787     // There is no overlap between these relatively aligned accesses of similar
11788     // size, return no alias.
11789     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11790         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11791       return false;
11792   }
11793
11794   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11795     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11796 #ifndef NDEBUG
11797   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11798       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11799     UseAA = false;
11800 #endif
11801   if (UseAA &&
11802       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11803     // Use alias analysis information.
11804     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11805                                  Op1->getSrcValueOffset());
11806     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11807         Op0->getSrcValueOffset() - MinOffset;
11808     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11809         Op1->getSrcValueOffset() - MinOffset;
11810     AliasAnalysis::AliasResult AAResult =
11811         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11812                                          Overlap1,
11813                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11814                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11815                                          Overlap2,
11816                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11817     if (AAResult == AliasAnalysis::NoAlias)
11818       return false;
11819   }
11820
11821   // Otherwise we have to assume they alias.
11822   return true;
11823 }
11824
11825 /// Walk up chain skipping non-aliasing memory nodes,
11826 /// looking for aliasing nodes and adding them to the Aliases vector.
11827 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11828                                    SmallVectorImpl<SDValue> &Aliases) {
11829   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11830   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11831
11832   // Get alias information for node.
11833   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11834
11835   // Starting off.
11836   Chains.push_back(OriginalChain);
11837   unsigned Depth = 0;
11838
11839   // Look at each chain and determine if it is an alias.  If so, add it to the
11840   // aliases list.  If not, then continue up the chain looking for the next
11841   // candidate.
11842   while (!Chains.empty()) {
11843     SDValue Chain = Chains.back();
11844     Chains.pop_back();
11845
11846     // For TokenFactor nodes, look at each operand and only continue up the
11847     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11848     // find more and revert to original chain since the xform is unlikely to be
11849     // profitable.
11850     //
11851     // FIXME: The depth check could be made to return the last non-aliasing
11852     // chain we found before we hit a tokenfactor rather than the original
11853     // chain.
11854     if (Depth > 6 || Aliases.size() == 2) {
11855       Aliases.clear();
11856       Aliases.push_back(OriginalChain);
11857       return;
11858     }
11859
11860     // Don't bother if we've been before.
11861     if (!Visited.insert(Chain.getNode()))
11862       continue;
11863
11864     switch (Chain.getOpcode()) {
11865     case ISD::EntryToken:
11866       // Entry token is ideal chain operand, but handled in FindBetterChain.
11867       break;
11868
11869     case ISD::LOAD:
11870     case ISD::STORE: {
11871       // Get alias information for Chain.
11872       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11873           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11874
11875       // If chain is alias then stop here.
11876       if (!(IsLoad && IsOpLoad) &&
11877           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11878         Aliases.push_back(Chain);
11879       } else {
11880         // Look further up the chain.
11881         Chains.push_back(Chain.getOperand(0));
11882         ++Depth;
11883       }
11884       break;
11885     }
11886
11887     case ISD::TokenFactor:
11888       // We have to check each of the operands of the token factor for "small"
11889       // token factors, so we queue them up.  Adding the operands to the queue
11890       // (stack) in reverse order maintains the original order and increases the
11891       // likelihood that getNode will find a matching token factor (CSE.)
11892       if (Chain.getNumOperands() > 16) {
11893         Aliases.push_back(Chain);
11894         break;
11895       }
11896       for (unsigned n = Chain.getNumOperands(); n;)
11897         Chains.push_back(Chain.getOperand(--n));
11898       ++Depth;
11899       break;
11900
11901     default:
11902       // For all other instructions we will just have to take what we can get.
11903       Aliases.push_back(Chain);
11904       break;
11905     }
11906   }
11907
11908   // We need to be careful here to also search for aliases through the
11909   // value operand of a store, etc. Consider the following situation:
11910   //   Token1 = ...
11911   //   L1 = load Token1, %52
11912   //   S1 = store Token1, L1, %51
11913   //   L2 = load Token1, %52+8
11914   //   S2 = store Token1, L2, %51+8
11915   //   Token2 = Token(S1, S2)
11916   //   L3 = load Token2, %53
11917   //   S3 = store Token2, L3, %52
11918   //   L4 = load Token2, %53+8
11919   //   S4 = store Token2, L4, %52+8
11920   // If we search for aliases of S3 (which loads address %52), and we look
11921   // only through the chain, then we'll miss the trivial dependence on L1
11922   // (which also loads from %52). We then might change all loads and
11923   // stores to use Token1 as their chain operand, which could result in
11924   // copying %53 into %52 before copying %52 into %51 (which should
11925   // happen first).
11926   //
11927   // The problem is, however, that searching for such data dependencies
11928   // can become expensive, and the cost is not directly related to the
11929   // chain depth. Instead, we'll rule out such configurations here by
11930   // insisting that we've visited all chain users (except for users
11931   // of the original chain, which is not necessary). When doing this,
11932   // we need to look through nodes we don't care about (otherwise, things
11933   // like register copies will interfere with trivial cases).
11934
11935   SmallVector<const SDNode *, 16> Worklist;
11936   for (const SDNode *N : Visited)
11937     if (N != OriginalChain.getNode())
11938       Worklist.push_back(N);
11939
11940   while (!Worklist.empty()) {
11941     const SDNode *M = Worklist.pop_back_val();
11942
11943     // We have already visited M, and want to make sure we've visited any uses
11944     // of M that we care about. For uses that we've not visisted, and don't
11945     // care about, queue them to the worklist.
11946
11947     for (SDNode::use_iterator UI = M->use_begin(),
11948          UIE = M->use_end(); UI != UIE; ++UI)
11949       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11950         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11951           // We've not visited this use, and we care about it (it could have an
11952           // ordering dependency with the original node).
11953           Aliases.clear();
11954           Aliases.push_back(OriginalChain);
11955           return;
11956         }
11957
11958         // We've not visited this use, but we don't care about it. Mark it as
11959         // visited and enqueue it to the worklist.
11960         Worklist.push_back(*UI);
11961       }
11962   }
11963 }
11964
11965 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11966 /// (aliasing node.)
11967 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11968   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11969
11970   // Accumulate all the aliases to this node.
11971   GatherAllAliases(N, OldChain, Aliases);
11972
11973   // If no operands then chain to entry token.
11974   if (Aliases.size() == 0)
11975     return DAG.getEntryNode();
11976
11977   // If a single operand then chain to it.  We don't need to revisit it.
11978   if (Aliases.size() == 1)
11979     return Aliases[0];
11980
11981   // Construct a custom tailored token factor.
11982   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11983 }
11984
11985 /// This is the entry point for the file.
11986 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11987                            CodeGenOpt::Level OptLevel) {
11988   /// This is the main entry point to this class.
11989   DAGCombiner(*this, AA, OptLevel).Run(Level);
11990 }