Remove unnecessary include.
[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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.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 visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitBRCOND(SDNode *N);
294     SDValue visitBR_CC(SDNode *N);
295     SDValue visitLOAD(SDNode *N);
296     SDValue visitSTORE(SDNode *N);
297     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
298     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
299     SDValue visitBUILD_VECTOR(SDNode *N);
300     SDValue visitCONCAT_VECTORS(SDNode *N);
301     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
302     SDValue visitVECTOR_SHUFFLE(SDNode *N);
303     SDValue visitINSERT_SUBVECTOR(SDNode *N);
304
305     SDValue XformToShuffleWithZero(SDNode *N);
306     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
307
308     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
309
310     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
311     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
312     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
313     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
314                              SDValue N3, ISD::CondCode CC,
315                              bool NotExtCompare = false);
316     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
317                           SDLoc DL, bool foldBooleans = true);
318
319     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
320                            SDValue &CC) const;
321     bool isOneUseSetCC(SDValue N) const;
322
323     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
324                                          unsigned HiOp);
325     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
326     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
327     SDValue BuildSDIV(SDNode *N);
328     SDValue BuildSDIVPow2(SDNode *N);
329     SDValue BuildUDIV(SDNode *N);
330     SDValue BuildReciprocalEstimate(SDValue Op);
331     SDValue BuildRsqrtEstimate(SDValue Op);
332     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
333                                bool DemandHighBits = true);
334     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
335     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
336                               SDValue InnerPos, SDValue InnerNeg,
337                               unsigned PosOpcode, unsigned NegOpcode,
338                               SDLoc DL);
339     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
340     SDValue ReduceLoadWidth(SDNode *N);
341     SDValue ReduceLoadOpStoreWidth(SDNode *N);
342     SDValue TransformFPLoadStorePair(SDNode *N);
343     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
344     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
345
346     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
347
348     /// Walk up chain skipping non-aliasing memory nodes,
349     /// looking for aliasing nodes and adding them to the Aliases vector.
350     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
351                           SmallVectorImpl<SDValue> &Aliases);
352
353     /// Return true if there is any possibility that the two addresses overlap.
354     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
355
356     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
357     /// chain (aliasing node.)
358     SDValue FindBetterChain(SDNode *N, SDValue Chain);
359
360     /// Merge consecutive store operations into a wide store.
361     /// This optimization uses wide integers or vectors when possible.
362     /// \return True if some memory operations were changed.
363     bool MergeConsecutiveStores(StoreSDNode *N);
364
365     /// \brief Try to transform a truncation where C is a constant:
366     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
367     ///
368     /// \p N needs to be a truncation and its first operand an AND. Other
369     /// requirements are checked by the function (e.g. that trunc is
370     /// single-use) and if missed an empty SDValue is returned.
371     SDValue distributeTruncateThroughAnd(SDNode *N);
372
373   public:
374     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
375         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
376           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
377       AttributeSet FnAttrs =
378           DAG.getMachineFunction().getFunction()->getAttributes();
379       ForCodeSize =
380           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
381                                Attribute::OptimizeForSize) ||
382           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
383     }
384
385     /// Runs the dag combiner on all nodes in the work list
386     void Run(CombineLevel AtLevel);
387
388     SelectionDAG &getDAG() const { return DAG; }
389
390     /// Returns a type large enough to hold any valid shift amount - before type
391     /// legalization these can be huge.
392     EVT getShiftAmountTy(EVT LHSTy) {
393       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
394       if (LHSTy.isVector())
395         return LHSTy;
396       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
397                         : TLI.getPointerTy();
398     }
399
400     /// This method returns true if we are running before type legalization or
401     /// if the specified VT is legal.
402     bool isTypeLegal(const EVT &VT) {
403       if (!LegalTypes) return true;
404       return TLI.isTypeLegal(VT);
405     }
406
407     /// Convenience wrapper around TargetLowering::getSetCCResultType
408     EVT getSetCCResultType(EVT VT) const {
409       return TLI.getSetCCResultType(*DAG.getContext(), VT);
410     }
411   };
412 }
413
414
415 namespace {
416 /// This class is a DAGUpdateListener that removes any deleted
417 /// nodes from the worklist.
418 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
419   DAGCombiner &DC;
420 public:
421   explicit WorklistRemover(DAGCombiner &dc)
422     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
423
424   void NodeDeleted(SDNode *N, SDNode *E) override {
425     DC.removeFromWorklist(N);
426   }
427 };
428 }
429
430 //===----------------------------------------------------------------------===//
431 //  TargetLowering::DAGCombinerInfo implementation
432 //===----------------------------------------------------------------------===//
433
434 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
435   ((DAGCombiner*)DC)->AddToWorklist(N);
436 }
437
438 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
439   ((DAGCombiner*)DC)->removeFromWorklist(N);
440 }
441
442 SDValue TargetLowering::DAGCombinerInfo::
443 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
444   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
445 }
446
447 SDValue TargetLowering::DAGCombinerInfo::
448 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
449   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
450 }
451
452
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
455   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
456 }
457
458 void TargetLowering::DAGCombinerInfo::
459 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
460   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
461 }
462
463 //===----------------------------------------------------------------------===//
464 // Helper Functions
465 //===----------------------------------------------------------------------===//
466
467 void DAGCombiner::deleteAndRecombine(SDNode *N) {
468   removeFromWorklist(N);
469
470   // If the operands of this node are only used by the node, they will now be
471   // dead. Make sure to re-visit them and recursively delete dead nodes.
472   for (const SDValue &Op : N->ops())
473     // For an operand generating multiple values, one of the values may
474     // become dead allowing further simplification (e.g. split index
475     // arithmetic from an indexed load).
476     if (Op->hasOneUse() || Op->getNumValues() > 1)
477       AddToWorklist(Op.getNode());
478
479   DAG.DeleteNode(N);
480 }
481
482 /// Return 1 if we can compute the negated form of the specified expression for
483 /// the same cost as the expression itself, or 2 if we can compute the negated
484 /// form more cheaply than the expression itself.
485 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
486                                const TargetLowering &TLI,
487                                const TargetOptions *Options,
488                                unsigned Depth = 0) {
489   // fneg is removable even if it has multiple uses.
490   if (Op.getOpcode() == ISD::FNEG) return 2;
491
492   // Don't allow anything with multiple uses.
493   if (!Op.hasOneUse()) return 0;
494
495   // Don't recurse exponentially.
496   if (Depth > 6) return 0;
497
498   switch (Op.getOpcode()) {
499   default: return false;
500   case ISD::ConstantFP:
501     // Don't invert constant FP values after legalize.  The negated constant
502     // isn't necessarily legal.
503     return LegalOperations ? 0 : 1;
504   case ISD::FADD:
505     // FIXME: determine better conditions for this xform.
506     if (!Options->UnsafeFPMath) return 0;
507
508     // After operation legalization, it might not be legal to create new FSUBs.
509     if (LegalOperations &&
510         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
511       return 0;
512
513     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
514     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
515                                     Options, Depth + 1))
516       return V;
517     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
518     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
519                               Depth + 1);
520   case ISD::FSUB:
521     // We can't turn -(A-B) into B-A when we honor signed zeros.
522     if (!Options->UnsafeFPMath) return 0;
523
524     // fold (fneg (fsub A, B)) -> (fsub B, A)
525     return 1;
526
527   case ISD::FMUL:
528   case ISD::FDIV:
529     if (Options->HonorSignDependentRoundingFPMath()) return 0;
530
531     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
532     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
533                                     Options, Depth + 1))
534       return V;
535
536     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
537                               Depth + 1);
538
539   case ISD::FP_EXTEND:
540   case ISD::FP_ROUND:
541   case ISD::FSIN:
542     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
543                               Depth + 1);
544   }
545 }
546
547 /// If isNegatibleForFree returns true, return the newly negated expression.
548 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
549                                     bool LegalOperations, unsigned Depth = 0) {
550   const TargetOptions &Options = DAG.getTarget().Options;
551   // fneg is removable even if it has multiple uses.
552   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
553
554   // Don't allow anything with multiple uses.
555   assert(Op.hasOneUse() && "Unknown reuse!");
556
557   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
558   switch (Op.getOpcode()) {
559   default: llvm_unreachable("Unknown code");
560   case ISD::ConstantFP: {
561     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
562     V.changeSign();
563     return DAG.getConstantFP(V, Op.getValueType());
564   }
565   case ISD::FADD:
566     // FIXME: determine better conditions for this xform.
567     assert(Options.UnsafeFPMath);
568
569     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
570     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
571                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
572       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
573                          GetNegatedExpression(Op.getOperand(0), DAG,
574                                               LegalOperations, Depth+1),
575                          Op.getOperand(1));
576     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
577     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
578                        GetNegatedExpression(Op.getOperand(1), DAG,
579                                             LegalOperations, Depth+1),
580                        Op.getOperand(0));
581   case ISD::FSUB:
582     // We can't turn -(A-B) into B-A when we honor signed zeros.
583     assert(Options.UnsafeFPMath);
584
585     // fold (fneg (fsub 0, B)) -> B
586     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
587       if (N0CFP->getValueAPF().isZero())
588         return Op.getOperand(1);
589
590     // fold (fneg (fsub A, B)) -> (fsub B, A)
591     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
592                        Op.getOperand(1), Op.getOperand(0));
593
594   case ISD::FMUL:
595   case ISD::FDIV:
596     assert(!Options.HonorSignDependentRoundingFPMath());
597
598     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
599     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
600                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
601       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
602                          GetNegatedExpression(Op.getOperand(0), DAG,
603                                               LegalOperations, Depth+1),
604                          Op.getOperand(1));
605
606     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
607     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608                        Op.getOperand(0),
609                        GetNegatedExpression(Op.getOperand(1), DAG,
610                                             LegalOperations, Depth+1));
611
612   case ISD::FP_EXTEND:
613   case ISD::FSIN:
614     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
615                        GetNegatedExpression(Op.getOperand(0), DAG,
616                                             LegalOperations, Depth+1));
617   case ISD::FP_ROUND:
618       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
619                          GetNegatedExpression(Op.getOperand(0), DAG,
620                                               LegalOperations, Depth+1),
621                          Op.getOperand(1));
622   }
623 }
624
625 // Return true if this node is a setcc, or is a select_cc
626 // that selects between the target values used for true and false, making it
627 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
628 // the appropriate nodes based on the type of node we are checking. This
629 // simplifies life a bit for the callers.
630 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
631                                     SDValue &CC) const {
632   if (N.getOpcode() == ISD::SETCC) {
633     LHS = N.getOperand(0);
634     RHS = N.getOperand(1);
635     CC  = N.getOperand(2);
636     return true;
637   }
638
639   if (N.getOpcode() != ISD::SELECT_CC ||
640       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
641       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
642     return false;
643
644   LHS = N.getOperand(0);
645   RHS = N.getOperand(1);
646   CC  = N.getOperand(4);
647   return true;
648 }
649
650 /// Return true if this is a SetCC-equivalent operation with only one use.
651 /// If this is true, it allows the users to invert the operation for free when
652 /// it is profitable to do so.
653 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
654   SDValue N0, N1, N2;
655   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
656     return true;
657   return false;
658 }
659
660 /// Returns true if N is a BUILD_VECTOR node whose
661 /// elements are all the same constant or undefined.
662 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
663   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
664   if (!C)
665     return false;
666
667   APInt SplatUndef;
668   unsigned SplatBitSize;
669   bool HasAnyUndefs;
670   EVT EltVT = N->getValueType(0).getVectorElementType();
671   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
672                              HasAnyUndefs) &&
673           EltVT.getSizeInBits() >= SplatBitSize);
674 }
675
676 // \brief Returns the SDNode if it is a constant BuildVector or constant.
677 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
678   if (isa<ConstantSDNode>(N))
679     return N.getNode();
680   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
681   if (BV && BV->isConstant())
682     return BV;
683   return nullptr;
684 }
685
686 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
687 // int.
688 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
689   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
690     return CN;
691
692   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
693     BitVector UndefElements;
694     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
695
696     // BuildVectors can truncate their operands. Ignore that case here.
697     // FIXME: We blindly ignore splats which include undef which is overly
698     // pessimistic.
699     if (CN && UndefElements.none() &&
700         CN->getValueType(0) == N.getValueType().getScalarType())
701       return CN;
702   }
703
704   return nullptr;
705 }
706
707 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
708 // float.
709 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
710   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
711     return CN;
712
713   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
714     BitVector UndefElements;
715     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
716
717     if (CN && UndefElements.none())
718       return CN;
719   }
720
721   return nullptr;
722 }
723
724 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
725                                     SDValue N0, SDValue N1) {
726   EVT VT = N0.getValueType();
727   if (N0.getOpcode() == Opc) {
728     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
729       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
730         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
731         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
732         if (!OpNode.getNode())
733           return SDValue();
734         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
735       }
736       if (N0.hasOneUse()) {
737         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
738         // use
739         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
740         if (!OpNode.getNode())
741           return SDValue();
742         AddToWorklist(OpNode.getNode());
743         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
744       }
745     }
746   }
747
748   if (N1.getOpcode() == Opc) {
749     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
750       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
751         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
752         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
753         if (!OpNode.getNode())
754           return SDValue();
755         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
756       }
757       if (N1.hasOneUse()) {
758         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
759         // use
760         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
761         if (!OpNode.getNode())
762           return SDValue();
763         AddToWorklist(OpNode.getNode());
764         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
765       }
766     }
767   }
768
769   return SDValue();
770 }
771
772 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
773                                bool AddTo) {
774   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
775   ++NodesCombined;
776   DEBUG(dbgs() << "\nReplacing.1 ";
777         N->dump(&DAG);
778         dbgs() << "\nWith: ";
779         To[0].getNode()->dump(&DAG);
780         dbgs() << " and " << NumTo-1 << " other values\n";
781         for (unsigned i = 0, e = NumTo; i != e; ++i)
782           assert((!To[i].getNode() ||
783                   N->getValueType(i) == To[i].getValueType()) &&
784                  "Cannot combine value to value of different type!"));
785   WorklistRemover DeadNodes(*this);
786   DAG.ReplaceAllUsesWith(N, To);
787   if (AddTo) {
788     // Push the new nodes and any users onto the worklist
789     for (unsigned i = 0, e = NumTo; i != e; ++i) {
790       if (To[i].getNode()) {
791         AddToWorklist(To[i].getNode());
792         AddUsersToWorklist(To[i].getNode());
793       }
794     }
795   }
796
797   // Finally, if the node is now dead, remove it from the graph.  The node
798   // may not be dead if the replacement process recursively simplified to
799   // something else needing this node.
800   if (N->use_empty())
801     deleteAndRecombine(N);
802   return SDValue(N, 0);
803 }
804
805 void DAGCombiner::
806 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
807   // Replace all uses.  If any nodes become isomorphic to other nodes and
808   // are deleted, make sure to remove them from our worklist.
809   WorklistRemover DeadNodes(*this);
810   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
811
812   // Push the new node and any (possibly new) users onto the worklist.
813   AddToWorklist(TLO.New.getNode());
814   AddUsersToWorklist(TLO.New.getNode());
815
816   // Finally, if the node is now dead, remove it from the graph.  The node
817   // may not be dead if the replacement process recursively simplified to
818   // something else needing this node.
819   if (TLO.Old.getNode()->use_empty())
820     deleteAndRecombine(TLO.Old.getNode());
821 }
822
823 /// Check the specified integer node value to see if it can be simplified or if
824 /// things it uses can be simplified by bit propagation. If so, return true.
825 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
826   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
827   APInt KnownZero, KnownOne;
828   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
829     return false;
830
831   // Revisit the node.
832   AddToWorklist(Op.getNode());
833
834   // Replace the old value with the new one.
835   ++NodesCombined;
836   DEBUG(dbgs() << "\nReplacing.2 ";
837         TLO.Old.getNode()->dump(&DAG);
838         dbgs() << "\nWith: ";
839         TLO.New.getNode()->dump(&DAG);
840         dbgs() << '\n');
841
842   CommitTargetLoweringOpt(TLO);
843   return true;
844 }
845
846 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
847   SDLoc dl(Load);
848   EVT VT = Load->getValueType(0);
849   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
850
851   DEBUG(dbgs() << "\nReplacing.9 ";
852         Load->dump(&DAG);
853         dbgs() << "\nWith: ";
854         Trunc.getNode()->dump(&DAG);
855         dbgs() << '\n');
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
858   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
859   deleteAndRecombine(Load);
860   AddToWorklist(Trunc.getNode());
861 }
862
863 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
864   Replace = false;
865   SDLoc dl(Op);
866   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
867     EVT MemVT = LD->getMemoryVT();
868     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
869       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
870                                                   : ISD::EXTLOAD)
871       : LD->getExtensionType();
872     Replace = true;
873     return DAG.getExtLoad(ExtType, dl, PVT,
874                           LD->getChain(), LD->getBasePtr(),
875                           MemVT, LD->getMemOperand());
876   }
877
878   unsigned Opc = Op.getOpcode();
879   switch (Opc) {
880   default: break;
881   case ISD::AssertSext:
882     return DAG.getNode(ISD::AssertSext, dl, PVT,
883                        SExtPromoteOperand(Op.getOperand(0), PVT),
884                        Op.getOperand(1));
885   case ISD::AssertZext:
886     return DAG.getNode(ISD::AssertZext, dl, PVT,
887                        ZExtPromoteOperand(Op.getOperand(0), PVT),
888                        Op.getOperand(1));
889   case ISD::Constant: {
890     unsigned ExtOpc =
891       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
892     return DAG.getNode(ExtOpc, dl, PVT, Op);
893   }
894   }
895
896   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
897     return SDValue();
898   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
899 }
900
901 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
902   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
903     return SDValue();
904   EVT OldVT = Op.getValueType();
905   SDLoc dl(Op);
906   bool Replace = false;
907   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
908   if (!NewOp.getNode())
909     return SDValue();
910   AddToWorklist(NewOp.getNode());
911
912   if (Replace)
913     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
914   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
915                      DAG.getValueType(OldVT));
916 }
917
918 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
919   EVT OldVT = Op.getValueType();
920   SDLoc dl(Op);
921   bool Replace = false;
922   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
923   if (!NewOp.getNode())
924     return SDValue();
925   AddToWorklist(NewOp.getNode());
926
927   if (Replace)
928     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
929   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
930 }
931
932 /// Promote the specified integer binary operation if the target indicates it is
933 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
934 /// i32 since i16 instructions are longer.
935 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
936   if (!LegalOperations)
937     return SDValue();
938
939   EVT VT = Op.getValueType();
940   if (VT.isVector() || !VT.isInteger())
941     return SDValue();
942
943   // If operation type is 'undesirable', e.g. i16 on x86, consider
944   // promoting it.
945   unsigned Opc = Op.getOpcode();
946   if (TLI.isTypeDesirableForOp(Opc, VT))
947     return SDValue();
948
949   EVT PVT = VT;
950   // Consult target whether it is a good idea to promote this operation and
951   // what's the right type to promote it to.
952   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
953     assert(PVT != VT && "Don't know what type to promote to!");
954
955     bool Replace0 = false;
956     SDValue N0 = Op.getOperand(0);
957     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
958     if (!NN0.getNode())
959       return SDValue();
960
961     bool Replace1 = false;
962     SDValue N1 = Op.getOperand(1);
963     SDValue NN1;
964     if (N0 == N1)
965       NN1 = NN0;
966     else {
967       NN1 = PromoteOperand(N1, PVT, Replace1);
968       if (!NN1.getNode())
969         return SDValue();
970     }
971
972     AddToWorklist(NN0.getNode());
973     if (NN1.getNode())
974       AddToWorklist(NN1.getNode());
975
976     if (Replace0)
977       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
978     if (Replace1)
979       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
980
981     DEBUG(dbgs() << "\nPromoting ";
982           Op.getNode()->dump(&DAG));
983     SDLoc dl(Op);
984     return DAG.getNode(ISD::TRUNCATE, dl, VT,
985                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
986   }
987   return SDValue();
988 }
989
990 /// Promote the specified integer shift operation if the target indicates it is
991 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
992 /// i32 since i16 instructions are longer.
993 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
994   if (!LegalOperations)
995     return SDValue();
996
997   EVT VT = Op.getValueType();
998   if (VT.isVector() || !VT.isInteger())
999     return SDValue();
1000
1001   // If operation type is 'undesirable', e.g. i16 on x86, consider
1002   // promoting it.
1003   unsigned Opc = Op.getOpcode();
1004   if (TLI.isTypeDesirableForOp(Opc, VT))
1005     return SDValue();
1006
1007   EVT PVT = VT;
1008   // Consult target whether it is a good idea to promote this operation and
1009   // what's the right type to promote it to.
1010   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1011     assert(PVT != VT && "Don't know what type to promote to!");
1012
1013     bool Replace = false;
1014     SDValue N0 = Op.getOperand(0);
1015     if (Opc == ISD::SRA)
1016       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1017     else if (Opc == ISD::SRL)
1018       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1019     else
1020       N0 = PromoteOperand(N0, PVT, Replace);
1021     if (!N0.getNode())
1022       return SDValue();
1023
1024     AddToWorklist(N0.getNode());
1025     if (Replace)
1026       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1033   }
1034   return SDValue();
1035 }
1036
1037 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1038   if (!LegalOperations)
1039     return SDValue();
1040
1041   EVT VT = Op.getValueType();
1042   if (VT.isVector() || !VT.isInteger())
1043     return SDValue();
1044
1045   // If operation type is 'undesirable', e.g. i16 on x86, consider
1046   // promoting it.
1047   unsigned Opc = Op.getOpcode();
1048   if (TLI.isTypeDesirableForOp(Opc, VT))
1049     return SDValue();
1050
1051   EVT PVT = VT;
1052   // Consult target whether it is a good idea to promote this operation and
1053   // what's the right type to promote it to.
1054   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1055     assert(PVT != VT && "Don't know what type to promote to!");
1056     // fold (aext (aext x)) -> (aext x)
1057     // fold (aext (zext x)) -> (zext x)
1058     // fold (aext (sext x)) -> (sext x)
1059     DEBUG(dbgs() << "\nPromoting ";
1060           Op.getNode()->dump(&DAG));
1061     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1062   }
1063   return SDValue();
1064 }
1065
1066 bool DAGCombiner::PromoteLoad(SDValue Op) {
1067   if (!LegalOperations)
1068     return false;
1069
1070   EVT VT = Op.getValueType();
1071   if (VT.isVector() || !VT.isInteger())
1072     return false;
1073
1074   // If operation type is 'undesirable', e.g. i16 on x86, consider
1075   // promoting it.
1076   unsigned Opc = Op.getOpcode();
1077   if (TLI.isTypeDesirableForOp(Opc, VT))
1078     return false;
1079
1080   EVT PVT = VT;
1081   // Consult target whether it is a good idea to promote this operation and
1082   // what's the right type to promote it to.
1083   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1084     assert(PVT != VT && "Don't know what type to promote to!");
1085
1086     SDLoc dl(Op);
1087     SDNode *N = Op.getNode();
1088     LoadSDNode *LD = cast<LoadSDNode>(N);
1089     EVT MemVT = LD->getMemoryVT();
1090     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1091       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1092                                                   : ISD::EXTLOAD)
1093       : LD->getExtensionType();
1094     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1095                                    LD->getChain(), LD->getBasePtr(),
1096                                    MemVT, LD->getMemOperand());
1097     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1098
1099     DEBUG(dbgs() << "\nPromoting ";
1100           N->dump(&DAG);
1101           dbgs() << "\nTo: ";
1102           Result.getNode()->dump(&DAG);
1103           dbgs() << '\n');
1104     WorklistRemover DeadNodes(*this);
1105     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1106     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1107     deleteAndRecombine(N);
1108     AddToWorklist(Result.getNode());
1109     return true;
1110   }
1111   return false;
1112 }
1113
1114 /// \brief Recursively delete a node which has no uses and any operands for
1115 /// which it is the only use.
1116 ///
1117 /// Note that this both deletes the nodes and removes them from the worklist.
1118 /// It also adds any nodes who have had a user deleted to the worklist as they
1119 /// may now have only one use and subject to other combines.
1120 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1121   if (!N->use_empty())
1122     return false;
1123
1124   SmallSetVector<SDNode *, 16> Nodes;
1125   Nodes.insert(N);
1126   do {
1127     N = Nodes.pop_back_val();
1128     if (!N)
1129       continue;
1130
1131     if (N->use_empty()) {
1132       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1133         Nodes.insert(N->getOperand(i).getNode());
1134
1135       removeFromWorklist(N);
1136       DAG.DeleteNode(N);
1137     } else {
1138       AddToWorklist(N);
1139     }
1140   } while (!Nodes.empty());
1141   return true;
1142 }
1143
1144 //===----------------------------------------------------------------------===//
1145 //  Main DAG Combiner implementation
1146 //===----------------------------------------------------------------------===//
1147
1148 void DAGCombiner::Run(CombineLevel AtLevel) {
1149   // set the instance variables, so that the various visit routines may use it.
1150   Level = AtLevel;
1151   LegalOperations = Level >= AfterLegalizeVectorOps;
1152   LegalTypes = Level >= AfterLegalizeTypes;
1153
1154   // Add all the dag nodes to the worklist.
1155   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1156        E = DAG.allnodes_end(); I != E; ++I)
1157     AddToWorklist(I);
1158
1159   // Create a dummy node (which is not added to allnodes), that adds a reference
1160   // to the root node, preventing it from being deleted, and tracking any
1161   // changes of the root.
1162   HandleSDNode Dummy(DAG.getRoot());
1163
1164   // while the worklist isn't empty, find a node and
1165   // try and combine it.
1166   while (!WorklistMap.empty()) {
1167     SDNode *N;
1168     // The Worklist holds the SDNodes in order, but it may contain null entries.
1169     do {
1170       N = Worklist.pop_back_val();
1171     } while (!N);
1172
1173     bool GoodWorklistEntry = WorklistMap.erase(N);
1174     (void)GoodWorklistEntry;
1175     assert(GoodWorklistEntry &&
1176            "Found a worklist entry without a corresponding map entry!");
1177
1178     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1179     // N is deleted from the DAG, since they too may now be dead or may have a
1180     // reduced number of uses, allowing other xforms.
1181     if (recursivelyDeleteUnusedNodes(N))
1182       continue;
1183
1184     WorklistRemover DeadNodes(*this);
1185
1186     // If this combine is running after legalizing the DAG, re-legalize any
1187     // nodes pulled off the worklist.
1188     if (Level == AfterLegalizeDAG) {
1189       SmallSetVector<SDNode *, 16> UpdatedNodes;
1190       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1191
1192       for (SDNode *LN : UpdatedNodes) {
1193         AddToWorklist(LN);
1194         AddUsersToWorklist(LN);
1195       }
1196       if (!NIsValid)
1197         continue;
1198     }
1199
1200     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1201
1202     // Add any operands of the new node which have not yet been combined to the
1203     // worklist as well. Because the worklist uniques things already, this
1204     // won't repeatedly process the same operand.
1205     CombinedNodes.insert(N);
1206     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1207       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1208         AddToWorklist(N->getOperand(i).getNode());
1209
1210     SDValue RV = combine(N);
1211
1212     if (!RV.getNode())
1213       continue;
1214
1215     ++NodesCombined;
1216
1217     // If we get back the same node we passed in, rather than a new node or
1218     // zero, we know that the node must have defined multiple values and
1219     // CombineTo was used.  Since CombineTo takes care of the worklist
1220     // mechanics for us, we have no work to do in this case.
1221     if (RV.getNode() == N)
1222       continue;
1223
1224     assert(N->getOpcode() != ISD::DELETED_NODE &&
1225            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1226            "Node was deleted but visit returned new node!");
1227
1228     DEBUG(dbgs() << " ... into: ";
1229           RV.getNode()->dump(&DAG));
1230
1231     // Transfer debug value.
1232     DAG.TransferDbgValues(SDValue(N, 0), RV);
1233     if (N->getNumValues() == RV.getNode()->getNumValues())
1234       DAG.ReplaceAllUsesWith(N, RV.getNode());
1235     else {
1236       assert(N->getValueType(0) == RV.getValueType() &&
1237              N->getNumValues() == 1 && "Type mismatch");
1238       SDValue OpV = RV;
1239       DAG.ReplaceAllUsesWith(N, &OpV);
1240     }
1241
1242     // Push the new node and any users onto the worklist
1243     AddToWorklist(RV.getNode());
1244     AddUsersToWorklist(RV.getNode());
1245
1246     // Finally, if the node is now dead, remove it from the graph.  The node
1247     // may not be dead if the replacement process recursively simplified to
1248     // something else needing this node. This will also take care of adding any
1249     // operands which have lost a user to the worklist.
1250     recursivelyDeleteUnusedNodes(N);
1251   }
1252
1253   // If the root changed (e.g. it was a dead load, update the root).
1254   DAG.setRoot(Dummy.getValue());
1255   DAG.RemoveDeadNodes();
1256 }
1257
1258 SDValue DAGCombiner::visit(SDNode *N) {
1259   switch (N->getOpcode()) {
1260   default: break;
1261   case ISD::TokenFactor:        return visitTokenFactor(N);
1262   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1263   case ISD::ADD:                return visitADD(N);
1264   case ISD::SUB:                return visitSUB(N);
1265   case ISD::ADDC:               return visitADDC(N);
1266   case ISD::SUBC:               return visitSUBC(N);
1267   case ISD::ADDE:               return visitADDE(N);
1268   case ISD::SUBE:               return visitSUBE(N);
1269   case ISD::MUL:                return visitMUL(N);
1270   case ISD::SDIV:               return visitSDIV(N);
1271   case ISD::UDIV:               return visitUDIV(N);
1272   case ISD::SREM:               return visitSREM(N);
1273   case ISD::UREM:               return visitUREM(N);
1274   case ISD::MULHU:              return visitMULHU(N);
1275   case ISD::MULHS:              return visitMULHS(N);
1276   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1277   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1278   case ISD::SMULO:              return visitSMULO(N);
1279   case ISD::UMULO:              return visitUMULO(N);
1280   case ISD::SDIVREM:            return visitSDIVREM(N);
1281   case ISD::UDIVREM:            return visitUDIVREM(N);
1282   case ISD::AND:                return visitAND(N);
1283   case ISD::OR:                 return visitOR(N);
1284   case ISD::XOR:                return visitXOR(N);
1285   case ISD::SHL:                return visitSHL(N);
1286   case ISD::SRA:                return visitSRA(N);
1287   case ISD::SRL:                return visitSRL(N);
1288   case ISD::ROTR:
1289   case ISD::ROTL:               return visitRotate(N);
1290   case ISD::CTLZ:               return visitCTLZ(N);
1291   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1292   case ISD::CTTZ:               return visitCTTZ(N);
1293   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1294   case ISD::CTPOP:              return visitCTPOP(N);
1295   case ISD::SELECT:             return visitSELECT(N);
1296   case ISD::VSELECT:            return visitVSELECT(N);
1297   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1298   case ISD::SETCC:              return visitSETCC(N);
1299   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1300   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1301   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1302   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1303   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1304   case ISD::BITCAST:            return visitBITCAST(N);
1305   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1306   case ISD::FADD:               return visitFADD(N);
1307   case ISD::FSUB:               return visitFSUB(N);
1308   case ISD::FMUL:               return visitFMUL(N);
1309   case ISD::FMA:                return visitFMA(N);
1310   case ISD::FDIV:               return visitFDIV(N);
1311   case ISD::FREM:               return visitFREM(N);
1312   case ISD::FSQRT:              return visitFSQRT(N);
1313   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1314   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1315   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1316   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1317   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1318   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1319   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1320   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1321   case ISD::FNEG:               return visitFNEG(N);
1322   case ISD::FABS:               return visitFABS(N);
1323   case ISD::FFLOOR:             return visitFFLOOR(N);
1324   case ISD::FCEIL:              return visitFCEIL(N);
1325   case ISD::FTRUNC:             return visitFTRUNC(N);
1326   case ISD::BRCOND:             return visitBRCOND(N);
1327   case ISD::BR_CC:              return visitBR_CC(N);
1328   case ISD::LOAD:               return visitLOAD(N);
1329   case ISD::STORE:              return visitSTORE(N);
1330   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1331   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1332   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1333   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1334   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1335   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1336   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1337   }
1338   return SDValue();
1339 }
1340
1341 SDValue DAGCombiner::combine(SDNode *N) {
1342   SDValue RV = visit(N);
1343
1344   // If nothing happened, try a target-specific DAG combine.
1345   if (!RV.getNode()) {
1346     assert(N->getOpcode() != ISD::DELETED_NODE &&
1347            "Node was deleted but visit returned NULL!");
1348
1349     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1350         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1351
1352       // Expose the DAG combiner to the target combiner impls.
1353       TargetLowering::DAGCombinerInfo
1354         DagCombineInfo(DAG, Level, false, this);
1355
1356       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1357     }
1358   }
1359
1360   // If nothing happened still, try promoting the operation.
1361   if (!RV.getNode()) {
1362     switch (N->getOpcode()) {
1363     default: break;
1364     case ISD::ADD:
1365     case ISD::SUB:
1366     case ISD::MUL:
1367     case ISD::AND:
1368     case ISD::OR:
1369     case ISD::XOR:
1370       RV = PromoteIntBinOp(SDValue(N, 0));
1371       break;
1372     case ISD::SHL:
1373     case ISD::SRA:
1374     case ISD::SRL:
1375       RV = PromoteIntShiftOp(SDValue(N, 0));
1376       break;
1377     case ISD::SIGN_EXTEND:
1378     case ISD::ZERO_EXTEND:
1379     case ISD::ANY_EXTEND:
1380       RV = PromoteExtend(SDValue(N, 0));
1381       break;
1382     case ISD::LOAD:
1383       if (PromoteLoad(SDValue(N, 0)))
1384         RV = SDValue(N, 0);
1385       break;
1386     }
1387   }
1388
1389   // If N is a commutative binary node, try commuting it to enable more
1390   // sdisel CSE.
1391   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1392       N->getNumValues() == 1) {
1393     SDValue N0 = N->getOperand(0);
1394     SDValue N1 = N->getOperand(1);
1395
1396     // Constant operands are canonicalized to RHS.
1397     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1398       SDValue Ops[] = {N1, N0};
1399       SDNode *CSENode;
1400       if (const BinaryWithFlagsSDNode *BinNode =
1401               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1402         CSENode = DAG.getNodeIfExists(
1403             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1404             BinNode->hasNoSignedWrap(), BinNode->isExact());
1405       } else {
1406         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1407       }
1408       if (CSENode)
1409         return SDValue(CSENode, 0);
1410     }
1411   }
1412
1413   return RV;
1414 }
1415
1416 /// Given a node, return its input chain if it has one, otherwise return a null
1417 /// sd operand.
1418 static SDValue getInputChainForNode(SDNode *N) {
1419   if (unsigned NumOps = N->getNumOperands()) {
1420     if (N->getOperand(0).getValueType() == MVT::Other)
1421       return N->getOperand(0);
1422     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1423       return N->getOperand(NumOps-1);
1424     for (unsigned i = 1; i < NumOps-1; ++i)
1425       if (N->getOperand(i).getValueType() == MVT::Other)
1426         return N->getOperand(i);
1427   }
1428   return SDValue();
1429 }
1430
1431 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1432   // If N has two operands, where one has an input chain equal to the other,
1433   // the 'other' chain is redundant.
1434   if (N->getNumOperands() == 2) {
1435     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1436       return N->getOperand(0);
1437     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1438       return N->getOperand(1);
1439   }
1440
1441   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1442   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1443   SmallPtrSet<SDNode*, 16> SeenOps;
1444   bool Changed = false;             // If we should replace this token factor.
1445
1446   // Start out with this token factor.
1447   TFs.push_back(N);
1448
1449   // Iterate through token factors.  The TFs grows when new token factors are
1450   // encountered.
1451   for (unsigned i = 0; i < TFs.size(); ++i) {
1452     SDNode *TF = TFs[i];
1453
1454     // Check each of the operands.
1455     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1456       SDValue Op = TF->getOperand(i);
1457
1458       switch (Op.getOpcode()) {
1459       case ISD::EntryToken:
1460         // Entry tokens don't need to be added to the list. They are
1461         // rededundant.
1462         Changed = true;
1463         break;
1464
1465       case ISD::TokenFactor:
1466         if (Op.hasOneUse() &&
1467             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1468           // Queue up for processing.
1469           TFs.push_back(Op.getNode());
1470           // Clean up in case the token factor is removed.
1471           AddToWorklist(Op.getNode());
1472           Changed = true;
1473           break;
1474         }
1475         // Fall thru
1476
1477       default:
1478         // Only add if it isn't already in the list.
1479         if (SeenOps.insert(Op.getNode()))
1480           Ops.push_back(Op);
1481         else
1482           Changed = true;
1483         break;
1484       }
1485     }
1486   }
1487
1488   SDValue Result;
1489
1490   // If we've change things around then replace token factor.
1491   if (Changed) {
1492     if (Ops.empty()) {
1493       // The entry token is the only possible outcome.
1494       Result = DAG.getEntryNode();
1495     } else {
1496       // New and improved token factor.
1497       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1498     }
1499
1500     // Don't add users to work list.
1501     return CombineTo(N, Result, false);
1502   }
1503
1504   return Result;
1505 }
1506
1507 /// MERGE_VALUES can always be eliminated.
1508 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1509   WorklistRemover DeadNodes(*this);
1510   // Replacing results may cause a different MERGE_VALUES to suddenly
1511   // be CSE'd with N, and carry its uses with it. Iterate until no
1512   // uses remain, to ensure that the node can be safely deleted.
1513   // First add the users of this node to the work list so that they
1514   // can be tried again once they have new operands.
1515   AddUsersToWorklist(N);
1516   do {
1517     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1518       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1519   } while (!N->use_empty());
1520   deleteAndRecombine(N);
1521   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1522 }
1523
1524 SDValue DAGCombiner::visitADD(SDNode *N) {
1525   SDValue N0 = N->getOperand(0);
1526   SDValue N1 = N->getOperand(1);
1527   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1528   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1529   EVT VT = N0.getValueType();
1530
1531   // fold vector ops
1532   if (VT.isVector()) {
1533     SDValue FoldedVOp = SimplifyVBinOp(N);
1534     if (FoldedVOp.getNode()) return FoldedVOp;
1535
1536     // fold (add x, 0) -> x, vector edition
1537     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1538       return N0;
1539     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1540       return N1;
1541   }
1542
1543   // fold (add x, undef) -> undef
1544   if (N0.getOpcode() == ISD::UNDEF)
1545     return N0;
1546   if (N1.getOpcode() == ISD::UNDEF)
1547     return N1;
1548   // fold (add c1, c2) -> c1+c2
1549   if (N0C && N1C)
1550     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1551   // canonicalize constant to RHS
1552   if (N0C && !N1C)
1553     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1554   // fold (add x, 0) -> x
1555   if (N1C && N1C->isNullValue())
1556     return N0;
1557   // fold (add Sym, c) -> Sym+c
1558   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1559     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1560         GA->getOpcode() == ISD::GlobalAddress)
1561       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1562                                   GA->getOffset() +
1563                                     (uint64_t)N1C->getSExtValue());
1564   // fold ((c1-A)+c2) -> (c1+c2)-A
1565   if (N1C && N0.getOpcode() == ISD::SUB)
1566     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1567       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1568                          DAG.getConstant(N1C->getAPIntValue()+
1569                                          N0C->getAPIntValue(), VT),
1570                          N0.getOperand(1));
1571   // reassociate add
1572   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1573   if (RADD.getNode())
1574     return RADD;
1575   // fold ((0-A) + B) -> B-A
1576   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1577       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1578     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1579   // fold (A + (0-B)) -> A-B
1580   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1581       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1582     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1583   // fold (A+(B-A)) -> B
1584   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1585     return N1.getOperand(0);
1586   // fold ((B-A)+A) -> B
1587   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1588     return N0.getOperand(0);
1589   // fold (A+(B-(A+C))) to (B-C)
1590   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1591       N0 == N1.getOperand(1).getOperand(0))
1592     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1593                        N1.getOperand(1).getOperand(1));
1594   // fold (A+(B-(C+A))) to (B-C)
1595   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1596       N0 == N1.getOperand(1).getOperand(1))
1597     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1598                        N1.getOperand(1).getOperand(0));
1599   // fold (A+((B-A)+or-C)) to (B+or-C)
1600   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1601       N1.getOperand(0).getOpcode() == ISD::SUB &&
1602       N0 == N1.getOperand(0).getOperand(1))
1603     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1604                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1605
1606   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1607   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1608     SDValue N00 = N0.getOperand(0);
1609     SDValue N01 = N0.getOperand(1);
1610     SDValue N10 = N1.getOperand(0);
1611     SDValue N11 = N1.getOperand(1);
1612
1613     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1614       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1615                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1616                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1617   }
1618
1619   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1620     return SDValue(N, 0);
1621
1622   // fold (a+b) -> (a|b) iff a and b share no bits.
1623   if (VT.isInteger() && !VT.isVector()) {
1624     APInt LHSZero, LHSOne;
1625     APInt RHSZero, RHSOne;
1626     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1627
1628     if (LHSZero.getBoolValue()) {
1629       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1630
1631       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1632       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1633       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1634         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1635           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1636       }
1637     }
1638   }
1639
1640   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1641   if (N1.getOpcode() == ISD::SHL &&
1642       N1.getOperand(0).getOpcode() == ISD::SUB)
1643     if (ConstantSDNode *C =
1644           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1645       if (C->getAPIntValue() == 0)
1646         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1647                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1648                                        N1.getOperand(0).getOperand(1),
1649                                        N1.getOperand(1)));
1650   if (N0.getOpcode() == ISD::SHL &&
1651       N0.getOperand(0).getOpcode() == ISD::SUB)
1652     if (ConstantSDNode *C =
1653           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1654       if (C->getAPIntValue() == 0)
1655         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1656                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1657                                        N0.getOperand(0).getOperand(1),
1658                                        N0.getOperand(1)));
1659
1660   if (N1.getOpcode() == ISD::AND) {
1661     SDValue AndOp0 = N1.getOperand(0);
1662     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1663     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1664     unsigned DestBits = VT.getScalarType().getSizeInBits();
1665
1666     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1667     // and similar xforms where the inner op is either ~0 or 0.
1668     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1669       SDLoc DL(N);
1670       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1671     }
1672   }
1673
1674   // add (sext i1), X -> sub X, (zext i1)
1675   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1676       N0.getOperand(0).getValueType() == MVT::i1 &&
1677       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1678     SDLoc DL(N);
1679     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1680     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1681   }
1682
1683   return SDValue();
1684 }
1685
1686 SDValue DAGCombiner::visitADDC(SDNode *N) {
1687   SDValue N0 = N->getOperand(0);
1688   SDValue N1 = N->getOperand(1);
1689   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1690   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1691   EVT VT = N0.getValueType();
1692
1693   // If the flag result is dead, turn this into an ADD.
1694   if (!N->hasAnyUseOfValue(1))
1695     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1696                      DAG.getNode(ISD::CARRY_FALSE,
1697                                  SDLoc(N), MVT::Glue));
1698
1699   // canonicalize constant to RHS.
1700   if (N0C && !N1C)
1701     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1702
1703   // fold (addc x, 0) -> x + no carry out
1704   if (N1C && N1C->isNullValue())
1705     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1706                                         SDLoc(N), MVT::Glue));
1707
1708   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1709   APInt LHSZero, LHSOne;
1710   APInt RHSZero, RHSOne;
1711   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1712
1713   if (LHSZero.getBoolValue()) {
1714     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1715
1716     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1717     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1718     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1719       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1720                        DAG.getNode(ISD::CARRY_FALSE,
1721                                    SDLoc(N), MVT::Glue));
1722   }
1723
1724   return SDValue();
1725 }
1726
1727 SDValue DAGCombiner::visitADDE(SDNode *N) {
1728   SDValue N0 = N->getOperand(0);
1729   SDValue N1 = N->getOperand(1);
1730   SDValue CarryIn = N->getOperand(2);
1731   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1732   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1733
1734   // canonicalize constant to RHS
1735   if (N0C && !N1C)
1736     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1737                        N1, N0, CarryIn);
1738
1739   // fold (adde x, y, false) -> (addc x, y)
1740   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1741     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1742
1743   return SDValue();
1744 }
1745
1746 // Since it may not be valid to emit a fold to zero for vector initializers
1747 // check if we can before folding.
1748 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1749                              SelectionDAG &DAG,
1750                              bool LegalOperations, bool LegalTypes) {
1751   if (!VT.isVector())
1752     return DAG.getConstant(0, VT);
1753   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1754     return DAG.getConstant(0, VT);
1755   return SDValue();
1756 }
1757
1758 SDValue DAGCombiner::visitSUB(SDNode *N) {
1759   SDValue N0 = N->getOperand(0);
1760   SDValue N1 = N->getOperand(1);
1761   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1762   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1763   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1764     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1765   EVT VT = N0.getValueType();
1766
1767   // fold vector ops
1768   if (VT.isVector()) {
1769     SDValue FoldedVOp = SimplifyVBinOp(N);
1770     if (FoldedVOp.getNode()) return FoldedVOp;
1771
1772     // fold (sub x, 0) -> x, vector edition
1773     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1774       return N0;
1775   }
1776
1777   // fold (sub x, x) -> 0
1778   // FIXME: Refactor this and xor and other similar operations together.
1779   if (N0 == N1)
1780     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1781   // fold (sub c1, c2) -> c1-c2
1782   if (N0C && N1C)
1783     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1784   // fold (sub x, c) -> (add x, -c)
1785   if (N1C)
1786     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1787                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1788   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1789   if (N0C && N0C->isAllOnesValue())
1790     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1791   // fold A-(A-B) -> B
1792   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1793     return N1.getOperand(1);
1794   // fold (A+B)-A -> B
1795   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1796     return N0.getOperand(1);
1797   // fold (A+B)-B -> A
1798   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1799     return N0.getOperand(0);
1800   // fold C2-(A+C1) -> (C2-C1)-A
1801   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1802     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1803                                    VT);
1804     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1805                        N1.getOperand(0));
1806   }
1807   // fold ((A+(B+or-C))-B) -> A+or-C
1808   if (N0.getOpcode() == ISD::ADD &&
1809       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1810        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1811       N0.getOperand(1).getOperand(0) == N1)
1812     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1813                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1814   // fold ((A+(C+B))-B) -> A+C
1815   if (N0.getOpcode() == ISD::ADD &&
1816       N0.getOperand(1).getOpcode() == ISD::ADD &&
1817       N0.getOperand(1).getOperand(1) == N1)
1818     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1819                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1820   // fold ((A-(B-C))-C) -> A-B
1821   if (N0.getOpcode() == ISD::SUB &&
1822       N0.getOperand(1).getOpcode() == ISD::SUB &&
1823       N0.getOperand(1).getOperand(1) == N1)
1824     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1825                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1826
1827   // If either operand of a sub is undef, the result is undef
1828   if (N0.getOpcode() == ISD::UNDEF)
1829     return N0;
1830   if (N1.getOpcode() == ISD::UNDEF)
1831     return N1;
1832
1833   // If the relocation model supports it, consider symbol offsets.
1834   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1835     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1836       // fold (sub Sym, c) -> Sym-c
1837       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1838         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1839                                     GA->getOffset() -
1840                                       (uint64_t)N1C->getSExtValue());
1841       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1842       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1843         if (GA->getGlobal() == GB->getGlobal())
1844           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1845                                  VT);
1846     }
1847
1848   return SDValue();
1849 }
1850
1851 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1852   SDValue N0 = N->getOperand(0);
1853   SDValue N1 = N->getOperand(1);
1854   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1855   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1856   EVT VT = N0.getValueType();
1857
1858   // If the flag result is dead, turn this into an SUB.
1859   if (!N->hasAnyUseOfValue(1))
1860     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1861                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1862                                  MVT::Glue));
1863
1864   // fold (subc x, x) -> 0 + no borrow
1865   if (N0 == N1)
1866     return CombineTo(N, DAG.getConstant(0, VT),
1867                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1868                                  MVT::Glue));
1869
1870   // fold (subc x, 0) -> x + no borrow
1871   if (N1C && N1C->isNullValue())
1872     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1873                                         MVT::Glue));
1874
1875   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1876   if (N0C && N0C->isAllOnesValue())
1877     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1878                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1879                                  MVT::Glue));
1880
1881   return SDValue();
1882 }
1883
1884 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1885   SDValue N0 = N->getOperand(0);
1886   SDValue N1 = N->getOperand(1);
1887   SDValue CarryIn = N->getOperand(2);
1888
1889   // fold (sube x, y, false) -> (subc x, y)
1890   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1891     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1892
1893   return SDValue();
1894 }
1895
1896 SDValue DAGCombiner::visitMUL(SDNode *N) {
1897   SDValue N0 = N->getOperand(0);
1898   SDValue N1 = N->getOperand(1);
1899   EVT VT = N0.getValueType();
1900
1901   // fold (mul x, undef) -> 0
1902   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1903     return DAG.getConstant(0, VT);
1904
1905   bool N0IsConst = false;
1906   bool N1IsConst = false;
1907   APInt ConstValue0, ConstValue1;
1908   // fold vector ops
1909   if (VT.isVector()) {
1910     SDValue FoldedVOp = SimplifyVBinOp(N);
1911     if (FoldedVOp.getNode()) return FoldedVOp;
1912
1913     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1914     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1915   } else {
1916     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1917     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1918                             : APInt();
1919     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1920     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1921                             : APInt();
1922   }
1923
1924   // fold (mul c1, c2) -> c1*c2
1925   if (N0IsConst && N1IsConst)
1926     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1927
1928   // canonicalize constant to RHS
1929   if (N0IsConst && !N1IsConst)
1930     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1931   // fold (mul x, 0) -> 0
1932   if (N1IsConst && ConstValue1 == 0)
1933     return N1;
1934   // We require a splat of the entire scalar bit width for non-contiguous
1935   // bit patterns.
1936   bool IsFullSplat =
1937     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1938   // fold (mul x, 1) -> x
1939   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1940     return N0;
1941   // fold (mul x, -1) -> 0-x
1942   if (N1IsConst && ConstValue1.isAllOnesValue())
1943     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1944                        DAG.getConstant(0, VT), N0);
1945   // fold (mul x, (1 << c)) -> x << c
1946   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1947     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1948                        DAG.getConstant(ConstValue1.logBase2(),
1949                                        getShiftAmountTy(N0.getValueType())));
1950   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1951   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1952     unsigned Log2Val = (-ConstValue1).logBase2();
1953     // FIXME: If the input is something that is easily negated (e.g. a
1954     // single-use add), we should put the negate there.
1955     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1956                        DAG.getConstant(0, VT),
1957                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1958                             DAG.getConstant(Log2Val,
1959                                       getShiftAmountTy(N0.getValueType()))));
1960   }
1961
1962   APInt Val;
1963   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1964   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1965       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1966                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1967     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1968                              N1, N0.getOperand(1));
1969     AddToWorklist(C3.getNode());
1970     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1971                        N0.getOperand(0), C3);
1972   }
1973
1974   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1975   // use.
1976   {
1977     SDValue Sh(nullptr,0), Y(nullptr,0);
1978     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1979     if (N0.getOpcode() == ISD::SHL &&
1980         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1981                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1982         N0.getNode()->hasOneUse()) {
1983       Sh = N0; Y = N1;
1984     } else if (N1.getOpcode() == ISD::SHL &&
1985                isa<ConstantSDNode>(N1.getOperand(1)) &&
1986                N1.getNode()->hasOneUse()) {
1987       Sh = N1; Y = N0;
1988     }
1989
1990     if (Sh.getNode()) {
1991       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1992                                 Sh.getOperand(0), Y);
1993       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1994                          Mul, Sh.getOperand(1));
1995     }
1996   }
1997
1998   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1999   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2000       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2001                      isa<ConstantSDNode>(N0.getOperand(1))))
2002     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2003                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2004                                    N0.getOperand(0), N1),
2005                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2006                                    N0.getOperand(1), N1));
2007
2008   // reassociate mul
2009   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2010   if (RMUL.getNode())
2011     return RMUL;
2012
2013   return SDValue();
2014 }
2015
2016 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2017   SDValue N0 = N->getOperand(0);
2018   SDValue N1 = N->getOperand(1);
2019   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2020   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2021   EVT VT = N->getValueType(0);
2022
2023   // fold vector ops
2024   if (VT.isVector()) {
2025     SDValue FoldedVOp = SimplifyVBinOp(N);
2026     if (FoldedVOp.getNode()) return FoldedVOp;
2027   }
2028
2029   // fold (sdiv c1, c2) -> c1/c2
2030   if (N0C && N1C && !N1C->isNullValue())
2031     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2032   // fold (sdiv X, 1) -> X
2033   if (N1C && N1C->getAPIntValue() == 1LL)
2034     return N0;
2035   // fold (sdiv X, -1) -> 0-X
2036   if (N1C && N1C->isAllOnesValue())
2037     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2038                        DAG.getConstant(0, VT), N0);
2039   // If we know the sign bits of both operands are zero, strength reduce to a
2040   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2041   if (!VT.isVector()) {
2042     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2043       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2044                          N0, N1);
2045   }
2046
2047   // fold (sdiv X, pow2) -> simple ops after legalize
2048   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2049                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2050     // If dividing by powers of two is cheap, then don't perform the following
2051     // fold.
2052     if (TLI.isPow2SDivCheap())
2053       return SDValue();
2054
2055     // Target-specific implementation of sdiv x, pow2.
2056     SDValue Res = BuildSDIVPow2(N);
2057     if (Res.getNode())
2058       return Res;
2059
2060     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2061
2062     // Splat the sign bit into the register
2063     SDValue SGN =
2064         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2065                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2066                                     getShiftAmountTy(N0.getValueType())));
2067     AddToWorklist(SGN.getNode());
2068
2069     // Add (N0 < 0) ? abs2 - 1 : 0;
2070     SDValue SRL =
2071         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2072                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2073                                     getShiftAmountTy(SGN.getValueType())));
2074     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2075     AddToWorklist(SRL.getNode());
2076     AddToWorklist(ADD.getNode());    // Divide by pow2
2077     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2078                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2079
2080     // If we're dividing by a positive value, we're done.  Otherwise, we must
2081     // negate the result.
2082     if (N1C->getAPIntValue().isNonNegative())
2083       return SRA;
2084
2085     AddToWorklist(SRA.getNode());
2086     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2087   }
2088
2089   // if integer divide is expensive and we satisfy the requirements, emit an
2090   // alternate sequence.
2091   if (N1C && !TLI.isIntDivCheap()) {
2092     SDValue Op = BuildSDIV(N);
2093     if (Op.getNode()) return Op;
2094   }
2095
2096   // undef / X -> 0
2097   if (N0.getOpcode() == ISD::UNDEF)
2098     return DAG.getConstant(0, VT);
2099   // X / undef -> undef
2100   if (N1.getOpcode() == ISD::UNDEF)
2101     return N1;
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2110   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2111   EVT VT = N->getValueType(0);
2112
2113   // fold vector ops
2114   if (VT.isVector()) {
2115     SDValue FoldedVOp = SimplifyVBinOp(N);
2116     if (FoldedVOp.getNode()) return FoldedVOp;
2117   }
2118
2119   // fold (udiv c1, c2) -> c1/c2
2120   if (N0C && N1C && !N1C->isNullValue())
2121     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2122   // fold (udiv x, (1 << c)) -> x >>u c
2123   if (N1C && N1C->getAPIntValue().isPowerOf2())
2124     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2125                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2126                                        getShiftAmountTy(N0.getValueType())));
2127   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2128   if (N1.getOpcode() == ISD::SHL) {
2129     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2130       if (SHC->getAPIntValue().isPowerOf2()) {
2131         EVT ADDVT = N1.getOperand(1).getValueType();
2132         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2133                                   N1.getOperand(1),
2134                                   DAG.getConstant(SHC->getAPIntValue()
2135                                                                   .logBase2(),
2136                                                   ADDVT));
2137         AddToWorklist(Add.getNode());
2138         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2139       }
2140     }
2141   }
2142   // fold (udiv x, c) -> alternate
2143   if (N1C && !TLI.isIntDivCheap()) {
2144     SDValue Op = BuildUDIV(N);
2145     if (Op.getNode()) return Op;
2146   }
2147
2148   // undef / X -> 0
2149   if (N0.getOpcode() == ISD::UNDEF)
2150     return DAG.getConstant(0, VT);
2151   // X / undef -> undef
2152   if (N1.getOpcode() == ISD::UNDEF)
2153     return N1;
2154
2155   return SDValue();
2156 }
2157
2158 SDValue DAGCombiner::visitSREM(SDNode *N) {
2159   SDValue N0 = N->getOperand(0);
2160   SDValue N1 = N->getOperand(1);
2161   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2162   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2163   EVT VT = N->getValueType(0);
2164
2165   // fold (srem c1, c2) -> c1%c2
2166   if (N0C && N1C && !N1C->isNullValue())
2167     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2168   // If we know the sign bits of both operands are zero, strength reduce to a
2169   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2170   if (!VT.isVector()) {
2171     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2172       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2173   }
2174
2175   // If X/C can be simplified by the division-by-constant logic, lower
2176   // X%C to the equivalent of X-X/C*C.
2177   if (N1C && !N1C->isNullValue()) {
2178     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2179     AddToWorklist(Div.getNode());
2180     SDValue OptimizedDiv = combine(Div.getNode());
2181     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2182       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2183                                 OptimizedDiv, N1);
2184       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2185       AddToWorklist(Mul.getNode());
2186       return Sub;
2187     }
2188   }
2189
2190   // undef % X -> 0
2191   if (N0.getOpcode() == ISD::UNDEF)
2192     return DAG.getConstant(0, VT);
2193   // X % undef -> undef
2194   if (N1.getOpcode() == ISD::UNDEF)
2195     return N1;
2196
2197   return SDValue();
2198 }
2199
2200 SDValue DAGCombiner::visitUREM(SDNode *N) {
2201   SDValue N0 = N->getOperand(0);
2202   SDValue N1 = N->getOperand(1);
2203   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2204   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2205   EVT VT = N->getValueType(0);
2206
2207   // fold (urem c1, c2) -> c1%c2
2208   if (N0C && N1C && !N1C->isNullValue())
2209     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2210   // fold (urem x, pow2) -> (and x, pow2-1)
2211   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2212     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2213                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2214   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2215   if (N1.getOpcode() == ISD::SHL) {
2216     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2217       if (SHC->getAPIntValue().isPowerOf2()) {
2218         SDValue Add =
2219           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2220                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2221                                  VT));
2222         AddToWorklist(Add.getNode());
2223         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2224       }
2225     }
2226   }
2227
2228   // If X/C can be simplified by the division-by-constant logic, lower
2229   // X%C to the equivalent of X-X/C*C.
2230   if (N1C && !N1C->isNullValue()) {
2231     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2232     AddToWorklist(Div.getNode());
2233     SDValue OptimizedDiv = combine(Div.getNode());
2234     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2235       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2236                                 OptimizedDiv, N1);
2237       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2238       AddToWorklist(Mul.getNode());
2239       return Sub;
2240     }
2241   }
2242
2243   // undef % X -> 0
2244   if (N0.getOpcode() == ISD::UNDEF)
2245     return DAG.getConstant(0, VT);
2246   // X % undef -> undef
2247   if (N1.getOpcode() == ISD::UNDEF)
2248     return N1;
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2257   EVT VT = N->getValueType(0);
2258   SDLoc DL(N);
2259
2260   // fold (mulhs x, 0) -> 0
2261   if (N1C && N1C->isNullValue())
2262     return N1;
2263   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2264   if (N1C && N1C->getAPIntValue() == 1)
2265     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2266                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2267                                        getShiftAmountTy(N0.getValueType())));
2268   // fold (mulhs x, undef) -> 0
2269   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2270     return DAG.getConstant(0, VT);
2271
2272   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2273   // plus a shift.
2274   if (VT.isSimple() && !VT.isVector()) {
2275     MVT Simple = VT.getSimpleVT();
2276     unsigned SimpleSize = Simple.getSizeInBits();
2277     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2278     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2279       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2280       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2281       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2282       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2283             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2284       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2285     }
2286   }
2287
2288   return SDValue();
2289 }
2290
2291 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2292   SDValue N0 = N->getOperand(0);
2293   SDValue N1 = N->getOperand(1);
2294   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2295   EVT VT = N->getValueType(0);
2296   SDLoc DL(N);
2297
2298   // fold (mulhu x, 0) -> 0
2299   if (N1C && N1C->isNullValue())
2300     return N1;
2301   // fold (mulhu x, 1) -> 0
2302   if (N1C && N1C->getAPIntValue() == 1)
2303     return DAG.getConstant(0, N0.getValueType());
2304   // fold (mulhu x, undef) -> 0
2305   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2306     return DAG.getConstant(0, VT);
2307
2308   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2309   // plus a shift.
2310   if (VT.isSimple() && !VT.isVector()) {
2311     MVT Simple = VT.getSimpleVT();
2312     unsigned SimpleSize = Simple.getSizeInBits();
2313     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2314     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2315       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2316       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2317       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2318       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2319             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2320       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2321     }
2322   }
2323
2324   return SDValue();
2325 }
2326
2327 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2328 /// give the opcodes for the two computations that are being performed. Return
2329 /// true if a simplification was made.
2330 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2331                                                 unsigned HiOp) {
2332   // If the high half is not needed, just compute the low half.
2333   bool HiExists = N->hasAnyUseOfValue(1);
2334   if (!HiExists &&
2335       (!LegalOperations ||
2336        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2337     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2338     return CombineTo(N, Res, Res);
2339   }
2340
2341   // If the low half is not needed, just compute the high half.
2342   bool LoExists = N->hasAnyUseOfValue(0);
2343   if (!LoExists &&
2344       (!LegalOperations ||
2345        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2346     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2347     return CombineTo(N, Res, Res);
2348   }
2349
2350   // If both halves are used, return as it is.
2351   if (LoExists && HiExists)
2352     return SDValue();
2353
2354   // If the two computed results can be simplified separately, separate them.
2355   if (LoExists) {
2356     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2357     AddToWorklist(Lo.getNode());
2358     SDValue LoOpt = combine(Lo.getNode());
2359     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2360         (!LegalOperations ||
2361          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2362       return CombineTo(N, LoOpt, LoOpt);
2363   }
2364
2365   if (HiExists) {
2366     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2367     AddToWorklist(Hi.getNode());
2368     SDValue HiOpt = combine(Hi.getNode());
2369     if (HiOpt.getNode() && HiOpt != Hi &&
2370         (!LegalOperations ||
2371          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2372       return CombineTo(N, HiOpt, HiOpt);
2373   }
2374
2375   return SDValue();
2376 }
2377
2378 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2379   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2380   if (Res.getNode()) return Res;
2381
2382   EVT VT = N->getValueType(0);
2383   SDLoc DL(N);
2384
2385   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2386   // plus a shift.
2387   if (VT.isSimple() && !VT.isVector()) {
2388     MVT Simple = VT.getSimpleVT();
2389     unsigned SimpleSize = Simple.getSizeInBits();
2390     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2391     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2392       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2393       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2394       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2395       // Compute the high part as N1.
2396       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2397             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2398       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2399       // Compute the low part as N0.
2400       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2401       return CombineTo(N, Lo, Hi);
2402     }
2403   }
2404
2405   return SDValue();
2406 }
2407
2408 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2409   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2410   if (Res.getNode()) return Res;
2411
2412   EVT VT = N->getValueType(0);
2413   SDLoc DL(N);
2414
2415   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2416   // plus a shift.
2417   if (VT.isSimple() && !VT.isVector()) {
2418     MVT Simple = VT.getSimpleVT();
2419     unsigned SimpleSize = Simple.getSizeInBits();
2420     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2421     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2422       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2423       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2424       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2425       // Compute the high part as N1.
2426       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2427             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2428       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2429       // Compute the low part as N0.
2430       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2431       return CombineTo(N, Lo, Hi);
2432     }
2433   }
2434
2435   return SDValue();
2436 }
2437
2438 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2439   // (smulo x, 2) -> (saddo x, x)
2440   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2441     if (C2->getAPIntValue() == 2)
2442       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2443                          N->getOperand(0), N->getOperand(0));
2444
2445   return SDValue();
2446 }
2447
2448 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2449   // (umulo x, 2) -> (uaddo x, x)
2450   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2451     if (C2->getAPIntValue() == 2)
2452       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2453                          N->getOperand(0), N->getOperand(0));
2454
2455   return SDValue();
2456 }
2457
2458 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2459   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2460   if (Res.getNode()) return Res;
2461
2462   return SDValue();
2463 }
2464
2465 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2466   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2467   if (Res.getNode()) return Res;
2468
2469   return SDValue();
2470 }
2471
2472 /// If this is a binary operator with two operands of the same opcode, try to
2473 /// simplify it.
2474 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2475   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2476   EVT VT = N0.getValueType();
2477   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2478
2479   // Bail early if none of these transforms apply.
2480   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2481
2482   // For each of OP in AND/OR/XOR:
2483   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2484   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2485   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2486   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2487   //
2488   // do not sink logical op inside of a vector extend, since it may combine
2489   // into a vsetcc.
2490   EVT Op0VT = N0.getOperand(0).getValueType();
2491   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2492        N0.getOpcode() == ISD::SIGN_EXTEND ||
2493        // Avoid infinite looping with PromoteIntBinOp.
2494        (N0.getOpcode() == ISD::ANY_EXTEND &&
2495         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2496        (N0.getOpcode() == ISD::TRUNCATE &&
2497         (!TLI.isZExtFree(VT, Op0VT) ||
2498          !TLI.isTruncateFree(Op0VT, VT)) &&
2499         TLI.isTypeLegal(Op0VT))) &&
2500       !VT.isVector() &&
2501       Op0VT == N1.getOperand(0).getValueType() &&
2502       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2503     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2504                                  N0.getOperand(0).getValueType(),
2505                                  N0.getOperand(0), N1.getOperand(0));
2506     AddToWorklist(ORNode.getNode());
2507     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2508   }
2509
2510   // For each of OP in SHL/SRL/SRA/AND...
2511   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2512   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2513   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2514   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2515        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2516       N0.getOperand(1) == N1.getOperand(1)) {
2517     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2518                                  N0.getOperand(0).getValueType(),
2519                                  N0.getOperand(0), N1.getOperand(0));
2520     AddToWorklist(ORNode.getNode());
2521     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2522                        ORNode, N0.getOperand(1));
2523   }
2524
2525   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2526   // Only perform this optimization after type legalization and before
2527   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2528   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2529   // we don't want to undo this promotion.
2530   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2531   // on scalars.
2532   if ((N0.getOpcode() == ISD::BITCAST ||
2533        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2534       Level == AfterLegalizeTypes) {
2535     SDValue In0 = N0.getOperand(0);
2536     SDValue In1 = N1.getOperand(0);
2537     EVT In0Ty = In0.getValueType();
2538     EVT In1Ty = In1.getValueType();
2539     SDLoc DL(N);
2540     // If both incoming values are integers, and the original types are the
2541     // same.
2542     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2543       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2544       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2545       AddToWorklist(Op.getNode());
2546       return BC;
2547     }
2548   }
2549
2550   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2551   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2552   // If both shuffles use the same mask, and both shuffle within a single
2553   // vector, then it is worthwhile to move the swizzle after the operation.
2554   // The type-legalizer generates this pattern when loading illegal
2555   // vector types from memory. In many cases this allows additional shuffle
2556   // optimizations.
2557   // There are other cases where moving the shuffle after the xor/and/or
2558   // is profitable even if shuffles don't perform a swizzle.
2559   // If both shuffles use the same mask, and both shuffles have the same first
2560   // or second operand, then it might still be profitable to move the shuffle
2561   // after the xor/and/or operation.
2562   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2563     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2564     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2565
2566     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2567            "Inputs to shuffles are not the same type");
2568
2569     // Check that both shuffles use the same mask. The masks are known to be of
2570     // the same length because the result vector type is the same.
2571     // Check also that shuffles have only one use to avoid introducing extra
2572     // instructions.
2573     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2574         SVN0->getMask().equals(SVN1->getMask())) {
2575       SDValue ShOp = N0->getOperand(1);
2576
2577       // Don't try to fold this node if it requires introducing a
2578       // build vector of all zeros that might be illegal at this stage.
2579       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2580         if (!LegalTypes)
2581           ShOp = DAG.getConstant(0, VT);
2582         else
2583           ShOp = SDValue();
2584       }
2585
2586       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2587       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2588       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2589       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2590         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2591                                       N0->getOperand(0), N1->getOperand(0));
2592         AddToWorklist(NewNode.getNode());
2593         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2594                                     &SVN0->getMask()[0]);
2595       }
2596
2597       // Don't try to fold this node if it requires introducing a
2598       // build vector of all zeros that might be illegal at this stage.
2599       ShOp = N0->getOperand(0);
2600       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2601         if (!LegalTypes)
2602           ShOp = DAG.getConstant(0, VT);
2603         else
2604           ShOp = SDValue();
2605       }
2606
2607       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2608       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2609       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2610       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2611         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2612                                       N0->getOperand(1), N1->getOperand(1));
2613         AddToWorklist(NewNode.getNode());
2614         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2615                                     &SVN0->getMask()[0]);
2616       }
2617     }
2618   }
2619
2620   return SDValue();
2621 }
2622
2623 SDValue DAGCombiner::visitAND(SDNode *N) {
2624   SDValue N0 = N->getOperand(0);
2625   SDValue N1 = N->getOperand(1);
2626   SDValue LL, LR, RL, RR, CC0, CC1;
2627   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2628   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2629   EVT VT = N1.getValueType();
2630   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2631
2632   // fold vector ops
2633   if (VT.isVector()) {
2634     SDValue FoldedVOp = SimplifyVBinOp(N);
2635     if (FoldedVOp.getNode()) return FoldedVOp;
2636
2637     // fold (and x, 0) -> 0, vector edition
2638     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2639       // do not return N0, because undef node may exist in N0
2640       return DAG.getConstant(
2641           APInt::getNullValue(
2642               N0.getValueType().getScalarType().getSizeInBits()),
2643           N0.getValueType());
2644     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2645       // do not return N1, because undef node may exist in N1
2646       return DAG.getConstant(
2647           APInt::getNullValue(
2648               N1.getValueType().getScalarType().getSizeInBits()),
2649           N1.getValueType());
2650
2651     // fold (and x, -1) -> x, vector edition
2652     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2653       return N1;
2654     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2655       return N0;
2656   }
2657
2658   // fold (and x, undef) -> 0
2659   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2660     return DAG.getConstant(0, VT);
2661   // fold (and c1, c2) -> c1&c2
2662   if (N0C && N1C)
2663     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2664   // canonicalize constant to RHS
2665   if (N0C && !N1C)
2666     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2667   // fold (and x, -1) -> x
2668   if (N1C && N1C->isAllOnesValue())
2669     return N0;
2670   // if (and x, c) is known to be zero, return 0
2671   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2672                                    APInt::getAllOnesValue(BitWidth)))
2673     return DAG.getConstant(0, VT);
2674   // reassociate and
2675   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2676   if (RAND.getNode())
2677     return RAND;
2678   // fold (and (or x, C), D) -> D if (C & D) == D
2679   if (N1C && N0.getOpcode() == ISD::OR)
2680     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2681       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2682         return N1;
2683   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2684   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2685     SDValue N0Op0 = N0.getOperand(0);
2686     APInt Mask = ~N1C->getAPIntValue();
2687     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2688     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2689       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2690                                  N0.getValueType(), N0Op0);
2691
2692       // Replace uses of the AND with uses of the Zero extend node.
2693       CombineTo(N, Zext);
2694
2695       // We actually want to replace all uses of the any_extend with the
2696       // zero_extend, to avoid duplicating things.  This will later cause this
2697       // AND to be folded.
2698       CombineTo(N0.getNode(), Zext);
2699       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2700     }
2701   }
2702   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2703   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2704   // already be zero by virtue of the width of the base type of the load.
2705   //
2706   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2707   // more cases.
2708   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2709        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2710       N0.getOpcode() == ISD::LOAD) {
2711     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2712                                          N0 : N0.getOperand(0) );
2713
2714     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2715     // This can be a pure constant or a vector splat, in which case we treat the
2716     // vector as a scalar and use the splat value.
2717     APInt Constant = APInt::getNullValue(1);
2718     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2719       Constant = C->getAPIntValue();
2720     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2721       APInt SplatValue, SplatUndef;
2722       unsigned SplatBitSize;
2723       bool HasAnyUndefs;
2724       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2725                                              SplatBitSize, HasAnyUndefs);
2726       if (IsSplat) {
2727         // Undef bits can contribute to a possible optimisation if set, so
2728         // set them.
2729         SplatValue |= SplatUndef;
2730
2731         // The splat value may be something like "0x00FFFFFF", which means 0 for
2732         // the first vector value and FF for the rest, repeating. We need a mask
2733         // that will apply equally to all members of the vector, so AND all the
2734         // lanes of the constant together.
2735         EVT VT = Vector->getValueType(0);
2736         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2737
2738         // If the splat value has been compressed to a bitlength lower
2739         // than the size of the vector lane, we need to re-expand it to
2740         // the lane size.
2741         if (BitWidth > SplatBitSize)
2742           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2743                SplatBitSize < BitWidth;
2744                SplatBitSize = SplatBitSize * 2)
2745             SplatValue |= SplatValue.shl(SplatBitSize);
2746
2747         Constant = APInt::getAllOnesValue(BitWidth);
2748         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2749           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2750       }
2751     }
2752
2753     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2754     // actually legal and isn't going to get expanded, else this is a false
2755     // optimisation.
2756     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2757                                                     Load->getMemoryVT());
2758
2759     // Resize the constant to the same size as the original memory access before
2760     // extension. If it is still the AllOnesValue then this AND is completely
2761     // unneeded.
2762     Constant =
2763       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2764
2765     bool B;
2766     switch (Load->getExtensionType()) {
2767     default: B = false; break;
2768     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2769     case ISD::ZEXTLOAD:
2770     case ISD::NON_EXTLOAD: B = true; break;
2771     }
2772
2773     if (B && Constant.isAllOnesValue()) {
2774       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2775       // preserve semantics once we get rid of the AND.
2776       SDValue NewLoad(Load, 0);
2777       if (Load->getExtensionType() == ISD::EXTLOAD) {
2778         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2779                               Load->getValueType(0), SDLoc(Load),
2780                               Load->getChain(), Load->getBasePtr(),
2781                               Load->getOffset(), Load->getMemoryVT(),
2782                               Load->getMemOperand());
2783         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2784         if (Load->getNumValues() == 3) {
2785           // PRE/POST_INC loads have 3 values.
2786           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2787                            NewLoad.getValue(2) };
2788           CombineTo(Load, To, 3, true);
2789         } else {
2790           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2791         }
2792       }
2793
2794       // Fold the AND away, taking care not to fold to the old load node if we
2795       // replaced it.
2796       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2797
2798       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2799     }
2800   }
2801   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2802   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2803     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2804     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2805
2806     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2807         LL.getValueType().isInteger()) {
2808       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2809       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2810         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2811                                      LR.getValueType(), LL, RL);
2812         AddToWorklist(ORNode.getNode());
2813         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2814       }
2815       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2816       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2817         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2818                                       LR.getValueType(), LL, RL);
2819         AddToWorklist(ANDNode.getNode());
2820         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2821       }
2822       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2823       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2824         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2825                                      LR.getValueType(), LL, RL);
2826         AddToWorklist(ORNode.getNode());
2827         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2828       }
2829     }
2830     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2831     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2832         Op0 == Op1 && LL.getValueType().isInteger() &&
2833       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2834                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2835                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2836                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2837       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2838                                     LL, DAG.getConstant(1, LL.getValueType()));
2839       AddToWorklist(ADDNode.getNode());
2840       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2841                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2842     }
2843     // canonicalize equivalent to ll == rl
2844     if (LL == RR && LR == RL) {
2845       Op1 = ISD::getSetCCSwappedOperands(Op1);
2846       std::swap(RL, RR);
2847     }
2848     if (LL == RL && LR == RR) {
2849       bool isInteger = LL.getValueType().isInteger();
2850       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2851       if (Result != ISD::SETCC_INVALID &&
2852           (!LegalOperations ||
2853            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2854             TLI.isOperationLegal(ISD::SETCC,
2855                             getSetCCResultType(N0.getSimpleValueType())))))
2856         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2857                             LL, LR, Result);
2858     }
2859   }
2860
2861   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2862   if (N0.getOpcode() == N1.getOpcode()) {
2863     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2864     if (Tmp.getNode()) return Tmp;
2865   }
2866
2867   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2868   // fold (and (sra)) -> (and (srl)) when possible.
2869   if (!VT.isVector() &&
2870       SimplifyDemandedBits(SDValue(N, 0)))
2871     return SDValue(N, 0);
2872
2873   // fold (zext_inreg (extload x)) -> (zextload x)
2874   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2875     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2876     EVT MemVT = LN0->getMemoryVT();
2877     // If we zero all the possible extended bits, then we can turn this into
2878     // a zextload if we are running before legalize or the operation is legal.
2879     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2880     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2881                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2882         ((!LegalOperations && !LN0->isVolatile()) ||
2883          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2884       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2885                                        LN0->getChain(), LN0->getBasePtr(),
2886                                        MemVT, LN0->getMemOperand());
2887       AddToWorklist(N);
2888       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2889       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2890     }
2891   }
2892   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2893   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2894       N0.hasOneUse()) {
2895     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2896     EVT MemVT = LN0->getMemoryVT();
2897     // If we zero all the possible extended bits, then we can turn this into
2898     // a zextload if we are running before legalize or the operation is legal.
2899     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2900     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2901                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2902         ((!LegalOperations && !LN0->isVolatile()) ||
2903          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2904       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2905                                        LN0->getChain(), LN0->getBasePtr(),
2906                                        MemVT, LN0->getMemOperand());
2907       AddToWorklist(N);
2908       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910     }
2911   }
2912
2913   // fold (and (load x), 255) -> (zextload x, i8)
2914   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2915   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2916   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2917               (N0.getOpcode() == ISD::ANY_EXTEND &&
2918                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2919     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2920     LoadSDNode *LN0 = HasAnyExt
2921       ? cast<LoadSDNode>(N0.getOperand(0))
2922       : cast<LoadSDNode>(N0);
2923     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2924         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2925       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2926       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2927         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2928         EVT LoadedVT = LN0->getMemoryVT();
2929
2930         if (ExtVT == LoadedVT &&
2931             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2932           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2933
2934           SDValue NewLoad =
2935             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2936                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2937                            LN0->getMemOperand());
2938           AddToWorklist(N);
2939           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2940           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2941         }
2942
2943         // Do not change the width of a volatile load.
2944         // Do not generate loads of non-round integer types since these can
2945         // be expensive (and would be wrong if the type is not byte sized).
2946         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2947             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2948           EVT PtrType = LN0->getOperand(1).getValueType();
2949
2950           unsigned Alignment = LN0->getAlignment();
2951           SDValue NewPtr = LN0->getBasePtr();
2952
2953           // For big endian targets, we need to add an offset to the pointer
2954           // to load the correct bytes.  For little endian systems, we merely
2955           // need to read fewer bytes from the same pointer.
2956           if (TLI.isBigEndian()) {
2957             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2958             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2959             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2960             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2961                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2962             Alignment = MinAlign(Alignment, PtrOff);
2963           }
2964
2965           AddToWorklist(NewPtr.getNode());
2966
2967           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2968           SDValue Load =
2969             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2970                            LN0->getChain(), NewPtr,
2971                            LN0->getPointerInfo(),
2972                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2973                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
2974           AddToWorklist(N);
2975           CombineTo(LN0, Load, Load.getValue(1));
2976           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2977         }
2978       }
2979     }
2980   }
2981
2982   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2983       VT.getSizeInBits() <= 64) {
2984     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2985       APInt ADDC = ADDI->getAPIntValue();
2986       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2987         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2988         // immediate for an add, but it is legal if its top c2 bits are set,
2989         // transform the ADD so the immediate doesn't need to be materialized
2990         // in a register.
2991         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2992           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2993                                              SRLI->getZExtValue());
2994           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2995             ADDC |= Mask;
2996             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2997               SDValue NewAdd =
2998                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2999                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3000               CombineTo(N0.getNode(), NewAdd);
3001               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3002             }
3003           }
3004         }
3005       }
3006     }
3007   }
3008
3009   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3010   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3011     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3012                                        N0.getOperand(1), false);
3013     if (BSwap.getNode())
3014       return BSwap;
3015   }
3016
3017   return SDValue();
3018 }
3019
3020 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3021 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3022                                         bool DemandHighBits) {
3023   if (!LegalOperations)
3024     return SDValue();
3025
3026   EVT VT = N->getValueType(0);
3027   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3028     return SDValue();
3029   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3030     return SDValue();
3031
3032   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3033   bool LookPassAnd0 = false;
3034   bool LookPassAnd1 = false;
3035   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3036       std::swap(N0, N1);
3037   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3038       std::swap(N0, N1);
3039   if (N0.getOpcode() == ISD::AND) {
3040     if (!N0.getNode()->hasOneUse())
3041       return SDValue();
3042     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3043     if (!N01C || N01C->getZExtValue() != 0xFF00)
3044       return SDValue();
3045     N0 = N0.getOperand(0);
3046     LookPassAnd0 = true;
3047   }
3048
3049   if (N1.getOpcode() == ISD::AND) {
3050     if (!N1.getNode()->hasOneUse())
3051       return SDValue();
3052     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3053     if (!N11C || N11C->getZExtValue() != 0xFF)
3054       return SDValue();
3055     N1 = N1.getOperand(0);
3056     LookPassAnd1 = true;
3057   }
3058
3059   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3060     std::swap(N0, N1);
3061   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3062     return SDValue();
3063   if (!N0.getNode()->hasOneUse() ||
3064       !N1.getNode()->hasOneUse())
3065     return SDValue();
3066
3067   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3068   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3069   if (!N01C || !N11C)
3070     return SDValue();
3071   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3072     return SDValue();
3073
3074   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3075   SDValue N00 = N0->getOperand(0);
3076   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3077     if (!N00.getNode()->hasOneUse())
3078       return SDValue();
3079     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3080     if (!N001C || N001C->getZExtValue() != 0xFF)
3081       return SDValue();
3082     N00 = N00.getOperand(0);
3083     LookPassAnd0 = true;
3084   }
3085
3086   SDValue N10 = N1->getOperand(0);
3087   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3088     if (!N10.getNode()->hasOneUse())
3089       return SDValue();
3090     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3091     if (!N101C || N101C->getZExtValue() != 0xFF00)
3092       return SDValue();
3093     N10 = N10.getOperand(0);
3094     LookPassAnd1 = true;
3095   }
3096
3097   if (N00 != N10)
3098     return SDValue();
3099
3100   // Make sure everything beyond the low halfword gets set to zero since the SRL
3101   // 16 will clear the top bits.
3102   unsigned OpSizeInBits = VT.getSizeInBits();
3103   if (DemandHighBits && OpSizeInBits > 16) {
3104     // If the left-shift isn't masked out then the only way this is a bswap is
3105     // if all bits beyond the low 8 are 0. In that case the entire pattern
3106     // reduces to a left shift anyway: leave it for other parts of the combiner.
3107     if (!LookPassAnd0)
3108       return SDValue();
3109
3110     // However, if the right shift isn't masked out then it might be because
3111     // it's not needed. See if we can spot that too.
3112     if (!LookPassAnd1 &&
3113         !DAG.MaskedValueIsZero(
3114             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3115       return SDValue();
3116   }
3117
3118   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3119   if (OpSizeInBits > 16)
3120     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3121                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3122   return Res;
3123 }
3124
3125 /// Return true if the specified node is an element that makes up a 32-bit
3126 /// packed halfword byteswap.
3127 /// ((x & 0x000000ff) << 8) |
3128 /// ((x & 0x0000ff00) >> 8) |
3129 /// ((x & 0x00ff0000) << 8) |
3130 /// ((x & 0xff000000) >> 8)
3131 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3132   if (!N.getNode()->hasOneUse())
3133     return false;
3134
3135   unsigned Opc = N.getOpcode();
3136   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3137     return false;
3138
3139   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3140   if (!N1C)
3141     return false;
3142
3143   unsigned Num;
3144   switch (N1C->getZExtValue()) {
3145   default:
3146     return false;
3147   case 0xFF:       Num = 0; break;
3148   case 0xFF00:     Num = 1; break;
3149   case 0xFF0000:   Num = 2; break;
3150   case 0xFF000000: Num = 3; break;
3151   }
3152
3153   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3154   SDValue N0 = N.getOperand(0);
3155   if (Opc == ISD::AND) {
3156     if (Num == 0 || Num == 2) {
3157       // (x >> 8) & 0xff
3158       // (x >> 8) & 0xff0000
3159       if (N0.getOpcode() != ISD::SRL)
3160         return false;
3161       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3162       if (!C || C->getZExtValue() != 8)
3163         return false;
3164     } else {
3165       // (x << 8) & 0xff00
3166       // (x << 8) & 0xff000000
3167       if (N0.getOpcode() != ISD::SHL)
3168         return false;
3169       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3170       if (!C || C->getZExtValue() != 8)
3171         return false;
3172     }
3173   } else if (Opc == ISD::SHL) {
3174     // (x & 0xff) << 8
3175     // (x & 0xff0000) << 8
3176     if (Num != 0 && Num != 2)
3177       return false;
3178     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3179     if (!C || C->getZExtValue() != 8)
3180       return false;
3181   } else { // Opc == ISD::SRL
3182     // (x & 0xff00) >> 8
3183     // (x & 0xff000000) >> 8
3184     if (Num != 1 && Num != 3)
3185       return false;
3186     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3187     if (!C || C->getZExtValue() != 8)
3188       return false;
3189   }
3190
3191   if (Parts[Num])
3192     return false;
3193
3194   Parts[Num] = N0.getOperand(0).getNode();
3195   return true;
3196 }
3197
3198 /// Match a 32-bit packed halfword bswap. That is
3199 /// ((x & 0x000000ff) << 8) |
3200 /// ((x & 0x0000ff00) >> 8) |
3201 /// ((x & 0x00ff0000) << 8) |
3202 /// ((x & 0xff000000) >> 8)
3203 /// => (rotl (bswap x), 16)
3204 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3205   if (!LegalOperations)
3206     return SDValue();
3207
3208   EVT VT = N->getValueType(0);
3209   if (VT != MVT::i32)
3210     return SDValue();
3211   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3212     return SDValue();
3213
3214   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3215   // Look for either
3216   // (or (or (and), (and)), (or (and), (and)))
3217   // (or (or (or (and), (and)), (and)), (and))
3218   if (N0.getOpcode() != ISD::OR)
3219     return SDValue();
3220   SDValue N00 = N0.getOperand(0);
3221   SDValue N01 = N0.getOperand(1);
3222
3223   if (N1.getOpcode() == ISD::OR &&
3224       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3225     // (or (or (and), (and)), (or (and), (and)))
3226     SDValue N000 = N00.getOperand(0);
3227     if (!isBSwapHWordElement(N000, Parts))
3228       return SDValue();
3229
3230     SDValue N001 = N00.getOperand(1);
3231     if (!isBSwapHWordElement(N001, Parts))
3232       return SDValue();
3233     SDValue N010 = N01.getOperand(0);
3234     if (!isBSwapHWordElement(N010, Parts))
3235       return SDValue();
3236     SDValue N011 = N01.getOperand(1);
3237     if (!isBSwapHWordElement(N011, Parts))
3238       return SDValue();
3239   } else {
3240     // (or (or (or (and), (and)), (and)), (and))
3241     if (!isBSwapHWordElement(N1, Parts))
3242       return SDValue();
3243     if (!isBSwapHWordElement(N01, Parts))
3244       return SDValue();
3245     if (N00.getOpcode() != ISD::OR)
3246       return SDValue();
3247     SDValue N000 = N00.getOperand(0);
3248     if (!isBSwapHWordElement(N000, Parts))
3249       return SDValue();
3250     SDValue N001 = N00.getOperand(1);
3251     if (!isBSwapHWordElement(N001, Parts))
3252       return SDValue();
3253   }
3254
3255   // Make sure the parts are all coming from the same node.
3256   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3257     return SDValue();
3258
3259   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3260                               SDValue(Parts[0],0));
3261
3262   // Result of the bswap should be rotated by 16. If it's not legal, then
3263   // do  (x << 16) | (x >> 16).
3264   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3265   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3266     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3267   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3268     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3269   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3270                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3271                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3272 }
3273
3274 SDValue DAGCombiner::visitOR(SDNode *N) {
3275   SDValue N0 = N->getOperand(0);
3276   SDValue N1 = N->getOperand(1);
3277   SDValue LL, LR, RL, RR, CC0, CC1;
3278   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3280   EVT VT = N1.getValueType();
3281
3282   // fold vector ops
3283   if (VT.isVector()) {
3284     SDValue FoldedVOp = SimplifyVBinOp(N);
3285     if (FoldedVOp.getNode()) return FoldedVOp;
3286
3287     // fold (or x, 0) -> x, vector edition
3288     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3289       return N1;
3290     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3291       return N0;
3292
3293     // fold (or x, -1) -> -1, vector edition
3294     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3295       // do not return N0, because undef node may exist in N0
3296       return DAG.getConstant(
3297           APInt::getAllOnesValue(
3298               N0.getValueType().getScalarType().getSizeInBits()),
3299           N0.getValueType());
3300     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3301       // do not return N1, because undef node may exist in N1
3302       return DAG.getConstant(
3303           APInt::getAllOnesValue(
3304               N1.getValueType().getScalarType().getSizeInBits()),
3305           N1.getValueType());
3306
3307     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3308     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3309     // Do this only if the resulting shuffle is legal.
3310     if (isa<ShuffleVectorSDNode>(N0) &&
3311         isa<ShuffleVectorSDNode>(N1) &&
3312         // Avoid folding a node with illegal type.
3313         TLI.isTypeLegal(VT) &&
3314         N0->getOperand(1) == N1->getOperand(1) &&
3315         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3316       bool CanFold = true;
3317       unsigned NumElts = VT.getVectorNumElements();
3318       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3319       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3320       // We construct two shuffle masks:
3321       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3322       // and N1 as the second operand.
3323       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3324       // and N0 as the second operand.
3325       // We do this because OR is commutable and therefore there might be
3326       // two ways to fold this node into a shuffle.
3327       SmallVector<int,4> Mask1;
3328       SmallVector<int,4> Mask2;
3329
3330       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3331         int M0 = SV0->getMaskElt(i);
3332         int M1 = SV1->getMaskElt(i);
3333
3334         // Both shuffle indexes are undef. Propagate Undef.
3335         if (M0 < 0 && M1 < 0) {
3336           Mask1.push_back(M0);
3337           Mask2.push_back(M0);
3338           continue;
3339         }
3340
3341         if (M0 < 0 || M1 < 0 ||
3342             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3343             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3344           CanFold = false;
3345           break;
3346         }
3347
3348         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3349         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3350       }
3351
3352       if (CanFold) {
3353         // Fold this sequence only if the resulting shuffle is 'legal'.
3354         if (TLI.isShuffleMaskLegal(Mask1, VT))
3355           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3356                                       N1->getOperand(0), &Mask1[0]);
3357         if (TLI.isShuffleMaskLegal(Mask2, VT))
3358           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3359                                       N0->getOperand(0), &Mask2[0]);
3360       }
3361     }
3362   }
3363
3364   // fold (or x, undef) -> -1
3365   if (!LegalOperations &&
3366       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3367     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3368     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3369   }
3370   // fold (or c1, c2) -> c1|c2
3371   if (N0C && N1C)
3372     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3373   // canonicalize constant to RHS
3374   if (N0C && !N1C)
3375     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3376   // fold (or x, 0) -> x
3377   if (N1C && N1C->isNullValue())
3378     return N0;
3379   // fold (or x, -1) -> -1
3380   if (N1C && N1C->isAllOnesValue())
3381     return N1;
3382   // fold (or x, c) -> c iff (x & ~c) == 0
3383   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3384     return N1;
3385
3386   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3387   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3388   if (BSwap.getNode())
3389     return BSwap;
3390   BSwap = MatchBSwapHWordLow(N, N0, N1);
3391   if (BSwap.getNode())
3392     return BSwap;
3393
3394   // reassociate or
3395   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3396   if (ROR.getNode())
3397     return ROR;
3398   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3399   // iff (c1 & c2) == 0.
3400   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3401              isa<ConstantSDNode>(N0.getOperand(1))) {
3402     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3403     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3404       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3405       if (!COR.getNode())
3406         return SDValue();
3407       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3408                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3409                                      N0.getOperand(0), N1), COR);
3410     }
3411   }
3412   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3413   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3414     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3415     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3416
3417     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3418         LL.getValueType().isInteger()) {
3419       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3420       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3421       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3422           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3423         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3424                                      LR.getValueType(), LL, RL);
3425         AddToWorklist(ORNode.getNode());
3426         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3427       }
3428       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3429       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3430       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3431           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3432         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3433                                       LR.getValueType(), LL, RL);
3434         AddToWorklist(ANDNode.getNode());
3435         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3436       }
3437     }
3438     // canonicalize equivalent to ll == rl
3439     if (LL == RR && LR == RL) {
3440       Op1 = ISD::getSetCCSwappedOperands(Op1);
3441       std::swap(RL, RR);
3442     }
3443     if (LL == RL && LR == RR) {
3444       bool isInteger = LL.getValueType().isInteger();
3445       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3446       if (Result != ISD::SETCC_INVALID &&
3447           (!LegalOperations ||
3448            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3449             TLI.isOperationLegal(ISD::SETCC,
3450               getSetCCResultType(N0.getValueType())))))
3451         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3452                             LL, LR, Result);
3453     }
3454   }
3455
3456   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3457   if (N0.getOpcode() == N1.getOpcode()) {
3458     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3459     if (Tmp.getNode()) return Tmp;
3460   }
3461
3462   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3463   if (N0.getOpcode() == ISD::AND &&
3464       N1.getOpcode() == ISD::AND &&
3465       N0.getOperand(1).getOpcode() == ISD::Constant &&
3466       N1.getOperand(1).getOpcode() == ISD::Constant &&
3467       // Don't increase # computations.
3468       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3469     // We can only do this xform if we know that bits from X that are set in C2
3470     // but not in C1 are already zero.  Likewise for Y.
3471     const APInt &LHSMask =
3472       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3473     const APInt &RHSMask =
3474       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3475
3476     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3477         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3478       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3479                               N0.getOperand(0), N1.getOperand(0));
3480       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3481                          DAG.getConstant(LHSMask | RHSMask, VT));
3482     }
3483   }
3484
3485   // See if this is some rotate idiom.
3486   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3487     return SDValue(Rot, 0);
3488
3489   // Simplify the operands using demanded-bits information.
3490   if (!VT.isVector() &&
3491       SimplifyDemandedBits(SDValue(N, 0)))
3492     return SDValue(N, 0);
3493
3494   return SDValue();
3495 }
3496
3497 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3498 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3499   if (Op.getOpcode() == ISD::AND) {
3500     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3501       Mask = Op.getOperand(1);
3502       Op = Op.getOperand(0);
3503     } else {
3504       return false;
3505     }
3506   }
3507
3508   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3509     Shift = Op;
3510     return true;
3511   }
3512
3513   return false;
3514 }
3515
3516 // Return true if we can prove that, whenever Neg and Pos are both in the
3517 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3518 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3519 //
3520 //     (or (shift1 X, Neg), (shift2 X, Pos))
3521 //
3522 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3523 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3524 // to consider shift amounts with defined behavior.
3525 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3526   // If OpSize is a power of 2 then:
3527   //
3528   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3529   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3530   //
3531   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3532   // for the stronger condition:
3533   //
3534   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3535   //
3536   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3537   // we can just replace Neg with Neg' for the rest of the function.
3538   //
3539   // In other cases we check for the even stronger condition:
3540   //
3541   //     Neg == OpSize - Pos                                    [B]
3542   //
3543   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3544   // behavior if Pos == 0 (and consequently Neg == OpSize).
3545   //
3546   // We could actually use [A] whenever OpSize is a power of 2, but the
3547   // only extra cases that it would match are those uninteresting ones
3548   // where Neg and Pos are never in range at the same time.  E.g. for
3549   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3550   // as well as (sub 32, Pos), but:
3551   //
3552   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3553   //
3554   // always invokes undefined behavior for 32-bit X.
3555   //
3556   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3557   unsigned MaskLoBits = 0;
3558   if (Neg.getOpcode() == ISD::AND &&
3559       isPowerOf2_64(OpSize) &&
3560       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3561       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3562     Neg = Neg.getOperand(0);
3563     MaskLoBits = Log2_64(OpSize);
3564   }
3565
3566   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3567   if (Neg.getOpcode() != ISD::SUB)
3568     return 0;
3569   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3570   if (!NegC)
3571     return 0;
3572   SDValue NegOp1 = Neg.getOperand(1);
3573
3574   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3575   // Pos'.  The truncation is redundant for the purpose of the equality.
3576   if (MaskLoBits &&
3577       Pos.getOpcode() == ISD::AND &&
3578       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3579       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3580     Pos = Pos.getOperand(0);
3581
3582   // The condition we need is now:
3583   //
3584   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3585   //
3586   // If NegOp1 == Pos then we need:
3587   //
3588   //              OpSize & Mask == NegC & Mask
3589   //
3590   // (because "x & Mask" is a truncation and distributes through subtraction).
3591   APInt Width;
3592   if (Pos == NegOp1)
3593     Width = NegC->getAPIntValue();
3594   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3595   // Then the condition we want to prove becomes:
3596   //
3597   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3598   //
3599   // which, again because "x & Mask" is a truncation, becomes:
3600   //
3601   //                NegC & Mask == (OpSize - PosC) & Mask
3602   //              OpSize & Mask == (NegC + PosC) & Mask
3603   else if (Pos.getOpcode() == ISD::ADD &&
3604            Pos.getOperand(0) == NegOp1 &&
3605            Pos.getOperand(1).getOpcode() == ISD::Constant)
3606     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3607              NegC->getAPIntValue());
3608   else
3609     return false;
3610
3611   // Now we just need to check that OpSize & Mask == Width & Mask.
3612   if (MaskLoBits)
3613     // Opsize & Mask is 0 since Mask is Opsize - 1.
3614     return Width.getLoBits(MaskLoBits) == 0;
3615   return Width == OpSize;
3616 }
3617
3618 // A subroutine of MatchRotate used once we have found an OR of two opposite
3619 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3620 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3621 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3622 // Neg with outer conversions stripped away.
3623 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3624                                        SDValue Neg, SDValue InnerPos,
3625                                        SDValue InnerNeg, unsigned PosOpcode,
3626                                        unsigned NegOpcode, SDLoc DL) {
3627   // fold (or (shl x, (*ext y)),
3628   //          (srl x, (*ext (sub 32, y)))) ->
3629   //   (rotl x, y) or (rotr x, (sub 32, y))
3630   //
3631   // fold (or (shl x, (*ext (sub 32, y))),
3632   //          (srl x, (*ext y))) ->
3633   //   (rotr x, y) or (rotl x, (sub 32, y))
3634   EVT VT = Shifted.getValueType();
3635   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3636     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3637     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3638                        HasPos ? Pos : Neg).getNode();
3639   }
3640
3641   return nullptr;
3642 }
3643
3644 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3645 // idioms for rotate, and if the target supports rotation instructions, generate
3646 // a rot[lr].
3647 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3648   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3649   EVT VT = LHS.getValueType();
3650   if (!TLI.isTypeLegal(VT)) return nullptr;
3651
3652   // The target must have at least one rotate flavor.
3653   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3654   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3655   if (!HasROTL && !HasROTR) return nullptr;
3656
3657   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3658   SDValue LHSShift;   // The shift.
3659   SDValue LHSMask;    // AND value if any.
3660   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3661     return nullptr; // Not part of a rotate.
3662
3663   SDValue RHSShift;   // The shift.
3664   SDValue RHSMask;    // AND value if any.
3665   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3666     return nullptr; // Not part of a rotate.
3667
3668   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3669     return nullptr;   // Not shifting the same value.
3670
3671   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3672     return nullptr;   // Shifts must disagree.
3673
3674   // Canonicalize shl to left side in a shl/srl pair.
3675   if (RHSShift.getOpcode() == ISD::SHL) {
3676     std::swap(LHS, RHS);
3677     std::swap(LHSShift, RHSShift);
3678     std::swap(LHSMask , RHSMask );
3679   }
3680
3681   unsigned OpSizeInBits = VT.getSizeInBits();
3682   SDValue LHSShiftArg = LHSShift.getOperand(0);
3683   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3684   SDValue RHSShiftArg = RHSShift.getOperand(0);
3685   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3686
3687   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3688   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3689   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3690       RHSShiftAmt.getOpcode() == ISD::Constant) {
3691     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3692     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3693     if ((LShVal + RShVal) != OpSizeInBits)
3694       return nullptr;
3695
3696     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3697                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3698
3699     // If there is an AND of either shifted operand, apply it to the result.
3700     if (LHSMask.getNode() || RHSMask.getNode()) {
3701       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3702
3703       if (LHSMask.getNode()) {
3704         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3705         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3706       }
3707       if (RHSMask.getNode()) {
3708         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3709         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3710       }
3711
3712       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3713     }
3714
3715     return Rot.getNode();
3716   }
3717
3718   // If there is a mask here, and we have a variable shift, we can't be sure
3719   // that we're masking out the right stuff.
3720   if (LHSMask.getNode() || RHSMask.getNode())
3721     return nullptr;
3722
3723   // If the shift amount is sign/zext/any-extended just peel it off.
3724   SDValue LExtOp0 = LHSShiftAmt;
3725   SDValue RExtOp0 = RHSShiftAmt;
3726   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3727        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3728        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3729        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3730       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3731        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3732        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3733        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3734     LExtOp0 = LHSShiftAmt.getOperand(0);
3735     RExtOp0 = RHSShiftAmt.getOperand(0);
3736   }
3737
3738   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3739                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3740   if (TryL)
3741     return TryL;
3742
3743   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3744                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3745   if (TryR)
3746     return TryR;
3747
3748   return nullptr;
3749 }
3750
3751 SDValue DAGCombiner::visitXOR(SDNode *N) {
3752   SDValue N0 = N->getOperand(0);
3753   SDValue N1 = N->getOperand(1);
3754   SDValue LHS, RHS, CC;
3755   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3756   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3757   EVT VT = N0.getValueType();
3758
3759   // fold vector ops
3760   if (VT.isVector()) {
3761     SDValue FoldedVOp = SimplifyVBinOp(N);
3762     if (FoldedVOp.getNode()) return FoldedVOp;
3763
3764     // fold (xor x, 0) -> x, vector edition
3765     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3766       return N1;
3767     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3768       return N0;
3769   }
3770
3771   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3772   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3773     return DAG.getConstant(0, VT);
3774   // fold (xor x, undef) -> undef
3775   if (N0.getOpcode() == ISD::UNDEF)
3776     return N0;
3777   if (N1.getOpcode() == ISD::UNDEF)
3778     return N1;
3779   // fold (xor c1, c2) -> c1^c2
3780   if (N0C && N1C)
3781     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3782   // canonicalize constant to RHS
3783   if (N0C && !N1C)
3784     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3785   // fold (xor x, 0) -> x
3786   if (N1C && N1C->isNullValue())
3787     return N0;
3788   // reassociate xor
3789   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3790   if (RXOR.getNode())
3791     return RXOR;
3792
3793   // fold !(x cc y) -> (x !cc y)
3794   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3795     bool isInt = LHS.getValueType().isInteger();
3796     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3797                                                isInt);
3798
3799     if (!LegalOperations ||
3800         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3801       switch (N0.getOpcode()) {
3802       default:
3803         llvm_unreachable("Unhandled SetCC Equivalent!");
3804       case ISD::SETCC:
3805         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3806       case ISD::SELECT_CC:
3807         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3808                                N0.getOperand(3), NotCC);
3809       }
3810     }
3811   }
3812
3813   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3814   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3815       N0.getNode()->hasOneUse() &&
3816       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3817     SDValue V = N0.getOperand(0);
3818     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3819                     DAG.getConstant(1, V.getValueType()));
3820     AddToWorklist(V.getNode());
3821     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3822   }
3823
3824   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3825   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3826       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3827     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3828     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3829       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3830       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3831       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3832       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3833       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3834     }
3835   }
3836   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3837   if (N1C && N1C->isAllOnesValue() &&
3838       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3839     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3840     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3841       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3842       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3843       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3844       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3845       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3846     }
3847   }
3848   // fold (xor (and x, y), y) -> (and (not x), y)
3849   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3850       N0->getOperand(1) == N1) {
3851     SDValue X = N0->getOperand(0);
3852     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3853     AddToWorklist(NotX.getNode());
3854     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3855   }
3856   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3857   if (N1C && N0.getOpcode() == ISD::XOR) {
3858     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3859     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3860     if (N00C)
3861       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3862                          DAG.getConstant(N1C->getAPIntValue() ^
3863                                          N00C->getAPIntValue(), VT));
3864     if (N01C)
3865       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3866                          DAG.getConstant(N1C->getAPIntValue() ^
3867                                          N01C->getAPIntValue(), VT));
3868   }
3869   // fold (xor x, x) -> 0
3870   if (N0 == N1)
3871     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3872
3873   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3874   if (N0.getOpcode() == N1.getOpcode()) {
3875     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3876     if (Tmp.getNode()) return Tmp;
3877   }
3878
3879   // Simplify the expression using non-local knowledge.
3880   if (!VT.isVector() &&
3881       SimplifyDemandedBits(SDValue(N, 0)))
3882     return SDValue(N, 0);
3883
3884   return SDValue();
3885 }
3886
3887 /// Handle transforms common to the three shifts, when the shift amount is a
3888 /// constant.
3889 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3890   // We can't and shouldn't fold opaque constants.
3891   if (Amt->isOpaque())
3892     return SDValue();
3893
3894   SDNode *LHS = N->getOperand(0).getNode();
3895   if (!LHS->hasOneUse()) return SDValue();
3896
3897   // We want to pull some binops through shifts, so that we have (and (shift))
3898   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3899   // thing happens with address calculations, so it's important to canonicalize
3900   // it.
3901   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3902
3903   switch (LHS->getOpcode()) {
3904   default: return SDValue();
3905   case ISD::OR:
3906   case ISD::XOR:
3907     HighBitSet = false; // We can only transform sra if the high bit is clear.
3908     break;
3909   case ISD::AND:
3910     HighBitSet = true;  // We can only transform sra if the high bit is set.
3911     break;
3912   case ISD::ADD:
3913     if (N->getOpcode() != ISD::SHL)
3914       return SDValue(); // only shl(add) not sr[al](add).
3915     HighBitSet = false; // We can only transform sra if the high bit is clear.
3916     break;
3917   }
3918
3919   // We require the RHS of the binop to be a constant and not opaque as well.
3920   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3921   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3922
3923   // FIXME: disable this unless the input to the binop is a shift by a constant.
3924   // If it is not a shift, it pessimizes some common cases like:
3925   //
3926   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3927   //    int bar(int *X, int i) { return X[i & 255]; }
3928   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3929   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3930        BinOpLHSVal->getOpcode() != ISD::SRA &&
3931        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3932       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3933     return SDValue();
3934
3935   EVT VT = N->getValueType(0);
3936
3937   // If this is a signed shift right, and the high bit is modified by the
3938   // logical operation, do not perform the transformation. The highBitSet
3939   // boolean indicates the value of the high bit of the constant which would
3940   // cause it to be modified for this operation.
3941   if (N->getOpcode() == ISD::SRA) {
3942     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3943     if (BinOpRHSSignSet != HighBitSet)
3944       return SDValue();
3945   }
3946
3947   if (!TLI.isDesirableToCommuteWithShift(LHS))
3948     return SDValue();
3949
3950   // Fold the constants, shifting the binop RHS by the shift amount.
3951   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3952                                N->getValueType(0),
3953                                LHS->getOperand(1), N->getOperand(1));
3954   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3955
3956   // Create the new shift.
3957   SDValue NewShift = DAG.getNode(N->getOpcode(),
3958                                  SDLoc(LHS->getOperand(0)),
3959                                  VT, LHS->getOperand(0), N->getOperand(1));
3960
3961   // Create the new binop.
3962   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3963 }
3964
3965 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3966   assert(N->getOpcode() == ISD::TRUNCATE);
3967   assert(N->getOperand(0).getOpcode() == ISD::AND);
3968
3969   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3970   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3971     SDValue N01 = N->getOperand(0).getOperand(1);
3972
3973     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3974       EVT TruncVT = N->getValueType(0);
3975       SDValue N00 = N->getOperand(0).getOperand(0);
3976       APInt TruncC = N01C->getAPIntValue();
3977       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3978
3979       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3980                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3981                          DAG.getConstant(TruncC, TruncVT));
3982     }
3983   }
3984
3985   return SDValue();
3986 }
3987
3988 SDValue DAGCombiner::visitRotate(SDNode *N) {
3989   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3990   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3991       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3992     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3993     if (NewOp1.getNode())
3994       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3995                          N->getOperand(0), NewOp1);
3996   }
3997   return SDValue();
3998 }
3999
4000 SDValue DAGCombiner::visitSHL(SDNode *N) {
4001   SDValue N0 = N->getOperand(0);
4002   SDValue N1 = N->getOperand(1);
4003   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4004   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4005   EVT VT = N0.getValueType();
4006   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4007
4008   // fold vector ops
4009   if (VT.isVector()) {
4010     SDValue FoldedVOp = SimplifyVBinOp(N);
4011     if (FoldedVOp.getNode()) return FoldedVOp;
4012
4013     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4014     // If setcc produces all-one true value then:
4015     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4016     if (N1CV && N1CV->isConstant()) {
4017       if (N0.getOpcode() == ISD::AND) {
4018         SDValue N00 = N0->getOperand(0);
4019         SDValue N01 = N0->getOperand(1);
4020         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4021
4022         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4023             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4024                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4025           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4026           if (C.getNode())
4027             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4028         }
4029       } else {
4030         N1C = isConstOrConstSplat(N1);
4031       }
4032     }
4033   }
4034
4035   // fold (shl c1, c2) -> c1<<c2
4036   if (N0C && N1C)
4037     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4038   // fold (shl 0, x) -> 0
4039   if (N0C && N0C->isNullValue())
4040     return N0;
4041   // fold (shl x, c >= size(x)) -> undef
4042   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4043     return DAG.getUNDEF(VT);
4044   // fold (shl x, 0) -> x
4045   if (N1C && N1C->isNullValue())
4046     return N0;
4047   // fold (shl undef, x) -> 0
4048   if (N0.getOpcode() == ISD::UNDEF)
4049     return DAG.getConstant(0, VT);
4050   // if (shl x, c) is known to be zero, return 0
4051   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4052                             APInt::getAllOnesValue(OpSizeInBits)))
4053     return DAG.getConstant(0, VT);
4054   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4055   if (N1.getOpcode() == ISD::TRUNCATE &&
4056       N1.getOperand(0).getOpcode() == ISD::AND) {
4057     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4058     if (NewOp1.getNode())
4059       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4060   }
4061
4062   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4063     return SDValue(N, 0);
4064
4065   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4066   if (N1C && N0.getOpcode() == ISD::SHL) {
4067     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4068       uint64_t c1 = N0C1->getZExtValue();
4069       uint64_t c2 = N1C->getZExtValue();
4070       if (c1 + c2 >= OpSizeInBits)
4071         return DAG.getConstant(0, VT);
4072       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4073                          DAG.getConstant(c1 + c2, N1.getValueType()));
4074     }
4075   }
4076
4077   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4078   // For this to be valid, the second form must not preserve any of the bits
4079   // that are shifted out by the inner shift in the first form.  This means
4080   // the outer shift size must be >= the number of bits added by the ext.
4081   // As a corollary, we don't care what kind of ext it is.
4082   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4083               N0.getOpcode() == ISD::ANY_EXTEND ||
4084               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4085       N0.getOperand(0).getOpcode() == ISD::SHL) {
4086     SDValue N0Op0 = N0.getOperand(0);
4087     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4088       uint64_t c1 = N0Op0C1->getZExtValue();
4089       uint64_t c2 = N1C->getZExtValue();
4090       EVT InnerShiftVT = N0Op0.getValueType();
4091       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4092       if (c2 >= OpSizeInBits - InnerShiftSize) {
4093         if (c1 + c2 >= OpSizeInBits)
4094           return DAG.getConstant(0, VT);
4095         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4096                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4097                                        N0Op0->getOperand(0)),
4098                            DAG.getConstant(c1 + c2, N1.getValueType()));
4099       }
4100     }
4101   }
4102
4103   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4104   // Only fold this if the inner zext has no other uses to avoid increasing
4105   // the total number of instructions.
4106   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4107       N0.getOperand(0).getOpcode() == ISD::SRL) {
4108     SDValue N0Op0 = N0.getOperand(0);
4109     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4110       uint64_t c1 = N0Op0C1->getZExtValue();
4111       if (c1 < VT.getScalarSizeInBits()) {
4112         uint64_t c2 = N1C->getZExtValue();
4113         if (c1 == c2) {
4114           SDValue NewOp0 = N0.getOperand(0);
4115           EVT CountVT = NewOp0.getOperand(1).getValueType();
4116           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4117                                        NewOp0, DAG.getConstant(c2, CountVT));
4118           AddToWorklist(NewSHL.getNode());
4119           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4120         }
4121       }
4122     }
4123   }
4124
4125   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4126   //                               (and (srl x, (sub c1, c2), MASK)
4127   // Only fold this if the inner shift has no other uses -- if it does, folding
4128   // this will increase the total number of instructions.
4129   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4130     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4131       uint64_t c1 = N0C1->getZExtValue();
4132       if (c1 < OpSizeInBits) {
4133         uint64_t c2 = N1C->getZExtValue();
4134         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4135         SDValue Shift;
4136         if (c2 > c1) {
4137           Mask = Mask.shl(c2 - c1);
4138           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4139                               DAG.getConstant(c2 - c1, N1.getValueType()));
4140         } else {
4141           Mask = Mask.lshr(c1 - c2);
4142           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4143                               DAG.getConstant(c1 - c2, N1.getValueType()));
4144         }
4145         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4146                            DAG.getConstant(Mask, VT));
4147       }
4148     }
4149   }
4150   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4151   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4152     unsigned BitSize = VT.getScalarSizeInBits();
4153     SDValue HiBitsMask =
4154       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4155                                             BitSize - N1C->getZExtValue()), VT);
4156     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4157                        HiBitsMask);
4158   }
4159
4160   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4161   // Variant of version done on multiply, except mul by a power of 2 is turned
4162   // into a shift.
4163   APInt Val;
4164   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4165       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4166        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4167     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4168     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4169     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4170   }
4171
4172   if (N1C) {
4173     SDValue NewSHL = visitShiftByConstant(N, N1C);
4174     if (NewSHL.getNode())
4175       return NewSHL;
4176   }
4177
4178   return SDValue();
4179 }
4180
4181 SDValue DAGCombiner::visitSRA(SDNode *N) {
4182   SDValue N0 = N->getOperand(0);
4183   SDValue N1 = N->getOperand(1);
4184   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4186   EVT VT = N0.getValueType();
4187   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4188
4189   // fold vector ops
4190   if (VT.isVector()) {
4191     SDValue FoldedVOp = SimplifyVBinOp(N);
4192     if (FoldedVOp.getNode()) return FoldedVOp;
4193
4194     N1C = isConstOrConstSplat(N1);
4195   }
4196
4197   // fold (sra c1, c2) -> (sra c1, c2)
4198   if (N0C && N1C)
4199     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4200   // fold (sra 0, x) -> 0
4201   if (N0C && N0C->isNullValue())
4202     return N0;
4203   // fold (sra -1, x) -> -1
4204   if (N0C && N0C->isAllOnesValue())
4205     return N0;
4206   // fold (sra x, (setge c, size(x))) -> undef
4207   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4208     return DAG.getUNDEF(VT);
4209   // fold (sra x, 0) -> x
4210   if (N1C && N1C->isNullValue())
4211     return N0;
4212   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4213   // sext_inreg.
4214   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4215     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4216     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4217     if (VT.isVector())
4218       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4219                                ExtVT, VT.getVectorNumElements());
4220     if ((!LegalOperations ||
4221          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4222       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4223                          N0.getOperand(0), DAG.getValueType(ExtVT));
4224   }
4225
4226   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4227   if (N1C && N0.getOpcode() == ISD::SRA) {
4228     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4229       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4230       if (Sum >= OpSizeInBits)
4231         Sum = OpSizeInBits - 1;
4232       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4233                          DAG.getConstant(Sum, N1.getValueType()));
4234     }
4235   }
4236
4237   // fold (sra (shl X, m), (sub result_size, n))
4238   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4239   // result_size - n != m.
4240   // If truncate is free for the target sext(shl) is likely to result in better
4241   // code.
4242   if (N0.getOpcode() == ISD::SHL && N1C) {
4243     // Get the two constanst of the shifts, CN0 = m, CN = n.
4244     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4245     if (N01C) {
4246       LLVMContext &Ctx = *DAG.getContext();
4247       // Determine what the truncate's result bitsize and type would be.
4248       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4249
4250       if (VT.isVector())
4251         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4252
4253       // Determine the residual right-shift amount.
4254       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4255
4256       // If the shift is not a no-op (in which case this should be just a sign
4257       // extend already), the truncated to type is legal, sign_extend is legal
4258       // on that type, and the truncate to that type is both legal and free,
4259       // perform the transform.
4260       if ((ShiftAmt > 0) &&
4261           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4262           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4263           TLI.isTruncateFree(VT, TruncVT)) {
4264
4265           SDValue Amt = DAG.getConstant(ShiftAmt,
4266               getShiftAmountTy(N0.getOperand(0).getValueType()));
4267           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4268                                       N0.getOperand(0), Amt);
4269           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4270                                       Shift);
4271           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4272                              N->getValueType(0), Trunc);
4273       }
4274     }
4275   }
4276
4277   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4278   if (N1.getOpcode() == ISD::TRUNCATE &&
4279       N1.getOperand(0).getOpcode() == ISD::AND) {
4280     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4281     if (NewOp1.getNode())
4282       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4283   }
4284
4285   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4286   //      if c1 is equal to the number of bits the trunc removes
4287   if (N0.getOpcode() == ISD::TRUNCATE &&
4288       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4289        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4290       N0.getOperand(0).hasOneUse() &&
4291       N0.getOperand(0).getOperand(1).hasOneUse() &&
4292       N1C) {
4293     SDValue N0Op0 = N0.getOperand(0);
4294     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4295       unsigned LargeShiftVal = LargeShift->getZExtValue();
4296       EVT LargeVT = N0Op0.getValueType();
4297
4298       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4299         SDValue Amt =
4300           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4301                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4302         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4303                                   N0Op0.getOperand(0), Amt);
4304         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4305       }
4306     }
4307   }
4308
4309   // Simplify, based on bits shifted out of the LHS.
4310   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4311     return SDValue(N, 0);
4312
4313
4314   // If the sign bit is known to be zero, switch this to a SRL.
4315   if (DAG.SignBitIsZero(N0))
4316     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4317
4318   if (N1C) {
4319     SDValue NewSRA = visitShiftByConstant(N, N1C);
4320     if (NewSRA.getNode())
4321       return NewSRA;
4322   }
4323
4324   return SDValue();
4325 }
4326
4327 SDValue DAGCombiner::visitSRL(SDNode *N) {
4328   SDValue N0 = N->getOperand(0);
4329   SDValue N1 = N->getOperand(1);
4330   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4331   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4332   EVT VT = N0.getValueType();
4333   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4334
4335   // fold vector ops
4336   if (VT.isVector()) {
4337     SDValue FoldedVOp = SimplifyVBinOp(N);
4338     if (FoldedVOp.getNode()) return FoldedVOp;
4339
4340     N1C = isConstOrConstSplat(N1);
4341   }
4342
4343   // fold (srl c1, c2) -> c1 >>u c2
4344   if (N0C && N1C)
4345     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4346   // fold (srl 0, x) -> 0
4347   if (N0C && N0C->isNullValue())
4348     return N0;
4349   // fold (srl x, c >= size(x)) -> undef
4350   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4351     return DAG.getUNDEF(VT);
4352   // fold (srl x, 0) -> x
4353   if (N1C && N1C->isNullValue())
4354     return N0;
4355   // if (srl x, c) is known to be zero, return 0
4356   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4357                                    APInt::getAllOnesValue(OpSizeInBits)))
4358     return DAG.getConstant(0, VT);
4359
4360   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4361   if (N1C && N0.getOpcode() == ISD::SRL) {
4362     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4363       uint64_t c1 = N01C->getZExtValue();
4364       uint64_t c2 = N1C->getZExtValue();
4365       if (c1 + c2 >= OpSizeInBits)
4366         return DAG.getConstant(0, VT);
4367       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4368                          DAG.getConstant(c1 + c2, N1.getValueType()));
4369     }
4370   }
4371
4372   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4373   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4374       N0.getOperand(0).getOpcode() == ISD::SRL &&
4375       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4376     uint64_t c1 =
4377       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4378     uint64_t c2 = N1C->getZExtValue();
4379     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4380     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4381     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4382     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4383     if (c1 + OpSizeInBits == InnerShiftSize) {
4384       if (c1 + c2 >= InnerShiftSize)
4385         return DAG.getConstant(0, VT);
4386       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4387                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4388                                      N0.getOperand(0)->getOperand(0),
4389                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4390     }
4391   }
4392
4393   // fold (srl (shl x, c), c) -> (and x, cst2)
4394   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4395     unsigned BitSize = N0.getScalarValueSizeInBits();
4396     if (BitSize <= 64) {
4397       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4398       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4399                          DAG.getConstant(~0ULL >> ShAmt, VT));
4400     }
4401   }
4402
4403   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4404   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4405     // Shifting in all undef bits?
4406     EVT SmallVT = N0.getOperand(0).getValueType();
4407     unsigned BitSize = SmallVT.getScalarSizeInBits();
4408     if (N1C->getZExtValue() >= BitSize)
4409       return DAG.getUNDEF(VT);
4410
4411     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4412       uint64_t ShiftAmt = N1C->getZExtValue();
4413       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4414                                        N0.getOperand(0),
4415                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4416       AddToWorklist(SmallShift.getNode());
4417       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4418       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4419                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4420                          DAG.getConstant(Mask, VT));
4421     }
4422   }
4423
4424   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4425   // bit, which is unmodified by sra.
4426   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4427     if (N0.getOpcode() == ISD::SRA)
4428       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4429   }
4430
4431   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4432   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4433       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4434     APInt KnownZero, KnownOne;
4435     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4436
4437     // If any of the input bits are KnownOne, then the input couldn't be all
4438     // zeros, thus the result of the srl will always be zero.
4439     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4440
4441     // If all of the bits input the to ctlz node are known to be zero, then
4442     // the result of the ctlz is "32" and the result of the shift is one.
4443     APInt UnknownBits = ~KnownZero;
4444     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4445
4446     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4447     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4448       // Okay, we know that only that the single bit specified by UnknownBits
4449       // could be set on input to the CTLZ node. If this bit is set, the SRL
4450       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4451       // to an SRL/XOR pair, which is likely to simplify more.
4452       unsigned ShAmt = UnknownBits.countTrailingZeros();
4453       SDValue Op = N0.getOperand(0);
4454
4455       if (ShAmt) {
4456         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4457                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4458         AddToWorklist(Op.getNode());
4459       }
4460
4461       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4462                          Op, DAG.getConstant(1, VT));
4463     }
4464   }
4465
4466   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4467   if (N1.getOpcode() == ISD::TRUNCATE &&
4468       N1.getOperand(0).getOpcode() == ISD::AND) {
4469     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4470     if (NewOp1.getNode())
4471       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4472   }
4473
4474   // fold operands of srl based on knowledge that the low bits are not
4475   // demanded.
4476   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4477     return SDValue(N, 0);
4478
4479   if (N1C) {
4480     SDValue NewSRL = visitShiftByConstant(N, N1C);
4481     if (NewSRL.getNode())
4482       return NewSRL;
4483   }
4484
4485   // Attempt to convert a srl of a load into a narrower zero-extending load.
4486   SDValue NarrowLoad = ReduceLoadWidth(N);
4487   if (NarrowLoad.getNode())
4488     return NarrowLoad;
4489
4490   // Here is a common situation. We want to optimize:
4491   //
4492   //   %a = ...
4493   //   %b = and i32 %a, 2
4494   //   %c = srl i32 %b, 1
4495   //   brcond i32 %c ...
4496   //
4497   // into
4498   //
4499   //   %a = ...
4500   //   %b = and %a, 2
4501   //   %c = setcc eq %b, 0
4502   //   brcond %c ...
4503   //
4504   // However when after the source operand of SRL is optimized into AND, the SRL
4505   // itself may not be optimized further. Look for it and add the BRCOND into
4506   // the worklist.
4507   if (N->hasOneUse()) {
4508     SDNode *Use = *N->use_begin();
4509     if (Use->getOpcode() == ISD::BRCOND)
4510       AddToWorklist(Use);
4511     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4512       // Also look pass the truncate.
4513       Use = *Use->use_begin();
4514       if (Use->getOpcode() == ISD::BRCOND)
4515         AddToWorklist(Use);
4516     }
4517   }
4518
4519   return SDValue();
4520 }
4521
4522 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4523   SDValue N0 = N->getOperand(0);
4524   EVT VT = N->getValueType(0);
4525
4526   // fold (ctlz c1) -> c2
4527   if (isa<ConstantSDNode>(N0))
4528     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   EVT VT = N->getValueType(0);
4535
4536   // fold (ctlz_zero_undef c1) -> c2
4537   if (isa<ConstantSDNode>(N0))
4538     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4539   return SDValue();
4540 }
4541
4542 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4543   SDValue N0 = N->getOperand(0);
4544   EVT VT = N->getValueType(0);
4545
4546   // fold (cttz c1) -> c2
4547   if (isa<ConstantSDNode>(N0))
4548     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4549   return SDValue();
4550 }
4551
4552 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4553   SDValue N0 = N->getOperand(0);
4554   EVT VT = N->getValueType(0);
4555
4556   // fold (cttz_zero_undef c1) -> c2
4557   if (isa<ConstantSDNode>(N0))
4558     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4559   return SDValue();
4560 }
4561
4562 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4563   SDValue N0 = N->getOperand(0);
4564   EVT VT = N->getValueType(0);
4565
4566   // fold (ctpop c1) -> c2
4567   if (isa<ConstantSDNode>(N0))
4568     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4569   return SDValue();
4570 }
4571
4572 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4573   SDValue N0 = N->getOperand(0);
4574   SDValue N1 = N->getOperand(1);
4575   SDValue N2 = N->getOperand(2);
4576   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4577   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4578   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4579   EVT VT = N->getValueType(0);
4580   EVT VT0 = N0.getValueType();
4581
4582   // fold (select C, X, X) -> X
4583   if (N1 == N2)
4584     return N1;
4585   // fold (select true, X, Y) -> X
4586   if (N0C && !N0C->isNullValue())
4587     return N1;
4588   // fold (select false, X, Y) -> Y
4589   if (N0C && N0C->isNullValue())
4590     return N2;
4591   // fold (select C, 1, X) -> (or C, X)
4592   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4593     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4594   // fold (select C, 0, 1) -> (xor C, 1)
4595   // We can't do this reliably if integer based booleans have different contents
4596   // to floating point based booleans. This is because we can't tell whether we
4597   // have an integer-based boolean or a floating-point-based boolean unless we
4598   // can find the SETCC that produced it and inspect its operands. This is
4599   // fairly easy if C is the SETCC node, but it can potentially be
4600   // undiscoverable (or not reasonably discoverable). For example, it could be
4601   // in another basic block or it could require searching a complicated
4602   // expression.
4603   if (VT.isInteger() &&
4604       (VT0 == MVT::i1 || (VT0.isInteger() &&
4605                           TLI.getBooleanContents(false, false) ==
4606                               TLI.getBooleanContents(false, true) &&
4607                           TLI.getBooleanContents(false, false) ==
4608                               TargetLowering::ZeroOrOneBooleanContent)) &&
4609       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4610     SDValue XORNode;
4611     if (VT == VT0)
4612       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4613                          N0, DAG.getConstant(1, VT0));
4614     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4615                           N0, DAG.getConstant(1, VT0));
4616     AddToWorklist(XORNode.getNode());
4617     if (VT.bitsGT(VT0))
4618       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4619     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4620   }
4621   // fold (select C, 0, X) -> (and (not C), X)
4622   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4623     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4624     AddToWorklist(NOTNode.getNode());
4625     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4626   }
4627   // fold (select C, X, 1) -> (or (not C), X)
4628   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4629     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4630     AddToWorklist(NOTNode.getNode());
4631     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4632   }
4633   // fold (select C, X, 0) -> (and C, X)
4634   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4635     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4636   // fold (select X, X, Y) -> (or X, Y)
4637   // fold (select X, 1, Y) -> (or X, Y)
4638   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4639     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4640   // fold (select X, Y, X) -> (and X, Y)
4641   // fold (select X, Y, 0) -> (and X, Y)
4642   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4643     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4644
4645   // If we can fold this based on the true/false value, do so.
4646   if (SimplifySelectOps(N, N1, N2))
4647     return SDValue(N, 0);  // Don't revisit N.
4648
4649   // fold selects based on a setcc into other things, such as min/max/abs
4650   if (N0.getOpcode() == ISD::SETCC) {
4651     if ((!LegalOperations &&
4652          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4653         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4654       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4655                          N0.getOperand(0), N0.getOperand(1),
4656                          N1, N2, N0.getOperand(2));
4657     return SimplifySelect(SDLoc(N), N0, N1, N2);
4658   }
4659
4660   return SDValue();
4661 }
4662
4663 static
4664 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4665   SDLoc DL(N);
4666   EVT LoVT, HiVT;
4667   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4668
4669   // Split the inputs.
4670   SDValue Lo, Hi, LL, LH, RL, RH;
4671   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4672   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4673
4674   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4675   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4676
4677   return std::make_pair(Lo, Hi);
4678 }
4679
4680 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4681 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4682 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4683   SDLoc dl(N);
4684   SDValue Cond = N->getOperand(0);
4685   SDValue LHS = N->getOperand(1);
4686   SDValue RHS = N->getOperand(2);
4687   EVT VT = N->getValueType(0);
4688   int NumElems = VT.getVectorNumElements();
4689   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4690          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4691          Cond.getOpcode() == ISD::BUILD_VECTOR);
4692
4693   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4694   // binary ones here.
4695   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4696     return SDValue();
4697
4698   // We're sure we have an even number of elements due to the
4699   // concat_vectors we have as arguments to vselect.
4700   // Skip BV elements until we find one that's not an UNDEF
4701   // After we find an UNDEF element, keep looping until we get to half the
4702   // length of the BV and see if all the non-undef nodes are the same.
4703   ConstantSDNode *BottomHalf = nullptr;
4704   for (int i = 0; i < NumElems / 2; ++i) {
4705     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4706       continue;
4707
4708     if (BottomHalf == nullptr)
4709       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4710     else if (Cond->getOperand(i).getNode() != BottomHalf)
4711       return SDValue();
4712   }
4713
4714   // Do the same for the second half of the BuildVector
4715   ConstantSDNode *TopHalf = nullptr;
4716   for (int i = NumElems / 2; i < NumElems; ++i) {
4717     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4718       continue;
4719
4720     if (TopHalf == nullptr)
4721       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4722     else if (Cond->getOperand(i).getNode() != TopHalf)
4723       return SDValue();
4724   }
4725
4726   assert(TopHalf && BottomHalf &&
4727          "One half of the selector was all UNDEFs and the other was all the "
4728          "same value. This should have been addressed before this function.");
4729   return DAG.getNode(
4730       ISD::CONCAT_VECTORS, dl, VT,
4731       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4732       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4733 }
4734
4735 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4736   SDValue N0 = N->getOperand(0);
4737   SDValue N1 = N->getOperand(1);
4738   SDValue N2 = N->getOperand(2);
4739   SDLoc DL(N);
4740
4741   // Canonicalize integer abs.
4742   // vselect (setg[te] X,  0),  X, -X ->
4743   // vselect (setgt    X, -1),  X, -X ->
4744   // vselect (setl[te] X,  0), -X,  X ->
4745   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4746   if (N0.getOpcode() == ISD::SETCC) {
4747     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4748     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4749     bool isAbs = false;
4750     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4751
4752     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4753          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4754         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4755       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4756     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4757              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4758       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4759
4760     if (isAbs) {
4761       EVT VT = LHS.getValueType();
4762       SDValue Shift = DAG.getNode(
4763           ISD::SRA, DL, VT, LHS,
4764           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4765       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4766       AddToWorklist(Shift.getNode());
4767       AddToWorklist(Add.getNode());
4768       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4769     }
4770   }
4771
4772   // If the VSELECT result requires splitting and the mask is provided by a
4773   // SETCC, then split both nodes and its operands before legalization. This
4774   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4775   // and enables future optimizations (e.g. min/max pattern matching on X86).
4776   if (N0.getOpcode() == ISD::SETCC) {
4777     EVT VT = N->getValueType(0);
4778
4779     // Check if any splitting is required.
4780     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4781         TargetLowering::TypeSplitVector)
4782       return SDValue();
4783
4784     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4785     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4786     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4787     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4788
4789     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4790     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4791
4792     // Add the new VSELECT nodes to the work list in case they need to be split
4793     // again.
4794     AddToWorklist(Lo.getNode());
4795     AddToWorklist(Hi.getNode());
4796
4797     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4798   }
4799
4800   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4801   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4802     return N1;
4803   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4804   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4805     return N2;
4806
4807   // The ConvertSelectToConcatVector function is assuming both the above
4808   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4809   // and addressed.
4810   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4811       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4812       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4813     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4814     if (CV.getNode())
4815       return CV;
4816   }
4817
4818   return SDValue();
4819 }
4820
4821 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4822   SDValue N0 = N->getOperand(0);
4823   SDValue N1 = N->getOperand(1);
4824   SDValue N2 = N->getOperand(2);
4825   SDValue N3 = N->getOperand(3);
4826   SDValue N4 = N->getOperand(4);
4827   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4828
4829   // fold select_cc lhs, rhs, x, x, cc -> x
4830   if (N2 == N3)
4831     return N2;
4832
4833   // Determine if the condition we're dealing with is constant
4834   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4835                               N0, N1, CC, SDLoc(N), false);
4836   if (SCC.getNode()) {
4837     AddToWorklist(SCC.getNode());
4838
4839     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4840       if (!SCCC->isNullValue())
4841         return N2;    // cond always true -> true val
4842       else
4843         return N3;    // cond always false -> false val
4844     }
4845
4846     // Fold to a simpler select_cc
4847     if (SCC.getOpcode() == ISD::SETCC)
4848       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4849                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4850                          SCC.getOperand(2));
4851   }
4852
4853   // If we can fold this based on the true/false value, do so.
4854   if (SimplifySelectOps(N, N2, N3))
4855     return SDValue(N, 0);  // Don't revisit N.
4856
4857   // fold select_cc into other things, such as min/max/abs
4858   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4859 }
4860
4861 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4862   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4863                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4864                        SDLoc(N));
4865 }
4866
4867 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4868 // dag node into a ConstantSDNode or a build_vector of constants.
4869 // This function is called by the DAGCombiner when visiting sext/zext/aext
4870 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4871 // Vector extends are not folded if operations are legal; this is to
4872 // avoid introducing illegal build_vector dag nodes.
4873 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4874                                          SelectionDAG &DAG, bool LegalTypes,
4875                                          bool LegalOperations) {
4876   unsigned Opcode = N->getOpcode();
4877   SDValue N0 = N->getOperand(0);
4878   EVT VT = N->getValueType(0);
4879
4880   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4881          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4882
4883   // fold (sext c1) -> c1
4884   // fold (zext c1) -> c1
4885   // fold (aext c1) -> c1
4886   if (isa<ConstantSDNode>(N0))
4887     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4888
4889   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4890   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4891   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4892   EVT SVT = VT.getScalarType();
4893   if (!(VT.isVector() &&
4894       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4895       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4896     return nullptr;
4897
4898   // We can fold this node into a build_vector.
4899   unsigned VTBits = SVT.getSizeInBits();
4900   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4901   unsigned ShAmt = VTBits - EVTBits;
4902   SmallVector<SDValue, 8> Elts;
4903   unsigned NumElts = N0->getNumOperands();
4904   SDLoc DL(N);
4905
4906   for (unsigned i=0; i != NumElts; ++i) {
4907     SDValue Op = N0->getOperand(i);
4908     if (Op->getOpcode() == ISD::UNDEF) {
4909       Elts.push_back(DAG.getUNDEF(SVT));
4910       continue;
4911     }
4912
4913     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4914     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4915     if (Opcode == ISD::SIGN_EXTEND)
4916       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4917                                      SVT));
4918     else
4919       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4920                                      SVT));
4921   }
4922
4923   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4924 }
4925
4926 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4927 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4928 // transformation. Returns true if extension are possible and the above
4929 // mentioned transformation is profitable.
4930 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4931                                     unsigned ExtOpc,
4932                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4933                                     const TargetLowering &TLI) {
4934   bool HasCopyToRegUses = false;
4935   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4936   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4937                             UE = N0.getNode()->use_end();
4938        UI != UE; ++UI) {
4939     SDNode *User = *UI;
4940     if (User == N)
4941       continue;
4942     if (UI.getUse().getResNo() != N0.getResNo())
4943       continue;
4944     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4945     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4946       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4947       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4948         // Sign bits will be lost after a zext.
4949         return false;
4950       bool Add = false;
4951       for (unsigned i = 0; i != 2; ++i) {
4952         SDValue UseOp = User->getOperand(i);
4953         if (UseOp == N0)
4954           continue;
4955         if (!isa<ConstantSDNode>(UseOp))
4956           return false;
4957         Add = true;
4958       }
4959       if (Add)
4960         ExtendNodes.push_back(User);
4961       continue;
4962     }
4963     // If truncates aren't free and there are users we can't
4964     // extend, it isn't worthwhile.
4965     if (!isTruncFree)
4966       return false;
4967     // Remember if this value is live-out.
4968     if (User->getOpcode() == ISD::CopyToReg)
4969       HasCopyToRegUses = true;
4970   }
4971
4972   if (HasCopyToRegUses) {
4973     bool BothLiveOut = false;
4974     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4975          UI != UE; ++UI) {
4976       SDUse &Use = UI.getUse();
4977       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4978         BothLiveOut = true;
4979         break;
4980       }
4981     }
4982     if (BothLiveOut)
4983       // Both unextended and extended values are live out. There had better be
4984       // a good reason for the transformation.
4985       return ExtendNodes.size();
4986   }
4987   return true;
4988 }
4989
4990 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4991                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4992                                   ISD::NodeType ExtType) {
4993   // Extend SetCC uses if necessary.
4994   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4995     SDNode *SetCC = SetCCs[i];
4996     SmallVector<SDValue, 4> Ops;
4997
4998     for (unsigned j = 0; j != 2; ++j) {
4999       SDValue SOp = SetCC->getOperand(j);
5000       if (SOp == Trunc)
5001         Ops.push_back(ExtLoad);
5002       else
5003         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5004     }
5005
5006     Ops.push_back(SetCC->getOperand(2));
5007     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5008   }
5009 }
5010
5011 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5012   SDValue N0 = N->getOperand(0);
5013   EVT VT = N->getValueType(0);
5014
5015   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5016                                               LegalOperations))
5017     return SDValue(Res, 0);
5018
5019   // fold (sext (sext x)) -> (sext x)
5020   // fold (sext (aext x)) -> (sext x)
5021   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5022     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5023                        N0.getOperand(0));
5024
5025   if (N0.getOpcode() == ISD::TRUNCATE) {
5026     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5027     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5028     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5029     if (NarrowLoad.getNode()) {
5030       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5031       if (NarrowLoad.getNode() != N0.getNode()) {
5032         CombineTo(N0.getNode(), NarrowLoad);
5033         // CombineTo deleted the truncate, if needed, but not what's under it.
5034         AddToWorklist(oye);
5035       }
5036       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5037     }
5038
5039     // See if the value being truncated is already sign extended.  If so, just
5040     // eliminate the trunc/sext pair.
5041     SDValue Op = N0.getOperand(0);
5042     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5043     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5044     unsigned DestBits = VT.getScalarType().getSizeInBits();
5045     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5046
5047     if (OpBits == DestBits) {
5048       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5049       // bits, it is already ready.
5050       if (NumSignBits > DestBits-MidBits)
5051         return Op;
5052     } else if (OpBits < DestBits) {
5053       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5054       // bits, just sext from i32.
5055       if (NumSignBits > OpBits-MidBits)
5056         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5057     } else {
5058       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5059       // bits, just truncate to i32.
5060       if (NumSignBits > OpBits-MidBits)
5061         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5062     }
5063
5064     // fold (sext (truncate x)) -> (sextinreg x).
5065     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5066                                                  N0.getValueType())) {
5067       if (OpBits < DestBits)
5068         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5069       else if (OpBits > DestBits)
5070         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5071       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5072                          DAG.getValueType(N0.getValueType()));
5073     }
5074   }
5075
5076   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5077   // None of the supported targets knows how to perform load and sign extend
5078   // on vectors in one instruction.  We only perform this transformation on
5079   // scalars.
5080   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5081       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5082       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5083        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5084     bool DoXform = true;
5085     SmallVector<SDNode*, 4> SetCCs;
5086     if (!N0.hasOneUse())
5087       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5088     if (DoXform) {
5089       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5090       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5091                                        LN0->getChain(),
5092                                        LN0->getBasePtr(), N0.getValueType(),
5093                                        LN0->getMemOperand());
5094       CombineTo(N, ExtLoad);
5095       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5096                                   N0.getValueType(), ExtLoad);
5097       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5098       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5099                       ISD::SIGN_EXTEND);
5100       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5101     }
5102   }
5103
5104   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5105   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5106   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5107       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5108     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5109     EVT MemVT = LN0->getMemoryVT();
5110     if ((!LegalOperations && !LN0->isVolatile()) ||
5111         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5112       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5113                                        LN0->getChain(),
5114                                        LN0->getBasePtr(), MemVT,
5115                                        LN0->getMemOperand());
5116       CombineTo(N, ExtLoad);
5117       CombineTo(N0.getNode(),
5118                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5119                             N0.getValueType(), ExtLoad),
5120                 ExtLoad.getValue(1));
5121       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5122     }
5123   }
5124
5125   // fold (sext (and/or/xor (load x), cst)) ->
5126   //      (and/or/xor (sextload x), (sext cst))
5127   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5128        N0.getOpcode() == ISD::XOR) &&
5129       isa<LoadSDNode>(N0.getOperand(0)) &&
5130       N0.getOperand(1).getOpcode() == ISD::Constant &&
5131       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5132       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5133     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5134     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5135       bool DoXform = true;
5136       SmallVector<SDNode*, 4> SetCCs;
5137       if (!N0.hasOneUse())
5138         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5139                                           SetCCs, TLI);
5140       if (DoXform) {
5141         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5142                                          LN0->getChain(), LN0->getBasePtr(),
5143                                          LN0->getMemoryVT(),
5144                                          LN0->getMemOperand());
5145         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5146         Mask = Mask.sext(VT.getSizeInBits());
5147         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5148                                   ExtLoad, DAG.getConstant(Mask, VT));
5149         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5150                                     SDLoc(N0.getOperand(0)),
5151                                     N0.getOperand(0).getValueType(), ExtLoad);
5152         CombineTo(N, And);
5153         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5154         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5155                         ISD::SIGN_EXTEND);
5156         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5157       }
5158     }
5159   }
5160
5161   if (N0.getOpcode() == ISD::SETCC) {
5162     EVT N0VT = N0.getOperand(0).getValueType();
5163     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5164     // Only do this before legalize for now.
5165     if (VT.isVector() && !LegalOperations &&
5166         TLI.getBooleanContents(N0VT) ==
5167             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5168       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5169       // of the same size as the compared operands. Only optimize sext(setcc())
5170       // if this is the case.
5171       EVT SVT = getSetCCResultType(N0VT);
5172
5173       // We know that the # elements of the results is the same as the
5174       // # elements of the compare (and the # elements of the compare result
5175       // for that matter).  Check to see that they are the same size.  If so,
5176       // we know that the element size of the sext'd result matches the
5177       // element size of the compare operands.
5178       if (VT.getSizeInBits() == SVT.getSizeInBits())
5179         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5180                              N0.getOperand(1),
5181                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5182
5183       // If the desired elements are smaller or larger than the source
5184       // elements we can use a matching integer vector type and then
5185       // truncate/sign extend
5186       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5187       if (SVT == MatchingVectorType) {
5188         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5189                                N0.getOperand(0), N0.getOperand(1),
5190                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5191         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5192       }
5193     }
5194
5195     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5196     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5197     SDValue NegOne =
5198       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5199     SDValue SCC =
5200       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5201                        NegOne, DAG.getConstant(0, VT),
5202                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5203     if (SCC.getNode()) return SCC;
5204
5205     if (!VT.isVector()) {
5206       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5207       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5208         SDLoc DL(N);
5209         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5210         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5211                                      N0.getOperand(0), N0.getOperand(1), CC);
5212         return DAG.getSelect(DL, VT, SetCC,
5213                              NegOne, DAG.getConstant(0, VT));
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       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6681       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6682
6683     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6684     if (N0.getOpcode() == ISD::FMUL &&
6685         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6686       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6687                          N0.getOperand(0), N0.getOperand(1), N1);
6688
6689     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6690     // Note: Commutes FADD operands.
6691     if (N1.getOpcode() == ISD::FMUL &&
6692         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6693       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6694                          N1.getOperand(0), N1.getOperand(1), N0);
6695   }
6696
6697   return SDValue();
6698 }
6699
6700 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6701   SDValue N0 = N->getOperand(0);
6702   SDValue N1 = N->getOperand(1);
6703   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6704   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6705   EVT VT = N->getValueType(0);
6706   SDLoc dl(N);
6707   const TargetOptions &Options = DAG.getTarget().Options;
6708
6709   // fold vector ops
6710   if (VT.isVector()) {
6711     SDValue FoldedVOp = SimplifyVBinOp(N);
6712     if (FoldedVOp.getNode()) return FoldedVOp;
6713   }
6714
6715   // fold (fsub c1, c2) -> c1-c2
6716   if (N0CFP && N1CFP)
6717     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6718
6719   // fold (fsub A, (fneg B)) -> (fadd A, B)
6720   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6721     return DAG.getNode(ISD::FADD, dl, VT, N0,
6722                        GetNegatedExpression(N1, DAG, LegalOperations));
6723
6724   // If 'unsafe math' is enabled, fold lots of things.
6725   if (Options.UnsafeFPMath) {
6726     // (fsub A, 0) -> A
6727     if (N1CFP && N1CFP->getValueAPF().isZero())
6728       return N0;
6729
6730     // (fsub 0, B) -> -B
6731     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6732       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6733         return GetNegatedExpression(N1, DAG, LegalOperations);
6734       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6735         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6736     }
6737
6738     // (fsub x, x) -> 0.0
6739     if (N0 == N1)
6740       return DAG.getConstantFP(0.0f, VT);
6741
6742     // (fsub x, (fadd x, y)) -> (fneg y)
6743     // (fsub x, (fadd y, x)) -> (fneg y)
6744     if (N1.getOpcode() == ISD::FADD) {
6745       SDValue N10 = N1->getOperand(0);
6746       SDValue N11 = N1->getOperand(1);
6747
6748       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6749         return GetNegatedExpression(N11, DAG, LegalOperations);
6750
6751       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6752         return GetNegatedExpression(N10, DAG, LegalOperations);
6753     }
6754   }
6755
6756   // FSUB -> FMA combines:
6757   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6758       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6759       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6760
6761     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6762     if (N0.getOpcode() == ISD::FMUL &&
6763         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6764       return DAG.getNode(ISD::FMA, dl, VT,
6765                          N0.getOperand(0), N0.getOperand(1),
6766                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6767
6768     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6769     // Note: Commutes FSUB operands.
6770     if (N1.getOpcode() == ISD::FMUL &&
6771         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6772       return DAG.getNode(ISD::FMA, dl, VT,
6773                          DAG.getNode(ISD::FNEG, dl, VT,
6774                          N1.getOperand(0)),
6775                          N1.getOperand(1), N0);
6776
6777     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6778     if (N0.getOpcode() == ISD::FNEG &&
6779         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6780         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6781             TLI.enableAggressiveFMAFusion(VT))) {
6782       SDValue N00 = N0.getOperand(0).getOperand(0);
6783       SDValue N01 = N0.getOperand(0).getOperand(1);
6784       return DAG.getNode(ISD::FMA, dl, VT,
6785                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6786                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6787     }
6788   }
6789
6790   return SDValue();
6791 }
6792
6793 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6794   SDValue N0 = N->getOperand(0);
6795   SDValue N1 = N->getOperand(1);
6796   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6797   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6798   EVT VT = N->getValueType(0);
6799   const TargetOptions &Options = DAG.getTarget().Options;
6800
6801   // fold vector ops
6802   if (VT.isVector()) {
6803     // This just handles C1 * C2 for vectors. Other vector folds are below.
6804     SDValue FoldedVOp = SimplifyVBinOp(N);
6805     if (FoldedVOp.getNode())
6806       return FoldedVOp;
6807     // Canonicalize vector constant to RHS.
6808     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6809         N1.getOpcode() != ISD::BUILD_VECTOR)
6810       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6811         if (BV0->isConstant())
6812           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6813   }
6814
6815   // fold (fmul c1, c2) -> c1*c2
6816   if (N0CFP && N1CFP)
6817     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6818
6819   // canonicalize constant to RHS
6820   if (N0CFP && !N1CFP)
6821     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6822
6823   // fold (fmul A, 1.0) -> A
6824   if (N1CFP && N1CFP->isExactlyValue(1.0))
6825     return N0;
6826
6827   if (Options.UnsafeFPMath) {
6828     // fold (fmul A, 0) -> 0
6829     if (N1CFP && N1CFP->getValueAPF().isZero())
6830       return N1;
6831
6832     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6833     if (N0.getOpcode() == ISD::FMUL) {
6834       // Fold scalars or any vector constants (not just splats).
6835       // This fold is done in general by InstCombine, but extra fmul insts
6836       // may have been generated during lowering.
6837       SDValue N01 = N0.getOperand(1);
6838       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6839       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6840       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6841           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6842         SDLoc SL(N);
6843         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6844         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6845       }
6846     }
6847
6848     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6849     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6850     // during an early run of DAGCombiner can prevent folding with fmuls
6851     // inserted during lowering.
6852     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6853       SDLoc SL(N);
6854       const SDValue Two = DAG.getConstantFP(2.0, VT);
6855       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6856       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6857     }
6858   }
6859
6860   // fold (fmul X, 2.0) -> (fadd X, X)
6861   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6862     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6863
6864   // fold (fmul X, -1.0) -> (fneg X)
6865   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6866     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6867       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6868
6869   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6870   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6871     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6872       // Both can be negated for free, check to see if at least one is cheaper
6873       // negated.
6874       if (LHSNeg == 2 || RHSNeg == 2)
6875         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6876                            GetNegatedExpression(N0, DAG, LegalOperations),
6877                            GetNegatedExpression(N1, DAG, LegalOperations));
6878     }
6879   }
6880
6881   return SDValue();
6882 }
6883
6884 SDValue DAGCombiner::visitFMA(SDNode *N) {
6885   SDValue N0 = N->getOperand(0);
6886   SDValue N1 = N->getOperand(1);
6887   SDValue N2 = N->getOperand(2);
6888   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6889   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6890   EVT VT = N->getValueType(0);
6891   SDLoc dl(N);
6892   const TargetOptions &Options = DAG.getTarget().Options;
6893
6894   // Constant fold FMA.
6895   if (isa<ConstantFPSDNode>(N0) &&
6896       isa<ConstantFPSDNode>(N1) &&
6897       isa<ConstantFPSDNode>(N2)) {
6898     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6899   }
6900
6901   if (Options.UnsafeFPMath) {
6902     if (N0CFP && N0CFP->isZero())
6903       return N2;
6904     if (N1CFP && N1CFP->isZero())
6905       return N2;
6906   }
6907   if (N0CFP && N0CFP->isExactlyValue(1.0))
6908     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6909   if (N1CFP && N1CFP->isExactlyValue(1.0))
6910     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6911
6912   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6913   if (N0CFP && !N1CFP)
6914     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6915
6916   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6917   if (Options.UnsafeFPMath && N1CFP &&
6918       N2.getOpcode() == ISD::FMUL &&
6919       N0 == N2.getOperand(0) &&
6920       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6921     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6922                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6923   }
6924
6925
6926   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6927   if (Options.UnsafeFPMath &&
6928       N0.getOpcode() == ISD::FMUL && N1CFP &&
6929       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6930     return DAG.getNode(ISD::FMA, dl, VT,
6931                        N0.getOperand(0),
6932                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6933                        N2);
6934   }
6935
6936   // (fma x, 1, y) -> (fadd x, y)
6937   // (fma x, -1, y) -> (fadd (fneg x), y)
6938   if (N1CFP) {
6939     if (N1CFP->isExactlyValue(1.0))
6940       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6941
6942     if (N1CFP->isExactlyValue(-1.0) &&
6943         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6944       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6945       AddToWorklist(RHSNeg.getNode());
6946       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6947     }
6948   }
6949
6950   // (fma x, c, x) -> (fmul x, (c+1))
6951   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6952     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6953                        DAG.getNode(ISD::FADD, dl, VT,
6954                                    N1, DAG.getConstantFP(1.0, VT)));
6955
6956   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6957   if (Options.UnsafeFPMath && N1CFP &&
6958       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6959     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6960                        DAG.getNode(ISD::FADD, dl, VT,
6961                                    N1, DAG.getConstantFP(-1.0, VT)));
6962
6963
6964   return SDValue();
6965 }
6966
6967 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6968   SDValue N0 = N->getOperand(0);
6969   SDValue N1 = N->getOperand(1);
6970   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6971   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6972   EVT VT = N->getValueType(0);
6973   SDLoc DL(N);
6974   const TargetOptions &Options = DAG.getTarget().Options;
6975
6976   // fold vector ops
6977   if (VT.isVector()) {
6978     SDValue FoldedVOp = SimplifyVBinOp(N);
6979     if (FoldedVOp.getNode()) return FoldedVOp;
6980   }
6981
6982   // fold (fdiv c1, c2) -> c1/c2
6983   if (N0CFP && N1CFP)
6984     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6985
6986   if (Options.UnsafeFPMath) {
6987     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6988     if (N1CFP) {
6989       // Compute the reciprocal 1.0 / c2.
6990       APFloat N1APF = N1CFP->getValueAPF();
6991       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6992       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6993       // Only do the transform if the reciprocal is a legal fp immediate that
6994       // isn't too nasty (eg NaN, denormal, ...).
6995       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6996           (!LegalOperations ||
6997            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6998            // backend)... we should handle this gracefully after Legalize.
6999            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7000            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7001            TLI.isFPImmLegal(Recip, VT)))
7002         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7003                            DAG.getConstantFP(Recip, VT));
7004     }
7005     
7006     // If this FDIV is part of a reciprocal square root, it may be folded
7007     // into a target-specific square root estimate instruction.
7008     if (N1.getOpcode() == ISD::FSQRT) {
7009       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7010         AddToWorklist(RV.getNode());
7011         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7012       }
7013     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7014                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7015       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7016         AddToWorklist(RV.getNode());
7017         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7018         AddToWorklist(RV.getNode());
7019         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7020       }
7021     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7022                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7023       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7024         AddToWorklist(RV.getNode());
7025         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7026         AddToWorklist(RV.getNode());
7027         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7028       }
7029     } else if (N1.getOpcode() == ISD::FMUL) {
7030       // Look through an FMUL. Even though this won't remove the FDIV directly,
7031       // it's still worthwhile to get rid of the FSQRT if possible.
7032       SDValue SqrtOp;
7033       SDValue OtherOp;
7034       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7035         SqrtOp = N1.getOperand(0);
7036         OtherOp = N1.getOperand(1);
7037       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7038         SqrtOp = N1.getOperand(1);
7039         OtherOp = N1.getOperand(0);
7040       }
7041       if (SqrtOp.getNode()) {
7042         // We found a FSQRT, so try to make this fold:
7043         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7044         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7045           AddToWorklist(RV.getNode());
7046           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7047           AddToWorklist(RV.getNode());
7048           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7049         }
7050       }
7051     }
7052     
7053     // Fold into a reciprocal estimate and multiply instead of a real divide.
7054     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7055       AddToWorklist(RV.getNode());
7056       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7057     }
7058   }
7059
7060   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7061   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7062     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7063       // Both can be negated for free, check to see if at least one is cheaper
7064       // negated.
7065       if (LHSNeg == 2 || RHSNeg == 2)
7066         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7067                            GetNegatedExpression(N0, DAG, LegalOperations),
7068                            GetNegatedExpression(N1, DAG, LegalOperations));
7069     }
7070   }
7071
7072   return SDValue();
7073 }
7074
7075 SDValue DAGCombiner::visitFREM(SDNode *N) {
7076   SDValue N0 = N->getOperand(0);
7077   SDValue N1 = N->getOperand(1);
7078   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7079   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7080   EVT VT = N->getValueType(0);
7081
7082   // fold (frem c1, c2) -> fmod(c1,c2)
7083   if (N0CFP && N1CFP)
7084     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7085
7086   return SDValue();
7087 }
7088
7089 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7090   if (DAG.getTarget().Options.UnsafeFPMath) {
7091     // Compute this as 1/(1/sqrt(X)): the reciprocal of the reciprocal sqrt.
7092     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7093       AddToWorklist(RV.getNode());
7094       RV = BuildReciprocalEstimate(RV);
7095       if (RV.getNode()) {
7096         // Unfortunately, RV is now NaN if the input was exactly 0.
7097         // Select out this case and force the answer to 0.
7098         EVT VT = RV.getValueType();
7099       
7100         SDValue Zero = DAG.getConstantFP(0.0, VT);
7101         SDValue ZeroCmp =
7102           DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7103                        N->getOperand(0), Zero, ISD::SETEQ);
7104         AddToWorklist(ZeroCmp.getNode());
7105         AddToWorklist(RV.getNode());
7106
7107         RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7108                          SDLoc(N), VT, ZeroCmp, Zero, RV);
7109         return RV;
7110       }
7111     }
7112   }
7113   return SDValue();
7114 }
7115
7116 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7117   SDValue N0 = N->getOperand(0);
7118   SDValue N1 = N->getOperand(1);
7119   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7120   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7121   EVT VT = N->getValueType(0);
7122
7123   if (N0CFP && N1CFP)  // Constant fold
7124     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7125
7126   if (N1CFP) {
7127     const APFloat& V = N1CFP->getValueAPF();
7128     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7129     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7130     if (!V.isNegative()) {
7131       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7132         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7133     } else {
7134       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7135         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7136                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7137     }
7138   }
7139
7140   // copysign(fabs(x), y) -> copysign(x, y)
7141   // copysign(fneg(x), y) -> copysign(x, y)
7142   // copysign(copysign(x,z), y) -> copysign(x, y)
7143   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7144       N0.getOpcode() == ISD::FCOPYSIGN)
7145     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7146                        N0.getOperand(0), N1);
7147
7148   // copysign(x, abs(y)) -> abs(x)
7149   if (N1.getOpcode() == ISD::FABS)
7150     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7151
7152   // copysign(x, copysign(y,z)) -> copysign(x, z)
7153   if (N1.getOpcode() == ISD::FCOPYSIGN)
7154     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7155                        N0, N1.getOperand(1));
7156
7157   // copysign(x, fp_extend(y)) -> copysign(x, y)
7158   // copysign(x, fp_round(y)) -> copysign(x, y)
7159   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7160     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7161                        N0, N1.getOperand(0));
7162
7163   return SDValue();
7164 }
7165
7166 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7167   SDValue N0 = N->getOperand(0);
7168   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7169   EVT VT = N->getValueType(0);
7170   EVT OpVT = N0.getValueType();
7171
7172   // fold (sint_to_fp c1) -> c1fp
7173   if (N0C &&
7174       // ...but only if the target supports immediate floating-point values
7175       (!LegalOperations ||
7176        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7177     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7178
7179   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7180   // but UINT_TO_FP is legal on this target, try to convert.
7181   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7182       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7183     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7184     if (DAG.SignBitIsZero(N0))
7185       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7186   }
7187
7188   // The next optimizations are desirable only if SELECT_CC can be lowered.
7189   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7190     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7191     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7192         !VT.isVector() &&
7193         (!LegalOperations ||
7194          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7195       SDValue Ops[] =
7196         { N0.getOperand(0), N0.getOperand(1),
7197           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7198           N0.getOperand(2) };
7199       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7200     }
7201
7202     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7203     //      (select_cc x, y, 1.0, 0.0,, cc)
7204     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7205         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7206         (!LegalOperations ||
7207          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7208       SDValue Ops[] =
7209         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7210           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7211           N0.getOperand(0).getOperand(2) };
7212       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7213     }
7214   }
7215
7216   return SDValue();
7217 }
7218
7219 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7220   SDValue N0 = N->getOperand(0);
7221   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7222   EVT VT = N->getValueType(0);
7223   EVT OpVT = N0.getValueType();
7224
7225   // fold (uint_to_fp c1) -> c1fp
7226   if (N0C &&
7227       // ...but only if the target supports immediate floating-point values
7228       (!LegalOperations ||
7229        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7230     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7231
7232   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7233   // but SINT_TO_FP is legal on this target, try to convert.
7234   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7235       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7236     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7237     if (DAG.SignBitIsZero(N0))
7238       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7239   }
7240
7241   // The next optimizations are desirable only if SELECT_CC can be lowered.
7242   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7243     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7244
7245     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7246         (!LegalOperations ||
7247          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7248       SDValue Ops[] =
7249         { N0.getOperand(0), N0.getOperand(1),
7250           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7251           N0.getOperand(2) };
7252       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7253     }
7254   }
7255
7256   return SDValue();
7257 }
7258
7259 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7260   SDValue N0 = N->getOperand(0);
7261   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7262   EVT VT = N->getValueType(0);
7263
7264   // fold (fp_to_sint c1fp) -> c1
7265   if (N0CFP)
7266     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7267
7268   return SDValue();
7269 }
7270
7271 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7272   SDValue N0 = N->getOperand(0);
7273   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7274   EVT VT = N->getValueType(0);
7275
7276   // fold (fp_to_uint c1fp) -> c1
7277   if (N0CFP)
7278     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7279
7280   return SDValue();
7281 }
7282
7283 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7284   SDValue N0 = N->getOperand(0);
7285   SDValue N1 = N->getOperand(1);
7286   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7287   EVT VT = N->getValueType(0);
7288
7289   // fold (fp_round c1fp) -> c1fp
7290   if (N0CFP)
7291     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7292
7293   // fold (fp_round (fp_extend x)) -> x
7294   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7295     return N0.getOperand(0);
7296
7297   // fold (fp_round (fp_round x)) -> (fp_round x)
7298   if (N0.getOpcode() == ISD::FP_ROUND) {
7299     // This is a value preserving truncation if both round's are.
7300     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7301                    N0.getNode()->getConstantOperandVal(1) == 1;
7302     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7303                        DAG.getIntPtrConstant(IsTrunc));
7304   }
7305
7306   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7307   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7308     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7309                               N0.getOperand(0), N1);
7310     AddToWorklist(Tmp.getNode());
7311     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7312                        Tmp, N0.getOperand(1));
7313   }
7314
7315   return SDValue();
7316 }
7317
7318 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7319   SDValue N0 = N->getOperand(0);
7320   EVT VT = N->getValueType(0);
7321   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7322   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7323
7324   // fold (fp_round_inreg c1fp) -> c1fp
7325   if (N0CFP && isTypeLegal(EVT)) {
7326     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7327     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7328   }
7329
7330   return SDValue();
7331 }
7332
7333 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7334   SDValue N0 = N->getOperand(0);
7335   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7336   EVT VT = N->getValueType(0);
7337
7338   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7339   if (N->hasOneUse() &&
7340       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7341     return SDValue();
7342
7343   // fold (fp_extend c1fp) -> c1fp
7344   if (N0CFP)
7345     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7346
7347   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7348   // value of X.
7349   if (N0.getOpcode() == ISD::FP_ROUND
7350       && N0.getNode()->getConstantOperandVal(1) == 1) {
7351     SDValue In = N0.getOperand(0);
7352     if (In.getValueType() == VT) return In;
7353     if (VT.bitsLT(In.getValueType()))
7354       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7355                          In, N0.getOperand(1));
7356     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7357   }
7358
7359   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7360   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7361        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7362     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7363     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7364                                      LN0->getChain(),
7365                                      LN0->getBasePtr(), N0.getValueType(),
7366                                      LN0->getMemOperand());
7367     CombineTo(N, ExtLoad);
7368     CombineTo(N0.getNode(),
7369               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7370                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7371               ExtLoad.getValue(1));
7372     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7373   }
7374
7375   return SDValue();
7376 }
7377
7378 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7379   SDValue N0 = N->getOperand(0);
7380   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7381   EVT VT = N->getValueType(0);
7382
7383   // fold (fceil c1) -> fceil(c1)
7384   if (N0CFP)
7385     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7386
7387   return SDValue();
7388 }
7389
7390 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7391   SDValue N0 = N->getOperand(0);
7392   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7393   EVT VT = N->getValueType(0);
7394
7395   // fold (ftrunc c1) -> ftrunc(c1)
7396   if (N0CFP)
7397     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7398
7399   return SDValue();
7400 }
7401
7402 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7403   SDValue N0 = N->getOperand(0);
7404   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7405   EVT VT = N->getValueType(0);
7406
7407   // fold (ffloor c1) -> ffloor(c1)
7408   if (N0CFP)
7409     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7410
7411   return SDValue();
7412 }
7413
7414 // FIXME: FNEG and FABS have a lot in common; refactor.
7415 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7416   SDValue N0 = N->getOperand(0);
7417   EVT VT = N->getValueType(0);
7418
7419   if (VT.isVector()) {
7420     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7421     if (FoldedVOp.getNode()) return FoldedVOp;
7422   }
7423
7424   // Constant fold FNEG.
7425   if (isa<ConstantFPSDNode>(N0))
7426     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7427
7428   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7429                          &DAG.getTarget().Options))
7430     return GetNegatedExpression(N0, DAG, LegalOperations);
7431
7432   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7433   // constant pool values.
7434   if (!TLI.isFNegFree(VT) &&
7435       N0.getOpcode() == ISD::BITCAST &&
7436       N0.getNode()->hasOneUse()) {
7437     SDValue Int = N0.getOperand(0);
7438     EVT IntVT = Int.getValueType();
7439     if (IntVT.isInteger() && !IntVT.isVector()) {
7440       APInt SignMask;
7441       if (N0.getValueType().isVector()) {
7442         // For a vector, get a mask such as 0x80... per scalar element
7443         // and splat it.
7444         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7445         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7446       } else {
7447         // For a scalar, just generate 0x80...
7448         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7449       }
7450       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7451                         DAG.getConstant(SignMask, IntVT));
7452       AddToWorklist(Int.getNode());
7453       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7454     }
7455   }
7456
7457   // (fneg (fmul c, x)) -> (fmul -c, x)
7458   if (N0.getOpcode() == ISD::FMUL) {
7459     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7460     if (CFP1) {
7461       APFloat CVal = CFP1->getValueAPF();
7462       CVal.changeSign();
7463       if (Level >= AfterLegalizeDAG &&
7464           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7465            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7466         return DAG.getNode(
7467             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7468             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7469     }
7470   }
7471
7472   return SDValue();
7473 }
7474
7475 SDValue DAGCombiner::visitFABS(SDNode *N) {
7476   SDValue N0 = N->getOperand(0);
7477   EVT VT = N->getValueType(0);
7478
7479   if (VT.isVector()) {
7480     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7481     if (FoldedVOp.getNode()) return FoldedVOp;
7482   }
7483
7484   // fold (fabs c1) -> fabs(c1)
7485   if (isa<ConstantFPSDNode>(N0))
7486     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7487   
7488   // fold (fabs (fabs x)) -> (fabs x)
7489   if (N0.getOpcode() == ISD::FABS)
7490     return N->getOperand(0);
7491
7492   // fold (fabs (fneg x)) -> (fabs x)
7493   // fold (fabs (fcopysign x, y)) -> (fabs x)
7494   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7495     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7496
7497   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7498   // constant pool values.
7499   if (!TLI.isFAbsFree(VT) &&
7500       N0.getOpcode() == ISD::BITCAST &&
7501       N0.getNode()->hasOneUse()) {
7502     SDValue Int = N0.getOperand(0);
7503     EVT IntVT = Int.getValueType();
7504     if (IntVT.isInteger() && !IntVT.isVector()) {
7505       APInt SignMask;
7506       if (N0.getValueType().isVector()) {
7507         // For a vector, get a mask such as 0x7f... per scalar element
7508         // and splat it.
7509         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7510         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7511       } else {
7512         // For a scalar, just generate 0x7f...
7513         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7514       }
7515       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7516                         DAG.getConstant(SignMask, IntVT));
7517       AddToWorklist(Int.getNode());
7518       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7519     }
7520   }
7521
7522   return SDValue();
7523 }
7524
7525 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7526   SDValue Chain = N->getOperand(0);
7527   SDValue N1 = N->getOperand(1);
7528   SDValue N2 = N->getOperand(2);
7529
7530   // If N is a constant we could fold this into a fallthrough or unconditional
7531   // branch. However that doesn't happen very often in normal code, because
7532   // Instcombine/SimplifyCFG should have handled the available opportunities.
7533   // If we did this folding here, it would be necessary to update the
7534   // MachineBasicBlock CFG, which is awkward.
7535
7536   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7537   // on the target.
7538   if (N1.getOpcode() == ISD::SETCC &&
7539       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7540                                    N1.getOperand(0).getValueType())) {
7541     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7542                        Chain, N1.getOperand(2),
7543                        N1.getOperand(0), N1.getOperand(1), N2);
7544   }
7545
7546   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7547       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7548        (N1.getOperand(0).hasOneUse() &&
7549         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7550     SDNode *Trunc = nullptr;
7551     if (N1.getOpcode() == ISD::TRUNCATE) {
7552       // Look pass the truncate.
7553       Trunc = N1.getNode();
7554       N1 = N1.getOperand(0);
7555     }
7556
7557     // Match this pattern so that we can generate simpler code:
7558     //
7559     //   %a = ...
7560     //   %b = and i32 %a, 2
7561     //   %c = srl i32 %b, 1
7562     //   brcond i32 %c ...
7563     //
7564     // into
7565     //
7566     //   %a = ...
7567     //   %b = and i32 %a, 2
7568     //   %c = setcc eq %b, 0
7569     //   brcond %c ...
7570     //
7571     // This applies only when the AND constant value has one bit set and the
7572     // SRL constant is equal to the log2 of the AND constant. The back-end is
7573     // smart enough to convert the result into a TEST/JMP sequence.
7574     SDValue Op0 = N1.getOperand(0);
7575     SDValue Op1 = N1.getOperand(1);
7576
7577     if (Op0.getOpcode() == ISD::AND &&
7578         Op1.getOpcode() == ISD::Constant) {
7579       SDValue AndOp1 = Op0.getOperand(1);
7580
7581       if (AndOp1.getOpcode() == ISD::Constant) {
7582         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7583
7584         if (AndConst.isPowerOf2() &&
7585             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7586           SDValue SetCC =
7587             DAG.getSetCC(SDLoc(N),
7588                          getSetCCResultType(Op0.getValueType()),
7589                          Op0, DAG.getConstant(0, Op0.getValueType()),
7590                          ISD::SETNE);
7591
7592           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7593                                           MVT::Other, Chain, SetCC, N2);
7594           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7595           // will convert it back to (X & C1) >> C2.
7596           CombineTo(N, NewBRCond, false);
7597           // Truncate is dead.
7598           if (Trunc)
7599             deleteAndRecombine(Trunc);
7600           // Replace the uses of SRL with SETCC
7601           WorklistRemover DeadNodes(*this);
7602           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7603           deleteAndRecombine(N1.getNode());
7604           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7605         }
7606       }
7607     }
7608
7609     if (Trunc)
7610       // Restore N1 if the above transformation doesn't match.
7611       N1 = N->getOperand(1);
7612   }
7613
7614   // Transform br(xor(x, y)) -> br(x != y)
7615   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7616   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7617     SDNode *TheXor = N1.getNode();
7618     SDValue Op0 = TheXor->getOperand(0);
7619     SDValue Op1 = TheXor->getOperand(1);
7620     if (Op0.getOpcode() == Op1.getOpcode()) {
7621       // Avoid missing important xor optimizations.
7622       SDValue Tmp = visitXOR(TheXor);
7623       if (Tmp.getNode()) {
7624         if (Tmp.getNode() != TheXor) {
7625           DEBUG(dbgs() << "\nReplacing.8 ";
7626                 TheXor->dump(&DAG);
7627                 dbgs() << "\nWith: ";
7628                 Tmp.getNode()->dump(&DAG);
7629                 dbgs() << '\n');
7630           WorklistRemover DeadNodes(*this);
7631           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7632           deleteAndRecombine(TheXor);
7633           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7634                              MVT::Other, Chain, Tmp, N2);
7635         }
7636
7637         // visitXOR has changed XOR's operands or replaced the XOR completely,
7638         // bail out.
7639         return SDValue(N, 0);
7640       }
7641     }
7642
7643     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7644       bool Equal = false;
7645       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7646         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7647             Op0.getOpcode() == ISD::XOR) {
7648           TheXor = Op0.getNode();
7649           Equal = true;
7650         }
7651
7652       EVT SetCCVT = N1.getValueType();
7653       if (LegalTypes)
7654         SetCCVT = getSetCCResultType(SetCCVT);
7655       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7656                                    SetCCVT,
7657                                    Op0, Op1,
7658                                    Equal ? ISD::SETEQ : ISD::SETNE);
7659       // Replace the uses of XOR with SETCC
7660       WorklistRemover DeadNodes(*this);
7661       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7662       deleteAndRecombine(N1.getNode());
7663       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7664                          MVT::Other, Chain, SetCC, N2);
7665     }
7666   }
7667
7668   return SDValue();
7669 }
7670
7671 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7672 //
7673 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7674   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7675   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7676
7677   // If N is a constant we could fold this into a fallthrough or unconditional
7678   // branch. However that doesn't happen very often in normal code, because
7679   // Instcombine/SimplifyCFG should have handled the available opportunities.
7680   // If we did this folding here, it would be necessary to update the
7681   // MachineBasicBlock CFG, which is awkward.
7682
7683   // Use SimplifySetCC to simplify SETCC's.
7684   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7685                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7686                                false);
7687   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7688
7689   // fold to a simpler setcc
7690   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7691     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7692                        N->getOperand(0), Simp.getOperand(2),
7693                        Simp.getOperand(0), Simp.getOperand(1),
7694                        N->getOperand(4));
7695
7696   return SDValue();
7697 }
7698
7699 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7700 /// and that N may be folded in the load / store addressing mode.
7701 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7702                                     SelectionDAG &DAG,
7703                                     const TargetLowering &TLI) {
7704   EVT VT;
7705   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7706     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7707       return false;
7708     VT = Use->getValueType(0);
7709   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7710     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7711       return false;
7712     VT = ST->getValue().getValueType();
7713   } else
7714     return false;
7715
7716   TargetLowering::AddrMode AM;
7717   if (N->getOpcode() == ISD::ADD) {
7718     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7719     if (Offset)
7720       // [reg +/- imm]
7721       AM.BaseOffs = Offset->getSExtValue();
7722     else
7723       // [reg +/- reg]
7724       AM.Scale = 1;
7725   } else if (N->getOpcode() == ISD::SUB) {
7726     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7727     if (Offset)
7728       // [reg +/- imm]
7729       AM.BaseOffs = -Offset->getSExtValue();
7730     else
7731       // [reg +/- reg]
7732       AM.Scale = 1;
7733   } else
7734     return false;
7735
7736   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7737 }
7738
7739 /// Try turning a load/store into a pre-indexed load/store when the base
7740 /// pointer is an add or subtract and it has other uses besides the load/store.
7741 /// After the transformation, the new indexed load/store has effectively folded
7742 /// the add/subtract in and all of its other uses are redirected to the
7743 /// new load/store.
7744 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7745   if (Level < AfterLegalizeDAG)
7746     return false;
7747
7748   bool isLoad = true;
7749   SDValue Ptr;
7750   EVT VT;
7751   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7752     if (LD->isIndexed())
7753       return false;
7754     VT = LD->getMemoryVT();
7755     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7756         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7757       return false;
7758     Ptr = LD->getBasePtr();
7759   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7760     if (ST->isIndexed())
7761       return false;
7762     VT = ST->getMemoryVT();
7763     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7764         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7765       return false;
7766     Ptr = ST->getBasePtr();
7767     isLoad = false;
7768   } else {
7769     return false;
7770   }
7771
7772   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7773   // out.  There is no reason to make this a preinc/predec.
7774   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7775       Ptr.getNode()->hasOneUse())
7776     return false;
7777
7778   // Ask the target to do addressing mode selection.
7779   SDValue BasePtr;
7780   SDValue Offset;
7781   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7782   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7783     return false;
7784
7785   // Backends without true r+i pre-indexed forms may need to pass a
7786   // constant base with a variable offset so that constant coercion
7787   // will work with the patterns in canonical form.
7788   bool Swapped = false;
7789   if (isa<ConstantSDNode>(BasePtr)) {
7790     std::swap(BasePtr, Offset);
7791     Swapped = true;
7792   }
7793
7794   // Don't create a indexed load / store with zero offset.
7795   if (isa<ConstantSDNode>(Offset) &&
7796       cast<ConstantSDNode>(Offset)->isNullValue())
7797     return false;
7798
7799   // Try turning it into a pre-indexed load / store except when:
7800   // 1) The new base ptr is a frame index.
7801   // 2) If N is a store and the new base ptr is either the same as or is a
7802   //    predecessor of the value being stored.
7803   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7804   //    that would create a cycle.
7805   // 4) All uses are load / store ops that use it as old base ptr.
7806
7807   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7808   // (plus the implicit offset) to a register to preinc anyway.
7809   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7810     return false;
7811
7812   // Check #2.
7813   if (!isLoad) {
7814     SDValue Val = cast<StoreSDNode>(N)->getValue();
7815     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7816       return false;
7817   }
7818
7819   // If the offset is a constant, there may be other adds of constants that
7820   // can be folded with this one. We should do this to avoid having to keep
7821   // a copy of the original base pointer.
7822   SmallVector<SDNode *, 16> OtherUses;
7823   if (isa<ConstantSDNode>(Offset))
7824     for (SDNode *Use : BasePtr.getNode()->uses()) {
7825       if (Use == Ptr.getNode())
7826         continue;
7827
7828       if (Use->isPredecessorOf(N))
7829         continue;
7830
7831       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7832         OtherUses.clear();
7833         break;
7834       }
7835
7836       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7837       if (Op1.getNode() == BasePtr.getNode())
7838         std::swap(Op0, Op1);
7839       assert(Op0.getNode() == BasePtr.getNode() &&
7840              "Use of ADD/SUB but not an operand");
7841
7842       if (!isa<ConstantSDNode>(Op1)) {
7843         OtherUses.clear();
7844         break;
7845       }
7846
7847       // FIXME: In some cases, we can be smarter about this.
7848       if (Op1.getValueType() != Offset.getValueType()) {
7849         OtherUses.clear();
7850         break;
7851       }
7852
7853       OtherUses.push_back(Use);
7854     }
7855
7856   if (Swapped)
7857     std::swap(BasePtr, Offset);
7858
7859   // Now check for #3 and #4.
7860   bool RealUse = false;
7861
7862   // Caches for hasPredecessorHelper
7863   SmallPtrSet<const SDNode *, 32> Visited;
7864   SmallVector<const SDNode *, 16> Worklist;
7865
7866   for (SDNode *Use : Ptr.getNode()->uses()) {
7867     if (Use == N)
7868       continue;
7869     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7870       return false;
7871
7872     // If Ptr may be folded in addressing mode of other use, then it's
7873     // not profitable to do this transformation.
7874     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7875       RealUse = true;
7876   }
7877
7878   if (!RealUse)
7879     return false;
7880
7881   SDValue Result;
7882   if (isLoad)
7883     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7884                                 BasePtr, Offset, AM);
7885   else
7886     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7887                                  BasePtr, Offset, AM);
7888   ++PreIndexedNodes;
7889   ++NodesCombined;
7890   DEBUG(dbgs() << "\nReplacing.4 ";
7891         N->dump(&DAG);
7892         dbgs() << "\nWith: ";
7893         Result.getNode()->dump(&DAG);
7894         dbgs() << '\n');
7895   WorklistRemover DeadNodes(*this);
7896   if (isLoad) {
7897     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7898     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7899   } else {
7900     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7901   }
7902
7903   // Finally, since the node is now dead, remove it from the graph.
7904   deleteAndRecombine(N);
7905
7906   if (Swapped)
7907     std::swap(BasePtr, Offset);
7908
7909   // Replace other uses of BasePtr that can be updated to use Ptr
7910   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7911     unsigned OffsetIdx = 1;
7912     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7913       OffsetIdx = 0;
7914     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7915            BasePtr.getNode() && "Expected BasePtr operand");
7916
7917     // We need to replace ptr0 in the following expression:
7918     //   x0 * offset0 + y0 * ptr0 = t0
7919     // knowing that
7920     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7921     //
7922     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7923     // indexed load/store and the expresion that needs to be re-written.
7924     //
7925     // Therefore, we have:
7926     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7927
7928     ConstantSDNode *CN =
7929       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7930     int X0, X1, Y0, Y1;
7931     APInt Offset0 = CN->getAPIntValue();
7932     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7933
7934     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7935     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7936     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7937     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7938
7939     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7940
7941     APInt CNV = Offset0;
7942     if (X0 < 0) CNV = -CNV;
7943     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7944     else CNV = CNV - Offset1;
7945
7946     // We can now generate the new expression.
7947     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7948     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7949
7950     SDValue NewUse = DAG.getNode(Opcode,
7951                                  SDLoc(OtherUses[i]),
7952                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7953     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7954     deleteAndRecombine(OtherUses[i]);
7955   }
7956
7957   // Replace the uses of Ptr with uses of the updated base value.
7958   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7959   deleteAndRecombine(Ptr.getNode());
7960
7961   return true;
7962 }
7963
7964 /// Try to combine a load/store with a add/sub of the base pointer node into a
7965 /// post-indexed load/store. The transformation folded the add/subtract into the
7966 /// new indexed load/store effectively and all of its uses are redirected to the
7967 /// new load/store.
7968 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7969   if (Level < AfterLegalizeDAG)
7970     return false;
7971
7972   bool isLoad = true;
7973   SDValue Ptr;
7974   EVT VT;
7975   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7976     if (LD->isIndexed())
7977       return false;
7978     VT = LD->getMemoryVT();
7979     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7980         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7981       return false;
7982     Ptr = LD->getBasePtr();
7983   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7984     if (ST->isIndexed())
7985       return false;
7986     VT = ST->getMemoryVT();
7987     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7988         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7989       return false;
7990     Ptr = ST->getBasePtr();
7991     isLoad = false;
7992   } else {
7993     return false;
7994   }
7995
7996   if (Ptr.getNode()->hasOneUse())
7997     return false;
7998
7999   for (SDNode *Op : Ptr.getNode()->uses()) {
8000     if (Op == N ||
8001         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8002       continue;
8003
8004     SDValue BasePtr;
8005     SDValue Offset;
8006     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8007     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8008       // Don't create a indexed load / store with zero offset.
8009       if (isa<ConstantSDNode>(Offset) &&
8010           cast<ConstantSDNode>(Offset)->isNullValue())
8011         continue;
8012
8013       // Try turning it into a post-indexed load / store except when
8014       // 1) All uses are load / store ops that use it as base ptr (and
8015       //    it may be folded as addressing mmode).
8016       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8017       //    nor a successor of N. Otherwise, if Op is folded that would
8018       //    create a cycle.
8019
8020       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8021         continue;
8022
8023       // Check for #1.
8024       bool TryNext = false;
8025       for (SDNode *Use : BasePtr.getNode()->uses()) {
8026         if (Use == Ptr.getNode())
8027           continue;
8028
8029         // If all the uses are load / store addresses, then don't do the
8030         // transformation.
8031         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8032           bool RealUse = false;
8033           for (SDNode *UseUse : Use->uses()) {
8034             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8035               RealUse = true;
8036           }
8037
8038           if (!RealUse) {
8039             TryNext = true;
8040             break;
8041           }
8042         }
8043       }
8044
8045       if (TryNext)
8046         continue;
8047
8048       // Check for #2
8049       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8050         SDValue Result = isLoad
8051           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8052                                BasePtr, Offset, AM)
8053           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8054                                 BasePtr, Offset, AM);
8055         ++PostIndexedNodes;
8056         ++NodesCombined;
8057         DEBUG(dbgs() << "\nReplacing.5 ";
8058               N->dump(&DAG);
8059               dbgs() << "\nWith: ";
8060               Result.getNode()->dump(&DAG);
8061               dbgs() << '\n');
8062         WorklistRemover DeadNodes(*this);
8063         if (isLoad) {
8064           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8065           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8066         } else {
8067           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8068         }
8069
8070         // Finally, since the node is now dead, remove it from the graph.
8071         deleteAndRecombine(N);
8072
8073         // Replace the uses of Use with uses of the updated base value.
8074         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8075                                       Result.getValue(isLoad ? 1 : 0));
8076         deleteAndRecombine(Op);
8077         return true;
8078       }
8079     }
8080   }
8081
8082   return false;
8083 }
8084
8085 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8086 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8087   ISD::MemIndexedMode AM = LD->getAddressingMode();
8088   assert(AM != ISD::UNINDEXED);
8089   SDValue BP = LD->getOperand(1);
8090   SDValue Inc = LD->getOperand(2);
8091
8092   // Some backends use TargetConstants for load offsets, but don't expect
8093   // TargetConstants in general ADD nodes. We can convert these constants into
8094   // regular Constants (if the constant is not opaque).
8095   assert((Inc.getOpcode() != ISD::TargetConstant ||
8096           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8097          "Cannot split out indexing using opaque target constants");
8098   if (Inc.getOpcode() == ISD::TargetConstant) {
8099     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8100     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8101                           ConstInc->getValueType(0));
8102   }
8103
8104   unsigned Opc =
8105       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8106   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8107 }
8108
8109 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8110   LoadSDNode *LD  = cast<LoadSDNode>(N);
8111   SDValue Chain = LD->getChain();
8112   SDValue Ptr   = LD->getBasePtr();
8113
8114   // If load is not volatile and there are no uses of the loaded value (and
8115   // the updated indexed value in case of indexed loads), change uses of the
8116   // chain value into uses of the chain input (i.e. delete the dead load).
8117   if (!LD->isVolatile()) {
8118     if (N->getValueType(1) == MVT::Other) {
8119       // Unindexed loads.
8120       if (!N->hasAnyUseOfValue(0)) {
8121         // It's not safe to use the two value CombineTo variant here. e.g.
8122         // v1, chain2 = load chain1, loc
8123         // v2, chain3 = load chain2, loc
8124         // v3         = add v2, c
8125         // Now we replace use of chain2 with chain1.  This makes the second load
8126         // isomorphic to the one we are deleting, and thus makes this load live.
8127         DEBUG(dbgs() << "\nReplacing.6 ";
8128               N->dump(&DAG);
8129               dbgs() << "\nWith chain: ";
8130               Chain.getNode()->dump(&DAG);
8131               dbgs() << "\n");
8132         WorklistRemover DeadNodes(*this);
8133         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8134
8135         if (N->use_empty())
8136           deleteAndRecombine(N);
8137
8138         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8139       }
8140     } else {
8141       // Indexed loads.
8142       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8143
8144       // If this load has an opaque TargetConstant offset, then we cannot split
8145       // the indexing into an add/sub directly (that TargetConstant may not be
8146       // valid for a different type of node, and we cannot convert an opaque
8147       // target constant into a regular constant).
8148       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8149                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8150
8151       if (!N->hasAnyUseOfValue(0) &&
8152           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8153         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8154         SDValue Index;
8155         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8156           Index = SplitIndexingFromLoad(LD);
8157           // Try to fold the base pointer arithmetic into subsequent loads and
8158           // stores.
8159           AddUsersToWorklist(N);
8160         } else
8161           Index = DAG.getUNDEF(N->getValueType(1));
8162         DEBUG(dbgs() << "\nReplacing.7 ";
8163               N->dump(&DAG);
8164               dbgs() << "\nWith: ";
8165               Undef.getNode()->dump(&DAG);
8166               dbgs() << " and 2 other values\n");
8167         WorklistRemover DeadNodes(*this);
8168         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8169         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8170         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8171         deleteAndRecombine(N);
8172         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8173       }
8174     }
8175   }
8176
8177   // If this load is directly stored, replace the load value with the stored
8178   // value.
8179   // TODO: Handle store large -> read small portion.
8180   // TODO: Handle TRUNCSTORE/LOADEXT
8181   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8182     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8183       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8184       if (PrevST->getBasePtr() == Ptr &&
8185           PrevST->getValue().getValueType() == N->getValueType(0))
8186       return CombineTo(N, Chain.getOperand(1), Chain);
8187     }
8188   }
8189
8190   // Try to infer better alignment information than the load already has.
8191   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8192     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8193       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8194         SDValue NewLoad =
8195                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8196                               LD->getValueType(0),
8197                               Chain, Ptr, LD->getPointerInfo(),
8198                               LD->getMemoryVT(),
8199                               LD->isVolatile(), LD->isNonTemporal(),
8200                               LD->isInvariant(), Align, LD->getAAInfo());
8201         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8202       }
8203     }
8204   }
8205
8206   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8207                                                   : DAG.getSubtarget().useAA();
8208 #ifndef NDEBUG
8209   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8210       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8211     UseAA = false;
8212 #endif
8213   if (UseAA && LD->isUnindexed()) {
8214     // Walk up chain skipping non-aliasing memory nodes.
8215     SDValue BetterChain = FindBetterChain(N, Chain);
8216
8217     // If there is a better chain.
8218     if (Chain != BetterChain) {
8219       SDValue ReplLoad;
8220
8221       // Replace the chain to void dependency.
8222       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8223         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8224                                BetterChain, Ptr, LD->getMemOperand());
8225       } else {
8226         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8227                                   LD->getValueType(0),
8228                                   BetterChain, Ptr, LD->getMemoryVT(),
8229                                   LD->getMemOperand());
8230       }
8231
8232       // Create token factor to keep old chain connected.
8233       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8234                                   MVT::Other, Chain, ReplLoad.getValue(1));
8235
8236       // Make sure the new and old chains are cleaned up.
8237       AddToWorklist(Token.getNode());
8238
8239       // Replace uses with load result and token factor. Don't add users
8240       // to work list.
8241       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8242     }
8243   }
8244
8245   // Try transforming N to an indexed load.
8246   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8247     return SDValue(N, 0);
8248
8249   // Try to slice up N to more direct loads if the slices are mapped to
8250   // different register banks or pairing can take place.
8251   if (SliceUpLoad(N))
8252     return SDValue(N, 0);
8253
8254   return SDValue();
8255 }
8256
8257 namespace {
8258 /// \brief Helper structure used to slice a load in smaller loads.
8259 /// Basically a slice is obtained from the following sequence:
8260 /// Origin = load Ty1, Base
8261 /// Shift = srl Ty1 Origin, CstTy Amount
8262 /// Inst = trunc Shift to Ty2
8263 ///
8264 /// Then, it will be rewriten into:
8265 /// Slice = load SliceTy, Base + SliceOffset
8266 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8267 ///
8268 /// SliceTy is deduced from the number of bits that are actually used to
8269 /// build Inst.
8270 struct LoadedSlice {
8271   /// \brief Helper structure used to compute the cost of a slice.
8272   struct Cost {
8273     /// Are we optimizing for code size.
8274     bool ForCodeSize;
8275     /// Various cost.
8276     unsigned Loads;
8277     unsigned Truncates;
8278     unsigned CrossRegisterBanksCopies;
8279     unsigned ZExts;
8280     unsigned Shift;
8281
8282     Cost(bool ForCodeSize = false)
8283         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8284           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8285
8286     /// \brief Get the cost of one isolated slice.
8287     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8288         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8289           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8290       EVT TruncType = LS.Inst->getValueType(0);
8291       EVT LoadedType = LS.getLoadedType();
8292       if (TruncType != LoadedType &&
8293           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8294         ZExts = 1;
8295     }
8296
8297     /// \brief Account for slicing gain in the current cost.
8298     /// Slicing provide a few gains like removing a shift or a
8299     /// truncate. This method allows to grow the cost of the original
8300     /// load with the gain from this slice.
8301     void addSliceGain(const LoadedSlice &LS) {
8302       // Each slice saves a truncate.
8303       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8304       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8305                               LS.Inst->getOperand(0).getValueType()))
8306         ++Truncates;
8307       // If there is a shift amount, this slice gets rid of it.
8308       if (LS.Shift)
8309         ++Shift;
8310       // If this slice can merge a cross register bank copy, account for it.
8311       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8312         ++CrossRegisterBanksCopies;
8313     }
8314
8315     Cost &operator+=(const Cost &RHS) {
8316       Loads += RHS.Loads;
8317       Truncates += RHS.Truncates;
8318       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8319       ZExts += RHS.ZExts;
8320       Shift += RHS.Shift;
8321       return *this;
8322     }
8323
8324     bool operator==(const Cost &RHS) const {
8325       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8326              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8327              ZExts == RHS.ZExts && Shift == RHS.Shift;
8328     }
8329
8330     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8331
8332     bool operator<(const Cost &RHS) const {
8333       // Assume cross register banks copies are as expensive as loads.
8334       // FIXME: Do we want some more target hooks?
8335       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8336       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8337       // Unless we are optimizing for code size, consider the
8338       // expensive operation first.
8339       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8340         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8341       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8342              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8343     }
8344
8345     bool operator>(const Cost &RHS) const { return RHS < *this; }
8346
8347     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8348
8349     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8350   };
8351   // The last instruction that represent the slice. This should be a
8352   // truncate instruction.
8353   SDNode *Inst;
8354   // The original load instruction.
8355   LoadSDNode *Origin;
8356   // The right shift amount in bits from the original load.
8357   unsigned Shift;
8358   // The DAG from which Origin came from.
8359   // This is used to get some contextual information about legal types, etc.
8360   SelectionDAG *DAG;
8361
8362   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8363               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8364       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8365
8366   LoadedSlice(const LoadedSlice &LS)
8367       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8368
8369   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8370   /// \return Result is \p BitWidth and has used bits set to 1 and
8371   ///         not used bits set to 0.
8372   APInt getUsedBits() const {
8373     // Reproduce the trunc(lshr) sequence:
8374     // - Start from the truncated value.
8375     // - Zero extend to the desired bit width.
8376     // - Shift left.
8377     assert(Origin && "No original load to compare against.");
8378     unsigned BitWidth = Origin->getValueSizeInBits(0);
8379     assert(Inst && "This slice is not bound to an instruction");
8380     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8381            "Extracted slice is bigger than the whole type!");
8382     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8383     UsedBits.setAllBits();
8384     UsedBits = UsedBits.zext(BitWidth);
8385     UsedBits <<= Shift;
8386     return UsedBits;
8387   }
8388
8389   /// \brief Get the size of the slice to be loaded in bytes.
8390   unsigned getLoadedSize() const {
8391     unsigned SliceSize = getUsedBits().countPopulation();
8392     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8393     return SliceSize / 8;
8394   }
8395
8396   /// \brief Get the type that will be loaded for this slice.
8397   /// Note: This may not be the final type for the slice.
8398   EVT getLoadedType() const {
8399     assert(DAG && "Missing context");
8400     LLVMContext &Ctxt = *DAG->getContext();
8401     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8402   }
8403
8404   /// \brief Get the alignment of the load used for this slice.
8405   unsigned getAlignment() const {
8406     unsigned Alignment = Origin->getAlignment();
8407     unsigned Offset = getOffsetFromBase();
8408     if (Offset != 0)
8409       Alignment = MinAlign(Alignment, Alignment + Offset);
8410     return Alignment;
8411   }
8412
8413   /// \brief Check if this slice can be rewritten with legal operations.
8414   bool isLegal() const {
8415     // An invalid slice is not legal.
8416     if (!Origin || !Inst || !DAG)
8417       return false;
8418
8419     // Offsets are for indexed load only, we do not handle that.
8420     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8421       return false;
8422
8423     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8424
8425     // Check that the type is legal.
8426     EVT SliceType = getLoadedType();
8427     if (!TLI.isTypeLegal(SliceType))
8428       return false;
8429
8430     // Check that the load is legal for this type.
8431     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8432       return false;
8433
8434     // Check that the offset can be computed.
8435     // 1. Check its type.
8436     EVT PtrType = Origin->getBasePtr().getValueType();
8437     if (PtrType == MVT::Untyped || PtrType.isExtended())
8438       return false;
8439
8440     // 2. Check that it fits in the immediate.
8441     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8442       return false;
8443
8444     // 3. Check that the computation is legal.
8445     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8446       return false;
8447
8448     // Check that the zext is legal if it needs one.
8449     EVT TruncateType = Inst->getValueType(0);
8450     if (TruncateType != SliceType &&
8451         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8452       return false;
8453
8454     return true;
8455   }
8456
8457   /// \brief Get the offset in bytes of this slice in the original chunk of
8458   /// bits.
8459   /// \pre DAG != nullptr.
8460   uint64_t getOffsetFromBase() const {
8461     assert(DAG && "Missing context.");
8462     bool IsBigEndian =
8463         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8464     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8465     uint64_t Offset = Shift / 8;
8466     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8467     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8468            "The size of the original loaded type is not a multiple of a"
8469            " byte.");
8470     // If Offset is bigger than TySizeInBytes, it means we are loading all
8471     // zeros. This should have been optimized before in the process.
8472     assert(TySizeInBytes > Offset &&
8473            "Invalid shift amount for given loaded size");
8474     if (IsBigEndian)
8475       Offset = TySizeInBytes - Offset - getLoadedSize();
8476     return Offset;
8477   }
8478
8479   /// \brief Generate the sequence of instructions to load the slice
8480   /// represented by this object and redirect the uses of this slice to
8481   /// this new sequence of instructions.
8482   /// \pre this->Inst && this->Origin are valid Instructions and this
8483   /// object passed the legal check: LoadedSlice::isLegal returned true.
8484   /// \return The last instruction of the sequence used to load the slice.
8485   SDValue loadSlice() const {
8486     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8487     const SDValue &OldBaseAddr = Origin->getBasePtr();
8488     SDValue BaseAddr = OldBaseAddr;
8489     // Get the offset in that chunk of bytes w.r.t. the endianess.
8490     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8491     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8492     if (Offset) {
8493       // BaseAddr = BaseAddr + Offset.
8494       EVT ArithType = BaseAddr.getValueType();
8495       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8496                               DAG->getConstant(Offset, ArithType));
8497     }
8498
8499     // Create the type of the loaded slice according to its size.
8500     EVT SliceType = getLoadedType();
8501
8502     // Create the load for the slice.
8503     SDValue LastInst = DAG->getLoad(
8504         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8505         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8506         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8507     // If the final type is not the same as the loaded type, this means that
8508     // we have to pad with zero. Create a zero extend for that.
8509     EVT FinalType = Inst->getValueType(0);
8510     if (SliceType != FinalType)
8511       LastInst =
8512           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8513     return LastInst;
8514   }
8515
8516   /// \brief Check if this slice can be merged with an expensive cross register
8517   /// bank copy. E.g.,
8518   /// i = load i32
8519   /// f = bitcast i32 i to float
8520   bool canMergeExpensiveCrossRegisterBankCopy() const {
8521     if (!Inst || !Inst->hasOneUse())
8522       return false;
8523     SDNode *Use = *Inst->use_begin();
8524     if (Use->getOpcode() != ISD::BITCAST)
8525       return false;
8526     assert(DAG && "Missing context");
8527     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8528     EVT ResVT = Use->getValueType(0);
8529     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8530     const TargetRegisterClass *ArgRC =
8531         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8532     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8533       return false;
8534
8535     // At this point, we know that we perform a cross-register-bank copy.
8536     // Check if it is expensive.
8537     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8538     // Assume bitcasts are cheap, unless both register classes do not
8539     // explicitly share a common sub class.
8540     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8541       return false;
8542
8543     // Check if it will be merged with the load.
8544     // 1. Check the alignment constraint.
8545     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8546         ResVT.getTypeForEVT(*DAG->getContext()));
8547
8548     if (RequiredAlignment > getAlignment())
8549       return false;
8550
8551     // 2. Check that the load is a legal operation for that type.
8552     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8553       return false;
8554
8555     // 3. Check that we do not have a zext in the way.
8556     if (Inst->getValueType(0) != getLoadedType())
8557       return false;
8558
8559     return true;
8560   }
8561 };
8562 }
8563
8564 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8565 /// \p UsedBits looks like 0..0 1..1 0..0.
8566 static bool areUsedBitsDense(const APInt &UsedBits) {
8567   // If all the bits are one, this is dense!
8568   if (UsedBits.isAllOnesValue())
8569     return true;
8570
8571   // Get rid of the unused bits on the right.
8572   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8573   // Get rid of the unused bits on the left.
8574   if (NarrowedUsedBits.countLeadingZeros())
8575     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8576   // Check that the chunk of bits is completely used.
8577   return NarrowedUsedBits.isAllOnesValue();
8578 }
8579
8580 /// \brief Check whether or not \p First and \p Second are next to each other
8581 /// in memory. This means that there is no hole between the bits loaded
8582 /// by \p First and the bits loaded by \p Second.
8583 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8584                                      const LoadedSlice &Second) {
8585   assert(First.Origin == Second.Origin && First.Origin &&
8586          "Unable to match different memory origins.");
8587   APInt UsedBits = First.getUsedBits();
8588   assert((UsedBits & Second.getUsedBits()) == 0 &&
8589          "Slices are not supposed to overlap.");
8590   UsedBits |= Second.getUsedBits();
8591   return areUsedBitsDense(UsedBits);
8592 }
8593
8594 /// \brief Adjust the \p GlobalLSCost according to the target
8595 /// paring capabilities and the layout of the slices.
8596 /// \pre \p GlobalLSCost should account for at least as many loads as
8597 /// there is in the slices in \p LoadedSlices.
8598 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8599                                  LoadedSlice::Cost &GlobalLSCost) {
8600   unsigned NumberOfSlices = LoadedSlices.size();
8601   // If there is less than 2 elements, no pairing is possible.
8602   if (NumberOfSlices < 2)
8603     return;
8604
8605   // Sort the slices so that elements that are likely to be next to each
8606   // other in memory are next to each other in the list.
8607   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8608             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8609     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8610     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8611   });
8612   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8613   // First (resp. Second) is the first (resp. Second) potentially candidate
8614   // to be placed in a paired load.
8615   const LoadedSlice *First = nullptr;
8616   const LoadedSlice *Second = nullptr;
8617   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8618                 // Set the beginning of the pair.
8619                                                            First = Second) {
8620
8621     Second = &LoadedSlices[CurrSlice];
8622
8623     // If First is NULL, it means we start a new pair.
8624     // Get to the next slice.
8625     if (!First)
8626       continue;
8627
8628     EVT LoadedType = First->getLoadedType();
8629
8630     // If the types of the slices are different, we cannot pair them.
8631     if (LoadedType != Second->getLoadedType())
8632       continue;
8633
8634     // Check if the target supplies paired loads for this type.
8635     unsigned RequiredAlignment = 0;
8636     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8637       // move to the next pair, this type is hopeless.
8638       Second = nullptr;
8639       continue;
8640     }
8641     // Check if we meet the alignment requirement.
8642     if (RequiredAlignment > First->getAlignment())
8643       continue;
8644
8645     // Check that both loads are next to each other in memory.
8646     if (!areSlicesNextToEachOther(*First, *Second))
8647       continue;
8648
8649     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8650     --GlobalLSCost.Loads;
8651     // Move to the next pair.
8652     Second = nullptr;
8653   }
8654 }
8655
8656 /// \brief Check the profitability of all involved LoadedSlice.
8657 /// Currently, it is considered profitable if there is exactly two
8658 /// involved slices (1) which are (2) next to each other in memory, and
8659 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8660 ///
8661 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8662 /// the elements themselves.
8663 ///
8664 /// FIXME: When the cost model will be mature enough, we can relax
8665 /// constraints (1) and (2).
8666 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8667                                 const APInt &UsedBits, bool ForCodeSize) {
8668   unsigned NumberOfSlices = LoadedSlices.size();
8669   if (StressLoadSlicing)
8670     return NumberOfSlices > 1;
8671
8672   // Check (1).
8673   if (NumberOfSlices != 2)
8674     return false;
8675
8676   // Check (2).
8677   if (!areUsedBitsDense(UsedBits))
8678     return false;
8679
8680   // Check (3).
8681   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8682   // The original code has one big load.
8683   OrigCost.Loads = 1;
8684   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8685     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8686     // Accumulate the cost of all the slices.
8687     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8688     GlobalSlicingCost += SliceCost;
8689
8690     // Account as cost in the original configuration the gain obtained
8691     // with the current slices.
8692     OrigCost.addSliceGain(LS);
8693   }
8694
8695   // If the target supports paired load, adjust the cost accordingly.
8696   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8697   return OrigCost > GlobalSlicingCost;
8698 }
8699
8700 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8701 /// operations, split it in the various pieces being extracted.
8702 ///
8703 /// This sort of thing is introduced by SROA.
8704 /// This slicing takes care not to insert overlapping loads.
8705 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8706 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8707   if (Level < AfterLegalizeDAG)
8708     return false;
8709
8710   LoadSDNode *LD = cast<LoadSDNode>(N);
8711   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8712       !LD->getValueType(0).isInteger())
8713     return false;
8714
8715   // Keep track of already used bits to detect overlapping values.
8716   // In that case, we will just abort the transformation.
8717   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8718
8719   SmallVector<LoadedSlice, 4> LoadedSlices;
8720
8721   // Check if this load is used as several smaller chunks of bits.
8722   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8723   // of computation for each trunc.
8724   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8725        UI != UIEnd; ++UI) {
8726     // Skip the uses of the chain.
8727     if (UI.getUse().getResNo() != 0)
8728       continue;
8729
8730     SDNode *User = *UI;
8731     unsigned Shift = 0;
8732
8733     // Check if this is a trunc(lshr).
8734     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8735         isa<ConstantSDNode>(User->getOperand(1))) {
8736       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8737       User = *User->use_begin();
8738     }
8739
8740     // At this point, User is a Truncate, iff we encountered, trunc or
8741     // trunc(lshr).
8742     if (User->getOpcode() != ISD::TRUNCATE)
8743       return false;
8744
8745     // The width of the type must be a power of 2 and greater than 8-bits.
8746     // Otherwise the load cannot be represented in LLVM IR.
8747     // Moreover, if we shifted with a non-8-bits multiple, the slice
8748     // will be across several bytes. We do not support that.
8749     unsigned Width = User->getValueSizeInBits(0);
8750     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8751       return 0;
8752
8753     // Build the slice for this chain of computations.
8754     LoadedSlice LS(User, LD, Shift, &DAG);
8755     APInt CurrentUsedBits = LS.getUsedBits();
8756
8757     // Check if this slice overlaps with another.
8758     if ((CurrentUsedBits & UsedBits) != 0)
8759       return false;
8760     // Update the bits used globally.
8761     UsedBits |= CurrentUsedBits;
8762
8763     // Check if the new slice would be legal.
8764     if (!LS.isLegal())
8765       return false;
8766
8767     // Record the slice.
8768     LoadedSlices.push_back(LS);
8769   }
8770
8771   // Abort slicing if it does not seem to be profitable.
8772   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8773     return false;
8774
8775   ++SlicedLoads;
8776
8777   // Rewrite each chain to use an independent load.
8778   // By construction, each chain can be represented by a unique load.
8779
8780   // Prepare the argument for the new token factor for all the slices.
8781   SmallVector<SDValue, 8> ArgChains;
8782   for (SmallVectorImpl<LoadedSlice>::const_iterator
8783            LSIt = LoadedSlices.begin(),
8784            LSItEnd = LoadedSlices.end();
8785        LSIt != LSItEnd; ++LSIt) {
8786     SDValue SliceInst = LSIt->loadSlice();
8787     CombineTo(LSIt->Inst, SliceInst, true);
8788     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8789       SliceInst = SliceInst.getOperand(0);
8790     assert(SliceInst->getOpcode() == ISD::LOAD &&
8791            "It takes more than a zext to get to the loaded slice!!");
8792     ArgChains.push_back(SliceInst.getValue(1));
8793   }
8794
8795   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8796                               ArgChains);
8797   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8798   return true;
8799 }
8800
8801 /// Check to see if V is (and load (ptr), imm), where the load is having
8802 /// specific bytes cleared out.  If so, return the byte size being masked out
8803 /// and the shift amount.
8804 static std::pair<unsigned, unsigned>
8805 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8806   std::pair<unsigned, unsigned> Result(0, 0);
8807
8808   // Check for the structure we're looking for.
8809   if (V->getOpcode() != ISD::AND ||
8810       !isa<ConstantSDNode>(V->getOperand(1)) ||
8811       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8812     return Result;
8813
8814   // Check the chain and pointer.
8815   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8816   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8817
8818   // The store should be chained directly to the load or be an operand of a
8819   // tokenfactor.
8820   if (LD == Chain.getNode())
8821     ; // ok.
8822   else if (Chain->getOpcode() != ISD::TokenFactor)
8823     return Result; // Fail.
8824   else {
8825     bool isOk = false;
8826     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8827       if (Chain->getOperand(i).getNode() == LD) {
8828         isOk = true;
8829         break;
8830       }
8831     if (!isOk) return Result;
8832   }
8833
8834   // This only handles simple types.
8835   if (V.getValueType() != MVT::i16 &&
8836       V.getValueType() != MVT::i32 &&
8837       V.getValueType() != MVT::i64)
8838     return Result;
8839
8840   // Check the constant mask.  Invert it so that the bits being masked out are
8841   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8842   // follow the sign bit for uniformity.
8843   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8844   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8845   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8846   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8847   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8848   if (NotMaskLZ == 64) return Result;  // All zero mask.
8849
8850   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8851   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8852     return Result;
8853
8854   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8855   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8856     NotMaskLZ -= 64-V.getValueSizeInBits();
8857
8858   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8859   switch (MaskedBytes) {
8860   case 1:
8861   case 2:
8862   case 4: break;
8863   default: return Result; // All one mask, or 5-byte mask.
8864   }
8865
8866   // Verify that the first bit starts at a multiple of mask so that the access
8867   // is aligned the same as the access width.
8868   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8869
8870   Result.first = MaskedBytes;
8871   Result.second = NotMaskTZ/8;
8872   return Result;
8873 }
8874
8875
8876 /// Check to see if IVal is something that provides a value as specified by
8877 /// MaskInfo. If so, replace the specified store with a narrower store of
8878 /// truncated IVal.
8879 static SDNode *
8880 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8881                                 SDValue IVal, StoreSDNode *St,
8882                                 DAGCombiner *DC) {
8883   unsigned NumBytes = MaskInfo.first;
8884   unsigned ByteShift = MaskInfo.second;
8885   SelectionDAG &DAG = DC->getDAG();
8886
8887   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8888   // that uses this.  If not, this is not a replacement.
8889   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8890                                   ByteShift*8, (ByteShift+NumBytes)*8);
8891   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8892
8893   // Check that it is legal on the target to do this.  It is legal if the new
8894   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8895   // legalization.
8896   MVT VT = MVT::getIntegerVT(NumBytes*8);
8897   if (!DC->isTypeLegal(VT))
8898     return nullptr;
8899
8900   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8901   // shifted by ByteShift and truncated down to NumBytes.
8902   if (ByteShift)
8903     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8904                        DAG.getConstant(ByteShift*8,
8905                                     DC->getShiftAmountTy(IVal.getValueType())));
8906
8907   // Figure out the offset for the store and the alignment of the access.
8908   unsigned StOffset;
8909   unsigned NewAlign = St->getAlignment();
8910
8911   if (DAG.getTargetLoweringInfo().isLittleEndian())
8912     StOffset = ByteShift;
8913   else
8914     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8915
8916   SDValue Ptr = St->getBasePtr();
8917   if (StOffset) {
8918     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8919                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8920     NewAlign = MinAlign(NewAlign, StOffset);
8921   }
8922
8923   // Truncate down to the new size.
8924   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8925
8926   ++OpsNarrowed;
8927   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8928                       St->getPointerInfo().getWithOffset(StOffset),
8929                       false, false, NewAlign).getNode();
8930 }
8931
8932
8933 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8934 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8935 /// narrowing the load and store if it would end up being a win for performance
8936 /// or code size.
8937 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8938   StoreSDNode *ST  = cast<StoreSDNode>(N);
8939   if (ST->isVolatile())
8940     return SDValue();
8941
8942   SDValue Chain = ST->getChain();
8943   SDValue Value = ST->getValue();
8944   SDValue Ptr   = ST->getBasePtr();
8945   EVT VT = Value.getValueType();
8946
8947   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8948     return SDValue();
8949
8950   unsigned Opc = Value.getOpcode();
8951
8952   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8953   // is a byte mask indicating a consecutive number of bytes, check to see if
8954   // Y is known to provide just those bytes.  If so, we try to replace the
8955   // load + replace + store sequence with a single (narrower) store, which makes
8956   // the load dead.
8957   if (Opc == ISD::OR) {
8958     std::pair<unsigned, unsigned> MaskedLoad;
8959     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8960     if (MaskedLoad.first)
8961       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8962                                                   Value.getOperand(1), ST,this))
8963         return SDValue(NewST, 0);
8964
8965     // Or is commutative, so try swapping X and Y.
8966     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8967     if (MaskedLoad.first)
8968       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8969                                                   Value.getOperand(0), ST,this))
8970         return SDValue(NewST, 0);
8971   }
8972
8973   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8974       Value.getOperand(1).getOpcode() != ISD::Constant)
8975     return SDValue();
8976
8977   SDValue N0 = Value.getOperand(0);
8978   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8979       Chain == SDValue(N0.getNode(), 1)) {
8980     LoadSDNode *LD = cast<LoadSDNode>(N0);
8981     if (LD->getBasePtr() != Ptr ||
8982         LD->getPointerInfo().getAddrSpace() !=
8983         ST->getPointerInfo().getAddrSpace())
8984       return SDValue();
8985
8986     // Find the type to narrow it the load / op / store to.
8987     SDValue N1 = Value.getOperand(1);
8988     unsigned BitWidth = N1.getValueSizeInBits();
8989     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8990     if (Opc == ISD::AND)
8991       Imm ^= APInt::getAllOnesValue(BitWidth);
8992     if (Imm == 0 || Imm.isAllOnesValue())
8993       return SDValue();
8994     unsigned ShAmt = Imm.countTrailingZeros();
8995     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8996     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8997     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8998     while (NewBW < BitWidth &&
8999            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9000              TLI.isNarrowingProfitable(VT, NewVT))) {
9001       NewBW = NextPowerOf2(NewBW);
9002       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9003     }
9004     if (NewBW >= BitWidth)
9005       return SDValue();
9006
9007     // If the lsb changed does not start at the type bitwidth boundary,
9008     // start at the previous one.
9009     if (ShAmt % NewBW)
9010       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9011     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9012                                    std::min(BitWidth, ShAmt + NewBW));
9013     if ((Imm & Mask) == Imm) {
9014       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9015       if (Opc == ISD::AND)
9016         NewImm ^= APInt::getAllOnesValue(NewBW);
9017       uint64_t PtrOff = ShAmt / 8;
9018       // For big endian targets, we need to adjust the offset to the pointer to
9019       // load the correct bytes.
9020       if (TLI.isBigEndian())
9021         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9022
9023       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9024       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9025       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9026         return SDValue();
9027
9028       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9029                                    Ptr.getValueType(), Ptr,
9030                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9031       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9032                                   LD->getChain(), NewPtr,
9033                                   LD->getPointerInfo().getWithOffset(PtrOff),
9034                                   LD->isVolatile(), LD->isNonTemporal(),
9035                                   LD->isInvariant(), NewAlign,
9036                                   LD->getAAInfo());
9037       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9038                                    DAG.getConstant(NewImm, NewVT));
9039       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9040                                    NewVal, NewPtr,
9041                                    ST->getPointerInfo().getWithOffset(PtrOff),
9042                                    false, false, NewAlign);
9043
9044       AddToWorklist(NewPtr.getNode());
9045       AddToWorklist(NewLD.getNode());
9046       AddToWorklist(NewVal.getNode());
9047       WorklistRemover DeadNodes(*this);
9048       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9049       ++OpsNarrowed;
9050       return NewST;
9051     }
9052   }
9053
9054   return SDValue();
9055 }
9056
9057 /// For a given floating point load / store pair, if the load value isn't used
9058 /// by any other operations, then consider transforming the pair to integer
9059 /// load / store operations if the target deems the transformation profitable.
9060 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9061   StoreSDNode *ST  = cast<StoreSDNode>(N);
9062   SDValue Chain = ST->getChain();
9063   SDValue Value = ST->getValue();
9064   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9065       Value.hasOneUse() &&
9066       Chain == SDValue(Value.getNode(), 1)) {
9067     LoadSDNode *LD = cast<LoadSDNode>(Value);
9068     EVT VT = LD->getMemoryVT();
9069     if (!VT.isFloatingPoint() ||
9070         VT != ST->getMemoryVT() ||
9071         LD->isNonTemporal() ||
9072         ST->isNonTemporal() ||
9073         LD->getPointerInfo().getAddrSpace() != 0 ||
9074         ST->getPointerInfo().getAddrSpace() != 0)
9075       return SDValue();
9076
9077     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9078     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9079         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9080         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9081         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9082       return SDValue();
9083
9084     unsigned LDAlign = LD->getAlignment();
9085     unsigned STAlign = ST->getAlignment();
9086     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9087     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9088     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9089       return SDValue();
9090
9091     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9092                                 LD->getChain(), LD->getBasePtr(),
9093                                 LD->getPointerInfo(),
9094                                 false, false, false, LDAlign);
9095
9096     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9097                                  NewLD, ST->getBasePtr(),
9098                                  ST->getPointerInfo(),
9099                                  false, false, STAlign);
9100
9101     AddToWorklist(NewLD.getNode());
9102     AddToWorklist(NewST.getNode());
9103     WorklistRemover DeadNodes(*this);
9104     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9105     ++LdStFP2Int;
9106     return NewST;
9107   }
9108
9109   return SDValue();
9110 }
9111
9112 /// Helper struct to parse and store a memory address as base + index + offset.
9113 /// We ignore sign extensions when it is safe to do so.
9114 /// The following two expressions are not equivalent. To differentiate we need
9115 /// to store whether there was a sign extension involved in the index
9116 /// computation.
9117 ///  (load (i64 add (i64 copyfromreg %c)
9118 ///                 (i64 signextend (add (i8 load %index)
9119 ///                                      (i8 1))))
9120 /// vs
9121 ///
9122 /// (load (i64 add (i64 copyfromreg %c)
9123 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9124 ///                                         (i32 1)))))
9125 struct BaseIndexOffset {
9126   SDValue Base;
9127   SDValue Index;
9128   int64_t Offset;
9129   bool IsIndexSignExt;
9130
9131   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9132
9133   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9134                   bool IsIndexSignExt) :
9135     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9136
9137   bool equalBaseIndex(const BaseIndexOffset &Other) {
9138     return Other.Base == Base && Other.Index == Index &&
9139       Other.IsIndexSignExt == IsIndexSignExt;
9140   }
9141
9142   /// Parses tree in Ptr for base, index, offset addresses.
9143   static BaseIndexOffset match(SDValue Ptr) {
9144     bool IsIndexSignExt = false;
9145
9146     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9147     // instruction, then it could be just the BASE or everything else we don't
9148     // know how to handle. Just use Ptr as BASE and give up.
9149     if (Ptr->getOpcode() != ISD::ADD)
9150       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9151
9152     // We know that we have at least an ADD instruction. Try to pattern match
9153     // the simple case of BASE + OFFSET.
9154     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9155       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9156       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9157                               IsIndexSignExt);
9158     }
9159
9160     // Inside a loop the current BASE pointer is calculated using an ADD and a
9161     // MUL instruction. In this case Ptr is the actual BASE pointer.
9162     // (i64 add (i64 %array_ptr)
9163     //          (i64 mul (i64 %induction_var)
9164     //                   (i64 %element_size)))
9165     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9166       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9167
9168     // Look at Base + Index + Offset cases.
9169     SDValue Base = Ptr->getOperand(0);
9170     SDValue IndexOffset = Ptr->getOperand(1);
9171
9172     // Skip signextends.
9173     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9174       IndexOffset = IndexOffset->getOperand(0);
9175       IsIndexSignExt = true;
9176     }
9177
9178     // Either the case of Base + Index (no offset) or something else.
9179     if (IndexOffset->getOpcode() != ISD::ADD)
9180       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9181
9182     // Now we have the case of Base + Index + offset.
9183     SDValue Index = IndexOffset->getOperand(0);
9184     SDValue Offset = IndexOffset->getOperand(1);
9185
9186     if (!isa<ConstantSDNode>(Offset))
9187       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9188
9189     // Ignore signextends.
9190     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9191       Index = Index->getOperand(0);
9192       IsIndexSignExt = true;
9193     } else IsIndexSignExt = false;
9194
9195     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9196     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9197   }
9198 };
9199
9200 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9201 /// is located in a sequence of memory operations connected by a chain.
9202 struct MemOpLink {
9203   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9204     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9205   // Ptr to the mem node.
9206   LSBaseSDNode *MemNode;
9207   // Offset from the base ptr.
9208   int64_t OffsetFromBase;
9209   // What is the sequence number of this mem node.
9210   // Lowest mem operand in the DAG starts at zero.
9211   unsigned SequenceNum;
9212 };
9213
9214 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9215   EVT MemVT = St->getMemoryVT();
9216   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9217   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9218     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9219
9220   // Don't merge vectors into wider inputs.
9221   if (MemVT.isVector() || !MemVT.isSimple())
9222     return false;
9223
9224   // Perform an early exit check. Do not bother looking at stored values that
9225   // are not constants or loads.
9226   SDValue StoredVal = St->getValue();
9227   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9228   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9229       !IsLoadSrc)
9230     return false;
9231
9232   // Only look at ends of store sequences.
9233   SDValue Chain = SDValue(St, 0);
9234   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9235     return false;
9236
9237   // This holds the base pointer, index, and the offset in bytes from the base
9238   // pointer.
9239   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9240
9241   // We must have a base and an offset.
9242   if (!BasePtr.Base.getNode())
9243     return false;
9244
9245   // Do not handle stores to undef base pointers.
9246   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9247     return false;
9248
9249   // Save the LoadSDNodes that we find in the chain.
9250   // We need to make sure that these nodes do not interfere with
9251   // any of the store nodes.
9252   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9253
9254   // Save the StoreSDNodes that we find in the chain.
9255   SmallVector<MemOpLink, 8> StoreNodes;
9256
9257   // Walk up the chain and look for nodes with offsets from the same
9258   // base pointer. Stop when reaching an instruction with a different kind
9259   // or instruction which has a different base pointer.
9260   unsigned Seq = 0;
9261   StoreSDNode *Index = St;
9262   while (Index) {
9263     // If the chain has more than one use, then we can't reorder the mem ops.
9264     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9265       break;
9266
9267     // Find the base pointer and offset for this memory node.
9268     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9269
9270     // Check that the base pointer is the same as the original one.
9271     if (!Ptr.equalBaseIndex(BasePtr))
9272       break;
9273
9274     // Check that the alignment is the same.
9275     if (Index->getAlignment() != St->getAlignment())
9276       break;
9277
9278     // The memory operands must not be volatile.
9279     if (Index->isVolatile() || Index->isIndexed())
9280       break;
9281
9282     // No truncation.
9283     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9284       if (St->isTruncatingStore())
9285         break;
9286
9287     // The stored memory type must be the same.
9288     if (Index->getMemoryVT() != MemVT)
9289       break;
9290
9291     // We do not allow unaligned stores because we want to prevent overriding
9292     // stores.
9293     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9294       break;
9295
9296     // We found a potential memory operand to merge.
9297     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9298
9299     // Find the next memory operand in the chain. If the next operand in the
9300     // chain is a store then move up and continue the scan with the next
9301     // memory operand. If the next operand is a load save it and use alias
9302     // information to check if it interferes with anything.
9303     SDNode *NextInChain = Index->getChain().getNode();
9304     while (1) {
9305       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9306         // We found a store node. Use it for the next iteration.
9307         Index = STn;
9308         break;
9309       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9310         if (Ldn->isVolatile()) {
9311           Index = nullptr;
9312           break;
9313         }
9314
9315         // Save the load node for later. Continue the scan.
9316         AliasLoadNodes.push_back(Ldn);
9317         NextInChain = Ldn->getChain().getNode();
9318         continue;
9319       } else {
9320         Index = nullptr;
9321         break;
9322       }
9323     }
9324   }
9325
9326   // Check if there is anything to merge.
9327   if (StoreNodes.size() < 2)
9328     return false;
9329
9330   // Sort the memory operands according to their distance from the base pointer.
9331   std::sort(StoreNodes.begin(), StoreNodes.end(),
9332             [](MemOpLink LHS, MemOpLink RHS) {
9333     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9334            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9335             LHS.SequenceNum > RHS.SequenceNum);
9336   });
9337
9338   // Scan the memory operations on the chain and find the first non-consecutive
9339   // store memory address.
9340   unsigned LastConsecutiveStore = 0;
9341   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9342   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9343
9344     // Check that the addresses are consecutive starting from the second
9345     // element in the list of stores.
9346     if (i > 0) {
9347       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9348       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9349         break;
9350     }
9351
9352     bool Alias = false;
9353     // Check if this store interferes with any of the loads that we found.
9354     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9355       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9356         Alias = true;
9357         break;
9358       }
9359     // We found a load that alias with this store. Stop the sequence.
9360     if (Alias)
9361       break;
9362
9363     // Mark this node as useful.
9364     LastConsecutiveStore = i;
9365   }
9366
9367   // The node with the lowest store address.
9368   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9369
9370   // Store the constants into memory as one consecutive store.
9371   if (!IsLoadSrc) {
9372     unsigned LastLegalType = 0;
9373     unsigned LastLegalVectorType = 0;
9374     bool NonZero = false;
9375     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9376       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9377       SDValue StoredVal = St->getValue();
9378
9379       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9380         NonZero |= !C->isNullValue();
9381       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9382         NonZero |= !C->getConstantFPValue()->isNullValue();
9383       } else {
9384         // Non-constant.
9385         break;
9386       }
9387
9388       // Find a legal type for the constant store.
9389       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9390       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9391       if (TLI.isTypeLegal(StoreTy))
9392         LastLegalType = i+1;
9393       // Or check whether a truncstore is legal.
9394       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9395                TargetLowering::TypePromoteInteger) {
9396         EVT LegalizedStoredValueTy =
9397           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9398         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9399           LastLegalType = i+1;
9400       }
9401
9402       // Find a legal type for the vector store.
9403       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9404       if (TLI.isTypeLegal(Ty))
9405         LastLegalVectorType = i + 1;
9406     }
9407
9408     // We only use vectors if the constant is known to be zero and the
9409     // function is not marked with the noimplicitfloat attribute.
9410     if (NonZero || NoVectors)
9411       LastLegalVectorType = 0;
9412
9413     // Check if we found a legal integer type to store.
9414     if (LastLegalType == 0 && LastLegalVectorType == 0)
9415       return false;
9416
9417     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9418     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9419
9420     // Make sure we have something to merge.
9421     if (NumElem < 2)
9422       return false;
9423
9424     unsigned EarliestNodeUsed = 0;
9425     for (unsigned i=0; i < NumElem; ++i) {
9426       // Find a chain for the new wide-store operand. Notice that some
9427       // of the store nodes that we found may not be selected for inclusion
9428       // in the wide store. The chain we use needs to be the chain of the
9429       // earliest store node which is *used* and replaced by the wide store.
9430       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9431         EarliestNodeUsed = i;
9432     }
9433
9434     // The earliest Node in the DAG.
9435     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9436     SDLoc DL(StoreNodes[0].MemNode);
9437
9438     SDValue StoredVal;
9439     if (UseVector) {
9440       // Find a legal type for the vector store.
9441       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9442       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9443       StoredVal = DAG.getConstant(0, Ty);
9444     } else {
9445       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9446       APInt StoreInt(StoreBW, 0);
9447
9448       // Construct a single integer constant which is made of the smaller
9449       // constant inputs.
9450       bool IsLE = TLI.isLittleEndian();
9451       for (unsigned i = 0; i < NumElem ; ++i) {
9452         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9453         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9454         SDValue Val = St->getValue();
9455         StoreInt<<=ElementSizeBytes*8;
9456         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9457           StoreInt|=C->getAPIntValue().zext(StoreBW);
9458         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9459           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9460         } else {
9461           assert(false && "Invalid constant element type");
9462         }
9463       }
9464
9465       // Create the new Load and Store operations.
9466       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9467       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9468     }
9469
9470     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9471                                     FirstInChain->getBasePtr(),
9472                                     FirstInChain->getPointerInfo(),
9473                                     false, false,
9474                                     FirstInChain->getAlignment());
9475
9476     // Replace the first store with the new store
9477     CombineTo(EarliestOp, NewStore);
9478     // Erase all other stores.
9479     for (unsigned i = 0; i < NumElem ; ++i) {
9480       if (StoreNodes[i].MemNode == EarliestOp)
9481         continue;
9482       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9483       // ReplaceAllUsesWith will replace all uses that existed when it was
9484       // called, but graph optimizations may cause new ones to appear. For
9485       // example, the case in pr14333 looks like
9486       //
9487       //  St's chain -> St -> another store -> X
9488       //
9489       // And the only difference from St to the other store is the chain.
9490       // When we change it's chain to be St's chain they become identical,
9491       // get CSEed and the net result is that X is now a use of St.
9492       // Since we know that St is redundant, just iterate.
9493       while (!St->use_empty())
9494         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9495       deleteAndRecombine(St);
9496     }
9497
9498     return true;
9499   }
9500
9501   // Below we handle the case of multiple consecutive stores that
9502   // come from multiple consecutive loads. We merge them into a single
9503   // wide load and a single wide store.
9504
9505   // Look for load nodes which are used by the stored values.
9506   SmallVector<MemOpLink, 8> LoadNodes;
9507
9508   // Find acceptable loads. Loads need to have the same chain (token factor),
9509   // must not be zext, volatile, indexed, and they must be consecutive.
9510   BaseIndexOffset LdBasePtr;
9511   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9512     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9513     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9514     if (!Ld) break;
9515
9516     // Loads must only have one use.
9517     if (!Ld->hasNUsesOfValue(1, 0))
9518       break;
9519
9520     // Check that the alignment is the same as the stores.
9521     if (Ld->getAlignment() != St->getAlignment())
9522       break;
9523
9524     // The memory operands must not be volatile.
9525     if (Ld->isVolatile() || Ld->isIndexed())
9526       break;
9527
9528     // We do not accept ext loads.
9529     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9530       break;
9531
9532     // The stored memory type must be the same.
9533     if (Ld->getMemoryVT() != MemVT)
9534       break;
9535
9536     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9537     // If this is not the first ptr that we check.
9538     if (LdBasePtr.Base.getNode()) {
9539       // The base ptr must be the same.
9540       if (!LdPtr.equalBaseIndex(LdBasePtr))
9541         break;
9542     } else {
9543       // Check that all other base pointers are the same as this one.
9544       LdBasePtr = LdPtr;
9545     }
9546
9547     // We found a potential memory operand to merge.
9548     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9549   }
9550
9551   if (LoadNodes.size() < 2)
9552     return false;
9553
9554   // If we have load/store pair instructions and we only have two values,
9555   // don't bother.
9556   unsigned RequiredAlignment;
9557   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9558       St->getAlignment() >= RequiredAlignment)
9559     return false;
9560
9561   // Scan the memory operations on the chain and find the first non-consecutive
9562   // load memory address. These variables hold the index in the store node
9563   // array.
9564   unsigned LastConsecutiveLoad = 0;
9565   // This variable refers to the size and not index in the array.
9566   unsigned LastLegalVectorType = 0;
9567   unsigned LastLegalIntegerType = 0;
9568   StartAddress = LoadNodes[0].OffsetFromBase;
9569   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9570   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9571     // All loads much share the same chain.
9572     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9573       break;
9574
9575     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9576     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9577       break;
9578     LastConsecutiveLoad = i;
9579
9580     // Find a legal type for the vector store.
9581     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9582     if (TLI.isTypeLegal(StoreTy))
9583       LastLegalVectorType = i + 1;
9584
9585     // Find a legal type for the integer store.
9586     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9587     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9588     if (TLI.isTypeLegal(StoreTy))
9589       LastLegalIntegerType = i + 1;
9590     // Or check whether a truncstore and extload is legal.
9591     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9592              TargetLowering::TypePromoteInteger) {
9593       EVT LegalizedStoredValueTy =
9594         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9595       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9596           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9597           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9598           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9599         LastLegalIntegerType = i+1;
9600     }
9601   }
9602
9603   // Only use vector types if the vector type is larger than the integer type.
9604   // If they are the same, use integers.
9605   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9606   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9607
9608   // We add +1 here because the LastXXX variables refer to location while
9609   // the NumElem refers to array/index size.
9610   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9611   NumElem = std::min(LastLegalType, NumElem);
9612
9613   if (NumElem < 2)
9614     return false;
9615
9616   // The earliest Node in the DAG.
9617   unsigned EarliestNodeUsed = 0;
9618   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9619   for (unsigned i=1; i<NumElem; ++i) {
9620     // Find a chain for the new wide-store operand. Notice that some
9621     // of the store nodes that we found may not be selected for inclusion
9622     // in the wide store. The chain we use needs to be the chain of the
9623     // earliest store node which is *used* and replaced by the wide store.
9624     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9625       EarliestNodeUsed = i;
9626   }
9627
9628   // Find if it is better to use vectors or integers to load and store
9629   // to memory.
9630   EVT JointMemOpVT;
9631   if (UseVectorTy) {
9632     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9633   } else {
9634     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9635     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9636   }
9637
9638   SDLoc LoadDL(LoadNodes[0].MemNode);
9639   SDLoc StoreDL(StoreNodes[0].MemNode);
9640
9641   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9642   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9643                                 FirstLoad->getChain(),
9644                                 FirstLoad->getBasePtr(),
9645                                 FirstLoad->getPointerInfo(),
9646                                 false, false, false,
9647                                 FirstLoad->getAlignment());
9648
9649   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9650                                   FirstInChain->getBasePtr(),
9651                                   FirstInChain->getPointerInfo(), false, false,
9652                                   FirstInChain->getAlignment());
9653
9654   // Replace one of the loads with the new load.
9655   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9656   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9657                                 SDValue(NewLoad.getNode(), 1));
9658
9659   // Remove the rest of the load chains.
9660   for (unsigned i = 1; i < NumElem ; ++i) {
9661     // Replace all chain users of the old load nodes with the chain of the new
9662     // load node.
9663     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9664     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9665   }
9666
9667   // Replace the first store with the new store.
9668   CombineTo(EarliestOp, NewStore);
9669   // Erase all other stores.
9670   for (unsigned i = 0; i < NumElem ; ++i) {
9671     // Remove all Store nodes.
9672     if (StoreNodes[i].MemNode == EarliestOp)
9673       continue;
9674     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9675     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9676     deleteAndRecombine(St);
9677   }
9678
9679   return true;
9680 }
9681
9682 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9683   StoreSDNode *ST  = cast<StoreSDNode>(N);
9684   SDValue Chain = ST->getChain();
9685   SDValue Value = ST->getValue();
9686   SDValue Ptr   = ST->getBasePtr();
9687
9688   // If this is a store of a bit convert, store the input value if the
9689   // resultant store does not need a higher alignment than the original.
9690   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9691       ST->isUnindexed()) {
9692     unsigned OrigAlign = ST->getAlignment();
9693     EVT SVT = Value.getOperand(0).getValueType();
9694     unsigned Align = TLI.getDataLayout()->
9695       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9696     if (Align <= OrigAlign &&
9697         ((!LegalOperations && !ST->isVolatile()) ||
9698          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9699       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9700                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9701                           ST->isNonTemporal(), OrigAlign,
9702                           ST->getAAInfo());
9703   }
9704
9705   // Turn 'store undef, Ptr' -> nothing.
9706   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9707     return Chain;
9708
9709   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9710   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9711     // NOTE: If the original store is volatile, this transform must not increase
9712     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9713     // processor operation but an i64 (which is not legal) requires two.  So the
9714     // transform should not be done in this case.
9715     if (Value.getOpcode() != ISD::TargetConstantFP) {
9716       SDValue Tmp;
9717       switch (CFP->getSimpleValueType(0).SimpleTy) {
9718       default: llvm_unreachable("Unknown FP type");
9719       case MVT::f16:    // We don't do this for these yet.
9720       case MVT::f80:
9721       case MVT::f128:
9722       case MVT::ppcf128:
9723         break;
9724       case MVT::f32:
9725         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9726             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9727           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9728                               bitcastToAPInt().getZExtValue(), MVT::i32);
9729           return DAG.getStore(Chain, SDLoc(N), Tmp,
9730                               Ptr, ST->getMemOperand());
9731         }
9732         break;
9733       case MVT::f64:
9734         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9735              !ST->isVolatile()) ||
9736             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9737           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9738                                 getZExtValue(), MVT::i64);
9739           return DAG.getStore(Chain, SDLoc(N), Tmp,
9740                               Ptr, ST->getMemOperand());
9741         }
9742
9743         if (!ST->isVolatile() &&
9744             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9745           // Many FP stores are not made apparent until after legalize, e.g. for
9746           // argument passing.  Since this is so common, custom legalize the
9747           // 64-bit integer store into two 32-bit stores.
9748           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9749           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9750           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9751           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9752
9753           unsigned Alignment = ST->getAlignment();
9754           bool isVolatile = ST->isVolatile();
9755           bool isNonTemporal = ST->isNonTemporal();
9756           AAMDNodes AAInfo = ST->getAAInfo();
9757
9758           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9759                                      Ptr, ST->getPointerInfo(),
9760                                      isVolatile, isNonTemporal,
9761                                      ST->getAlignment(), AAInfo);
9762           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9763                             DAG.getConstant(4, Ptr.getValueType()));
9764           Alignment = MinAlign(Alignment, 4U);
9765           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9766                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9767                                      isVolatile, isNonTemporal,
9768                                      Alignment, AAInfo);
9769           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9770                              St0, St1);
9771         }
9772
9773         break;
9774       }
9775     }
9776   }
9777
9778   // Try to infer better alignment information than the store already has.
9779   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9780     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9781       if (Align > ST->getAlignment())
9782         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9783                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9784                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9785                                  ST->getAAInfo());
9786     }
9787   }
9788
9789   // Try transforming a pair floating point load / store ops to integer
9790   // load / store ops.
9791   SDValue NewST = TransformFPLoadStorePair(N);
9792   if (NewST.getNode())
9793     return NewST;
9794
9795   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9796                                                   : DAG.getSubtarget().useAA();
9797 #ifndef NDEBUG
9798   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9799       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9800     UseAA = false;
9801 #endif
9802   if (UseAA && ST->isUnindexed()) {
9803     // Walk up chain skipping non-aliasing memory nodes.
9804     SDValue BetterChain = FindBetterChain(N, Chain);
9805
9806     // If there is a better chain.
9807     if (Chain != BetterChain) {
9808       SDValue ReplStore;
9809
9810       // Replace the chain to avoid dependency.
9811       if (ST->isTruncatingStore()) {
9812         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9813                                       ST->getMemoryVT(), ST->getMemOperand());
9814       } else {
9815         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9816                                  ST->getMemOperand());
9817       }
9818
9819       // Create token to keep both nodes around.
9820       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9821                                   MVT::Other, Chain, ReplStore);
9822
9823       // Make sure the new and old chains are cleaned up.
9824       AddToWorklist(Token.getNode());
9825
9826       // Don't add users to work list.
9827       return CombineTo(N, Token, false);
9828     }
9829   }
9830
9831   // Try transforming N to an indexed store.
9832   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9833     return SDValue(N, 0);
9834
9835   // FIXME: is there such a thing as a truncating indexed store?
9836   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9837       Value.getValueType().isInteger()) {
9838     // See if we can simplify the input to this truncstore with knowledge that
9839     // only the low bits are being used.  For example:
9840     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9841     SDValue Shorter =
9842       GetDemandedBits(Value,
9843                       APInt::getLowBitsSet(
9844                         Value.getValueType().getScalarType().getSizeInBits(),
9845                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9846     AddToWorklist(Value.getNode());
9847     if (Shorter.getNode())
9848       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9849                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9850
9851     // Otherwise, see if we can simplify the operation with
9852     // SimplifyDemandedBits, which only works if the value has a single use.
9853     if (SimplifyDemandedBits(Value,
9854                         APInt::getLowBitsSet(
9855                           Value.getValueType().getScalarType().getSizeInBits(),
9856                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9857       return SDValue(N, 0);
9858   }
9859
9860   // If this is a load followed by a store to the same location, then the store
9861   // is dead/noop.
9862   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9863     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9864         ST->isUnindexed() && !ST->isVolatile() &&
9865         // There can't be any side effects between the load and store, such as
9866         // a call or store.
9867         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9868       // The store is dead, remove it.
9869       return Chain;
9870     }
9871   }
9872
9873   // If this is a store followed by a store with the same value to the same
9874   // location, then the store is dead/noop.
9875   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9876     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9877         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9878         ST1->isUnindexed() && !ST1->isVolatile()) {
9879       // The store is dead, remove it.
9880       return Chain;
9881     }
9882   }
9883
9884   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9885   // truncating store.  We can do this even if this is already a truncstore.
9886   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9887       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9888       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9889                             ST->getMemoryVT())) {
9890     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9891                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9892   }
9893
9894   // Only perform this optimization before the types are legal, because we
9895   // don't want to perform this optimization on every DAGCombine invocation.
9896   if (!LegalTypes) {
9897     bool EverChanged = false;
9898
9899     do {
9900       // There can be multiple store sequences on the same chain.
9901       // Keep trying to merge store sequences until we are unable to do so
9902       // or until we merge the last store on the chain.
9903       bool Changed = MergeConsecutiveStores(ST);
9904       EverChanged |= Changed;
9905       if (!Changed) break;
9906     } while (ST->getOpcode() != ISD::DELETED_NODE);
9907
9908     if (EverChanged)
9909       return SDValue(N, 0);
9910   }
9911
9912   return ReduceLoadOpStoreWidth(N);
9913 }
9914
9915 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9916   SDValue InVec = N->getOperand(0);
9917   SDValue InVal = N->getOperand(1);
9918   SDValue EltNo = N->getOperand(2);
9919   SDLoc dl(N);
9920
9921   // If the inserted element is an UNDEF, just use the input vector.
9922   if (InVal.getOpcode() == ISD::UNDEF)
9923     return InVec;
9924
9925   EVT VT = InVec.getValueType();
9926
9927   // If we can't generate a legal BUILD_VECTOR, exit
9928   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9929     return SDValue();
9930
9931   // Check that we know which element is being inserted
9932   if (!isa<ConstantSDNode>(EltNo))
9933     return SDValue();
9934   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9935
9936   // Canonicalize insert_vector_elt dag nodes.
9937   // Example:
9938   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9939   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9940   //
9941   // Do this only if the child insert_vector node has one use; also
9942   // do this only if indices are both constants and Idx1 < Idx0.
9943   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9944       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9945     unsigned OtherElt =
9946       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9947     if (Elt < OtherElt) {
9948       // Swap nodes.
9949       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9950                                   InVec.getOperand(0), InVal, EltNo);
9951       AddToWorklist(NewOp.getNode());
9952       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9953                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9954     }
9955   }
9956
9957   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9958   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9959   // vector elements.
9960   SmallVector<SDValue, 8> Ops;
9961   // Do not combine these two vectors if the output vector will not replace
9962   // the input vector.
9963   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9964     Ops.append(InVec.getNode()->op_begin(),
9965                InVec.getNode()->op_end());
9966   } else if (InVec.getOpcode() == ISD::UNDEF) {
9967     unsigned NElts = VT.getVectorNumElements();
9968     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9969   } else {
9970     return SDValue();
9971   }
9972
9973   // Insert the element
9974   if (Elt < Ops.size()) {
9975     // All the operands of BUILD_VECTOR must have the same type;
9976     // we enforce that here.
9977     EVT OpVT = Ops[0].getValueType();
9978     if (InVal.getValueType() != OpVT)
9979       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9980                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9981                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9982     Ops[Elt] = InVal;
9983   }
9984
9985   // Return the new vector
9986   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9987 }
9988
9989 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9990     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9991   EVT ResultVT = EVE->getValueType(0);
9992   EVT VecEltVT = InVecVT.getVectorElementType();
9993   unsigned Align = OriginalLoad->getAlignment();
9994   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9995       VecEltVT.getTypeForEVT(*DAG.getContext()));
9996
9997   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9998     return SDValue();
9999
10000   Align = NewAlign;
10001
10002   SDValue NewPtr = OriginalLoad->getBasePtr();
10003   SDValue Offset;
10004   EVT PtrType = NewPtr.getValueType();
10005   MachinePointerInfo MPI;
10006   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10007     int Elt = ConstEltNo->getZExtValue();
10008     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10009     if (TLI.isBigEndian())
10010       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10011     Offset = DAG.getConstant(PtrOff, PtrType);
10012     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10013   } else {
10014     Offset = DAG.getNode(
10015         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10016         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10017     if (TLI.isBigEndian())
10018       Offset = DAG.getNode(
10019           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10020           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10021     MPI = OriginalLoad->getPointerInfo();
10022   }
10023   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10024
10025   // The replacement we need to do here is a little tricky: we need to
10026   // replace an extractelement of a load with a load.
10027   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10028   // Note that this replacement assumes that the extractvalue is the only
10029   // use of the load; that's okay because we don't want to perform this
10030   // transformation in other cases anyway.
10031   SDValue Load;
10032   SDValue Chain;
10033   if (ResultVT.bitsGT(VecEltVT)) {
10034     // If the result type of vextract is wider than the load, then issue an
10035     // extending load instead.
10036     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10037                                    ? ISD::ZEXTLOAD
10038                                    : ISD::EXTLOAD;
10039     Load = DAG.getExtLoad(
10040         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10041         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10042         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10043     Chain = Load.getValue(1);
10044   } else {
10045     Load = DAG.getLoad(
10046         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10047         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10048         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10049     Chain = Load.getValue(1);
10050     if (ResultVT.bitsLT(VecEltVT))
10051       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10052     else
10053       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10054   }
10055   WorklistRemover DeadNodes(*this);
10056   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10057   SDValue To[] = { Load, Chain };
10058   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10059   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10060   // worklist explicitly as well.
10061   AddToWorklist(Load.getNode());
10062   AddUsersToWorklist(Load.getNode()); // Add users too
10063   // Make sure to revisit this node to clean it up; it will usually be dead.
10064   AddToWorklist(EVE);
10065   ++OpsNarrowed;
10066   return SDValue(EVE, 0);
10067 }
10068
10069 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10070   // (vextract (scalar_to_vector val, 0) -> val
10071   SDValue InVec = N->getOperand(0);
10072   EVT VT = InVec.getValueType();
10073   EVT NVT = N->getValueType(0);
10074
10075   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10076     // Check if the result type doesn't match the inserted element type. A
10077     // SCALAR_TO_VECTOR may truncate the inserted element and the
10078     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10079     SDValue InOp = InVec.getOperand(0);
10080     if (InOp.getValueType() != NVT) {
10081       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10082       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10083     }
10084     return InOp;
10085   }
10086
10087   SDValue EltNo = N->getOperand(1);
10088   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10089
10090   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10091   // We only perform this optimization before the op legalization phase because
10092   // we may introduce new vector instructions which are not backed by TD
10093   // patterns. For example on AVX, extracting elements from a wide vector
10094   // without using extract_subvector. However, if we can find an underlying
10095   // scalar value, then we can always use that.
10096   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10097       && ConstEltNo) {
10098     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10099     int NumElem = VT.getVectorNumElements();
10100     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10101     // Find the new index to extract from.
10102     int OrigElt = SVOp->getMaskElt(Elt);
10103
10104     // Extracting an undef index is undef.
10105     if (OrigElt == -1)
10106       return DAG.getUNDEF(NVT);
10107
10108     // Select the right vector half to extract from.
10109     SDValue SVInVec;
10110     if (OrigElt < NumElem) {
10111       SVInVec = InVec->getOperand(0);
10112     } else {
10113       SVInVec = InVec->getOperand(1);
10114       OrigElt -= NumElem;
10115     }
10116
10117     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10118       SDValue InOp = SVInVec.getOperand(OrigElt);
10119       if (InOp.getValueType() != NVT) {
10120         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10121         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10122       }
10123
10124       return InOp;
10125     }
10126
10127     // FIXME: We should handle recursing on other vector shuffles and
10128     // scalar_to_vector here as well.
10129
10130     if (!LegalOperations) {
10131       EVT IndexTy = TLI.getVectorIdxTy();
10132       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10133                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10134     }
10135   }
10136
10137   bool BCNumEltsChanged = false;
10138   EVT ExtVT = VT.getVectorElementType();
10139   EVT LVT = ExtVT;
10140
10141   // If the result of load has to be truncated, then it's not necessarily
10142   // profitable.
10143   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10144     return SDValue();
10145
10146   if (InVec.getOpcode() == ISD::BITCAST) {
10147     // Don't duplicate a load with other uses.
10148     if (!InVec.hasOneUse())
10149       return SDValue();
10150
10151     EVT BCVT = InVec.getOperand(0).getValueType();
10152     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10153       return SDValue();
10154     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10155       BCNumEltsChanged = true;
10156     InVec = InVec.getOperand(0);
10157     ExtVT = BCVT.getVectorElementType();
10158   }
10159
10160   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10161   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10162       ISD::isNormalLoad(InVec.getNode()) &&
10163       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10164     SDValue Index = N->getOperand(1);
10165     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10166       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10167                                                            OrigLoad);
10168   }
10169
10170   // Perform only after legalization to ensure build_vector / vector_shuffle
10171   // optimizations have already been done.
10172   if (!LegalOperations) return SDValue();
10173
10174   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10175   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10176   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10177
10178   if (ConstEltNo) {
10179     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10180
10181     LoadSDNode *LN0 = nullptr;
10182     const ShuffleVectorSDNode *SVN = nullptr;
10183     if (ISD::isNormalLoad(InVec.getNode())) {
10184       LN0 = cast<LoadSDNode>(InVec);
10185     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10186                InVec.getOperand(0).getValueType() == ExtVT &&
10187                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10188       // Don't duplicate a load with other uses.
10189       if (!InVec.hasOneUse())
10190         return SDValue();
10191
10192       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10193     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10194       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10195       // =>
10196       // (load $addr+1*size)
10197
10198       // Don't duplicate a load with other uses.
10199       if (!InVec.hasOneUse())
10200         return SDValue();
10201
10202       // If the bit convert changed the number of elements, it is unsafe
10203       // to examine the mask.
10204       if (BCNumEltsChanged)
10205         return SDValue();
10206
10207       // Select the input vector, guarding against out of range extract vector.
10208       unsigned NumElems = VT.getVectorNumElements();
10209       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10210       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10211
10212       if (InVec.getOpcode() == ISD::BITCAST) {
10213         // Don't duplicate a load with other uses.
10214         if (!InVec.hasOneUse())
10215           return SDValue();
10216
10217         InVec = InVec.getOperand(0);
10218       }
10219       if (ISD::isNormalLoad(InVec.getNode())) {
10220         LN0 = cast<LoadSDNode>(InVec);
10221         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10222         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10223       }
10224     }
10225
10226     // Make sure we found a non-volatile load and the extractelement is
10227     // the only use.
10228     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10229       return SDValue();
10230
10231     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10232     if (Elt == -1)
10233       return DAG.getUNDEF(LVT);
10234
10235     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10236   }
10237
10238   return SDValue();
10239 }
10240
10241 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10242 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10243   // We perform this optimization post type-legalization because
10244   // the type-legalizer often scalarizes integer-promoted vectors.
10245   // Performing this optimization before may create bit-casts which
10246   // will be type-legalized to complex code sequences.
10247   // We perform this optimization only before the operation legalizer because we
10248   // may introduce illegal operations.
10249   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10250     return SDValue();
10251
10252   unsigned NumInScalars = N->getNumOperands();
10253   SDLoc dl(N);
10254   EVT VT = N->getValueType(0);
10255
10256   // Check to see if this is a BUILD_VECTOR of a bunch of values
10257   // which come from any_extend or zero_extend nodes. If so, we can create
10258   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10259   // optimizations. We do not handle sign-extend because we can't fill the sign
10260   // using shuffles.
10261   EVT SourceType = MVT::Other;
10262   bool AllAnyExt = true;
10263
10264   for (unsigned i = 0; i != NumInScalars; ++i) {
10265     SDValue In = N->getOperand(i);
10266     // Ignore undef inputs.
10267     if (In.getOpcode() == ISD::UNDEF) continue;
10268
10269     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10270     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10271
10272     // Abort if the element is not an extension.
10273     if (!ZeroExt && !AnyExt) {
10274       SourceType = MVT::Other;
10275       break;
10276     }
10277
10278     // The input is a ZeroExt or AnyExt. Check the original type.
10279     EVT InTy = In.getOperand(0).getValueType();
10280
10281     // Check that all of the widened source types are the same.
10282     if (SourceType == MVT::Other)
10283       // First time.
10284       SourceType = InTy;
10285     else if (InTy != SourceType) {
10286       // Multiple income types. Abort.
10287       SourceType = MVT::Other;
10288       break;
10289     }
10290
10291     // Check if all of the extends are ANY_EXTENDs.
10292     AllAnyExt &= AnyExt;
10293   }
10294
10295   // In order to have valid types, all of the inputs must be extended from the
10296   // same source type and all of the inputs must be any or zero extend.
10297   // Scalar sizes must be a power of two.
10298   EVT OutScalarTy = VT.getScalarType();
10299   bool ValidTypes = SourceType != MVT::Other &&
10300                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10301                  isPowerOf2_32(SourceType.getSizeInBits());
10302
10303   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10304   // turn into a single shuffle instruction.
10305   if (!ValidTypes)
10306     return SDValue();
10307
10308   bool isLE = TLI.isLittleEndian();
10309   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10310   assert(ElemRatio > 1 && "Invalid element size ratio");
10311   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10312                                DAG.getConstant(0, SourceType);
10313
10314   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10315   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10316
10317   // Populate the new build_vector
10318   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10319     SDValue Cast = N->getOperand(i);
10320     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10321             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10322             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10323     SDValue In;
10324     if (Cast.getOpcode() == ISD::UNDEF)
10325       In = DAG.getUNDEF(SourceType);
10326     else
10327       In = Cast->getOperand(0);
10328     unsigned Index = isLE ? (i * ElemRatio) :
10329                             (i * ElemRatio + (ElemRatio - 1));
10330
10331     assert(Index < Ops.size() && "Invalid index");
10332     Ops[Index] = In;
10333   }
10334
10335   // The type of the new BUILD_VECTOR node.
10336   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10337   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10338          "Invalid vector size");
10339   // Check if the new vector type is legal.
10340   if (!isTypeLegal(VecVT)) return SDValue();
10341
10342   // Make the new BUILD_VECTOR.
10343   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10344
10345   // The new BUILD_VECTOR node has the potential to be further optimized.
10346   AddToWorklist(BV.getNode());
10347   // Bitcast to the desired type.
10348   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10349 }
10350
10351 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10352   EVT VT = N->getValueType(0);
10353
10354   unsigned NumInScalars = N->getNumOperands();
10355   SDLoc dl(N);
10356
10357   EVT SrcVT = MVT::Other;
10358   unsigned Opcode = ISD::DELETED_NODE;
10359   unsigned NumDefs = 0;
10360
10361   for (unsigned i = 0; i != NumInScalars; ++i) {
10362     SDValue In = N->getOperand(i);
10363     unsigned Opc = In.getOpcode();
10364
10365     if (Opc == ISD::UNDEF)
10366       continue;
10367
10368     // If all scalar values are floats and converted from integers.
10369     if (Opcode == ISD::DELETED_NODE &&
10370         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10371       Opcode = Opc;
10372     }
10373
10374     if (Opc != Opcode)
10375       return SDValue();
10376
10377     EVT InVT = In.getOperand(0).getValueType();
10378
10379     // If all scalar values are typed differently, bail out. It's chosen to
10380     // simplify BUILD_VECTOR of integer types.
10381     if (SrcVT == MVT::Other)
10382       SrcVT = InVT;
10383     if (SrcVT != InVT)
10384       return SDValue();
10385     NumDefs++;
10386   }
10387
10388   // If the vector has just one element defined, it's not worth to fold it into
10389   // a vectorized one.
10390   if (NumDefs < 2)
10391     return SDValue();
10392
10393   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10394          && "Should only handle conversion from integer to float.");
10395   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10396
10397   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10398
10399   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10400     return SDValue();
10401
10402   SmallVector<SDValue, 8> Opnds;
10403   for (unsigned i = 0; i != NumInScalars; ++i) {
10404     SDValue In = N->getOperand(i);
10405
10406     if (In.getOpcode() == ISD::UNDEF)
10407       Opnds.push_back(DAG.getUNDEF(SrcVT));
10408     else
10409       Opnds.push_back(In.getOperand(0));
10410   }
10411   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10412   AddToWorklist(BV.getNode());
10413
10414   return DAG.getNode(Opcode, dl, VT, BV);
10415 }
10416
10417 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10418   unsigned NumInScalars = N->getNumOperands();
10419   SDLoc dl(N);
10420   EVT VT = N->getValueType(0);
10421
10422   // A vector built entirely of undefs is undef.
10423   if (ISD::allOperandsUndef(N))
10424     return DAG.getUNDEF(VT);
10425
10426   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10427   if (V.getNode())
10428     return V;
10429
10430   V = reduceBuildVecConvertToConvertBuildVec(N);
10431   if (V.getNode())
10432     return V;
10433
10434   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10435   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10436   // at most two distinct vectors, turn this into a shuffle node.
10437
10438   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10439   if (!isTypeLegal(VT))
10440     return SDValue();
10441
10442   // May only combine to shuffle after legalize if shuffle is legal.
10443   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10444     return SDValue();
10445
10446   SDValue VecIn1, VecIn2;
10447   for (unsigned i = 0; i != NumInScalars; ++i) {
10448     // Ignore undef inputs.
10449     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10450
10451     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10452     // constant index, bail out.
10453     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10454         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10455       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10456       break;
10457     }
10458
10459     // We allow up to two distinct input vectors.
10460     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10461     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10462       continue;
10463
10464     if (!VecIn1.getNode()) {
10465       VecIn1 = ExtractedFromVec;
10466     } else if (!VecIn2.getNode()) {
10467       VecIn2 = ExtractedFromVec;
10468     } else {
10469       // Too many inputs.
10470       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10471       break;
10472     }
10473   }
10474
10475   // If everything is good, we can make a shuffle operation.
10476   if (VecIn1.getNode()) {
10477     SmallVector<int, 8> Mask;
10478     for (unsigned i = 0; i != NumInScalars; ++i) {
10479       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10480         Mask.push_back(-1);
10481         continue;
10482       }
10483
10484       // If extracting from the first vector, just use the index directly.
10485       SDValue Extract = N->getOperand(i);
10486       SDValue ExtVal = Extract.getOperand(1);
10487       if (Extract.getOperand(0) == VecIn1) {
10488         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10489         if (ExtIndex > VT.getVectorNumElements())
10490           return SDValue();
10491
10492         Mask.push_back(ExtIndex);
10493         continue;
10494       }
10495
10496       // Otherwise, use InIdx + VecSize
10497       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10498       Mask.push_back(Idx+NumInScalars);
10499     }
10500
10501     // We can't generate a shuffle node with mismatched input and output types.
10502     // Attempt to transform a single input vector to the correct type.
10503     if ((VT != VecIn1.getValueType())) {
10504       // We don't support shuffeling between TWO values of different types.
10505       if (VecIn2.getNode())
10506         return SDValue();
10507
10508       // We only support widening of vectors which are half the size of the
10509       // output registers. For example XMM->YMM widening on X86 with AVX.
10510       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10511         return SDValue();
10512
10513       // If the input vector type has a different base type to the output
10514       // vector type, bail out.
10515       if (VecIn1.getValueType().getVectorElementType() !=
10516           VT.getVectorElementType())
10517         return SDValue();
10518
10519       // Widen the input vector by adding undef values.
10520       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10521                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10522     }
10523
10524     // If VecIn2 is unused then change it to undef.
10525     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10526
10527     // Check that we were able to transform all incoming values to the same
10528     // type.
10529     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10530         VecIn1.getValueType() != VT)
10531           return SDValue();
10532
10533     // Return the new VECTOR_SHUFFLE node.
10534     SDValue Ops[2];
10535     Ops[0] = VecIn1;
10536     Ops[1] = VecIn2;
10537     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10538   }
10539
10540   return SDValue();
10541 }
10542
10543 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10544   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10545   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10546   // inputs come from at most two distinct vectors, turn this into a shuffle
10547   // node.
10548
10549   // If we only have one input vector, we don't need to do any concatenation.
10550   if (N->getNumOperands() == 1)
10551     return N->getOperand(0);
10552
10553   // Check if all of the operands are undefs.
10554   EVT VT = N->getValueType(0);
10555   if (ISD::allOperandsUndef(N))
10556     return DAG.getUNDEF(VT);
10557
10558   // Optimize concat_vectors where one of the vectors is undef.
10559   if (N->getNumOperands() == 2 &&
10560       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10561     SDValue In = N->getOperand(0);
10562     assert(In.getValueType().isVector() && "Must concat vectors");
10563
10564     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10565     if (In->getOpcode() == ISD::BITCAST &&
10566         !In->getOperand(0)->getValueType(0).isVector()) {
10567       SDValue Scalar = In->getOperand(0);
10568       EVT SclTy = Scalar->getValueType(0);
10569
10570       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10571         return SDValue();
10572
10573       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10574                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10575       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10576         return SDValue();
10577
10578       SDLoc dl = SDLoc(N);
10579       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10580       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10581     }
10582   }
10583
10584   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10585   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10586   if (N->getNumOperands() == 2 &&
10587       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10588       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10589     EVT VT = N->getValueType(0);
10590     SDValue N0 = N->getOperand(0);
10591     SDValue N1 = N->getOperand(1);
10592     SmallVector<SDValue, 8> Opnds;
10593     unsigned BuildVecNumElts =  N0.getNumOperands();
10594
10595     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10596     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10597     if (SclTy0.isFloatingPoint()) {
10598       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10599         Opnds.push_back(N0.getOperand(i));
10600       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10601         Opnds.push_back(N1.getOperand(i));
10602     } else {
10603       // If BUILD_VECTOR are from built from integer, they may have different
10604       // operand types. Get the smaller type and truncate all operands to it.
10605       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10606       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10607         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10608                         N0.getOperand(i)));
10609       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10610         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10611                         N1.getOperand(i)));
10612     }
10613
10614     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10615   }
10616
10617   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10618   // nodes often generate nop CONCAT_VECTOR nodes.
10619   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10620   // place the incoming vectors at the exact same location.
10621   SDValue SingleSource = SDValue();
10622   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10623
10624   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10625     SDValue Op = N->getOperand(i);
10626
10627     if (Op.getOpcode() == ISD::UNDEF)
10628       continue;
10629
10630     // Check if this is the identity extract:
10631     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10632       return SDValue();
10633
10634     // Find the single incoming vector for the extract_subvector.
10635     if (SingleSource.getNode()) {
10636       if (Op.getOperand(0) != SingleSource)
10637         return SDValue();
10638     } else {
10639       SingleSource = Op.getOperand(0);
10640
10641       // Check the source type is the same as the type of the result.
10642       // If not, this concat may extend the vector, so we can not
10643       // optimize it away.
10644       if (SingleSource.getValueType() != N->getValueType(0))
10645         return SDValue();
10646     }
10647
10648     unsigned IdentityIndex = i * PartNumElem;
10649     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10650     // The extract index must be constant.
10651     if (!CS)
10652       return SDValue();
10653
10654     // Check that we are reading from the identity index.
10655     if (CS->getZExtValue() != IdentityIndex)
10656       return SDValue();
10657   }
10658
10659   if (SingleSource.getNode())
10660     return SingleSource;
10661
10662   return SDValue();
10663 }
10664
10665 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10666   EVT NVT = N->getValueType(0);
10667   SDValue V = N->getOperand(0);
10668
10669   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10670     // Combine:
10671     //    (extract_subvec (concat V1, V2, ...), i)
10672     // Into:
10673     //    Vi if possible
10674     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10675     // type.
10676     if (V->getOperand(0).getValueType() != NVT)
10677       return SDValue();
10678     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10679     unsigned NumElems = NVT.getVectorNumElements();
10680     assert((Idx % NumElems) == 0 &&
10681            "IDX in concat is not a multiple of the result vector length.");
10682     return V->getOperand(Idx / NumElems);
10683   }
10684
10685   // Skip bitcasting
10686   if (V->getOpcode() == ISD::BITCAST)
10687     V = V.getOperand(0);
10688
10689   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10690     SDLoc dl(N);
10691     // Handle only simple case where vector being inserted and vector
10692     // being extracted are of same type, and are half size of larger vectors.
10693     EVT BigVT = V->getOperand(0).getValueType();
10694     EVT SmallVT = V->getOperand(1).getValueType();
10695     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10696       return SDValue();
10697
10698     // Only handle cases where both indexes are constants with the same type.
10699     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10700     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10701
10702     if (InsIdx && ExtIdx &&
10703         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10704         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10705       // Combine:
10706       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10707       // Into:
10708       //    indices are equal or bit offsets are equal => V1
10709       //    otherwise => (extract_subvec V1, ExtIdx)
10710       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10711           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10712         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10713       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10714                          DAG.getNode(ISD::BITCAST, dl,
10715                                      N->getOperand(0).getValueType(),
10716                                      V->getOperand(0)), N->getOperand(1));
10717     }
10718   }
10719
10720   return SDValue();
10721 }
10722
10723 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10724                                                  SDValue V, SelectionDAG &DAG) {
10725   SDLoc DL(V);
10726   EVT VT = V.getValueType();
10727
10728   switch (V.getOpcode()) {
10729   default:
10730     return V;
10731
10732   case ISD::CONCAT_VECTORS: {
10733     EVT OpVT = V->getOperand(0).getValueType();
10734     int OpSize = OpVT.getVectorNumElements();
10735     SmallBitVector OpUsedElements(OpSize, false);
10736     bool FoundSimplification = false;
10737     SmallVector<SDValue, 4> NewOps;
10738     NewOps.reserve(V->getNumOperands());
10739     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10740       SDValue Op = V->getOperand(i);
10741       bool OpUsed = false;
10742       for (int j = 0; j < OpSize; ++j)
10743         if (UsedElements[i * OpSize + j]) {
10744           OpUsedElements[j] = true;
10745           OpUsed = true;
10746         }
10747       NewOps.push_back(
10748           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10749                  : DAG.getUNDEF(OpVT));
10750       FoundSimplification |= Op == NewOps.back();
10751       OpUsedElements.reset();
10752     }
10753     if (FoundSimplification)
10754       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10755     return V;
10756   }
10757
10758   case ISD::INSERT_SUBVECTOR: {
10759     SDValue BaseV = V->getOperand(0);
10760     SDValue SubV = V->getOperand(1);
10761     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10762     if (!IdxN)
10763       return V;
10764
10765     int SubSize = SubV.getValueType().getVectorNumElements();
10766     int Idx = IdxN->getZExtValue();
10767     bool SubVectorUsed = false;
10768     SmallBitVector SubUsedElements(SubSize, false);
10769     for (int i = 0; i < SubSize; ++i)
10770       if (UsedElements[i + Idx]) {
10771         SubVectorUsed = true;
10772         SubUsedElements[i] = true;
10773         UsedElements[i + Idx] = false;
10774       }
10775
10776     // Now recurse on both the base and sub vectors.
10777     SDValue SimplifiedSubV =
10778         SubVectorUsed
10779             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10780             : DAG.getUNDEF(SubV.getValueType());
10781     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10782     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10783       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10784                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10785     return V;
10786   }
10787   }
10788 }
10789
10790 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10791                                        SDValue N1, SelectionDAG &DAG) {
10792   EVT VT = SVN->getValueType(0);
10793   int NumElts = VT.getVectorNumElements();
10794   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10795   for (int M : SVN->getMask())
10796     if (M >= 0 && M < NumElts)
10797       N0UsedElements[M] = true;
10798     else if (M >= NumElts)
10799       N1UsedElements[M - NumElts] = true;
10800
10801   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10802   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10803   if (S0 == N0 && S1 == N1)
10804     return SDValue();
10805
10806   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10807 }
10808
10809 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10810 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10811   EVT VT = N->getValueType(0);
10812   unsigned NumElts = VT.getVectorNumElements();
10813
10814   SDValue N0 = N->getOperand(0);
10815   SDValue N1 = N->getOperand(1);
10816   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10817
10818   SmallVector<SDValue, 4> Ops;
10819   EVT ConcatVT = N0.getOperand(0).getValueType();
10820   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10821   unsigned NumConcats = NumElts / NumElemsPerConcat;
10822
10823   // Look at every vector that's inserted. We're looking for exact
10824   // subvector-sized copies from a concatenated vector
10825   for (unsigned I = 0; I != NumConcats; ++I) {
10826     // Make sure we're dealing with a copy.
10827     unsigned Begin = I * NumElemsPerConcat;
10828     bool AllUndef = true, NoUndef = true;
10829     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10830       if (SVN->getMaskElt(J) >= 0)
10831         AllUndef = false;
10832       else
10833         NoUndef = false;
10834     }
10835
10836     if (NoUndef) {
10837       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10838         return SDValue();
10839
10840       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10841         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10842           return SDValue();
10843
10844       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10845       if (FirstElt < N0.getNumOperands())
10846         Ops.push_back(N0.getOperand(FirstElt));
10847       else
10848         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10849
10850     } else if (AllUndef) {
10851       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10852     } else { // Mixed with general masks and undefs, can't do optimization.
10853       return SDValue();
10854     }
10855   }
10856
10857   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10858 }
10859
10860 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10861   EVT VT = N->getValueType(0);
10862   unsigned NumElts = VT.getVectorNumElements();
10863
10864   SDValue N0 = N->getOperand(0);
10865   SDValue N1 = N->getOperand(1);
10866
10867   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10868
10869   // Canonicalize shuffle undef, undef -> undef
10870   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10871     return DAG.getUNDEF(VT);
10872
10873   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10874
10875   // Canonicalize shuffle v, v -> v, undef
10876   if (N0 == N1) {
10877     SmallVector<int, 8> NewMask;
10878     for (unsigned i = 0; i != NumElts; ++i) {
10879       int Idx = SVN->getMaskElt(i);
10880       if (Idx >= (int)NumElts) Idx -= NumElts;
10881       NewMask.push_back(Idx);
10882     }
10883     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10884                                 &NewMask[0]);
10885   }
10886
10887   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10888   if (N0.getOpcode() == ISD::UNDEF) {
10889     SmallVector<int, 8> NewMask;
10890     for (unsigned i = 0; i != NumElts; ++i) {
10891       int Idx = SVN->getMaskElt(i);
10892       if (Idx >= 0) {
10893         if (Idx >= (int)NumElts)
10894           Idx -= NumElts;
10895         else
10896           Idx = -1; // remove reference to lhs
10897       }
10898       NewMask.push_back(Idx);
10899     }
10900     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10901                                 &NewMask[0]);
10902   }
10903
10904   // Remove references to rhs if it is undef
10905   if (N1.getOpcode() == ISD::UNDEF) {
10906     bool Changed = false;
10907     SmallVector<int, 8> NewMask;
10908     for (unsigned i = 0; i != NumElts; ++i) {
10909       int Idx = SVN->getMaskElt(i);
10910       if (Idx >= (int)NumElts) {
10911         Idx = -1;
10912         Changed = true;
10913       }
10914       NewMask.push_back(Idx);
10915     }
10916     if (Changed)
10917       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10918   }
10919
10920   // If it is a splat, check if the argument vector is another splat or a
10921   // build_vector with all scalar elements the same.
10922   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10923     SDNode *V = N0.getNode();
10924
10925     // If this is a bit convert that changes the element type of the vector but
10926     // not the number of vector elements, look through it.  Be careful not to
10927     // look though conversions that change things like v4f32 to v2f64.
10928     if (V->getOpcode() == ISD::BITCAST) {
10929       SDValue ConvInput = V->getOperand(0);
10930       if (ConvInput.getValueType().isVector() &&
10931           ConvInput.getValueType().getVectorNumElements() == NumElts)
10932         V = ConvInput.getNode();
10933     }
10934
10935     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10936       assert(V->getNumOperands() == NumElts &&
10937              "BUILD_VECTOR has wrong number of operands");
10938       SDValue Base;
10939       bool AllSame = true;
10940       for (unsigned i = 0; i != NumElts; ++i) {
10941         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10942           Base = V->getOperand(i);
10943           break;
10944         }
10945       }
10946       // Splat of <u, u, u, u>, return <u, u, u, u>
10947       if (!Base.getNode())
10948         return N0;
10949       for (unsigned i = 0; i != NumElts; ++i) {
10950         if (V->getOperand(i) != Base) {
10951           AllSame = false;
10952           break;
10953         }
10954       }
10955       // Splat of <x, x, x, x>, return <x, x, x, x>
10956       if (AllSame)
10957         return N0;
10958     }
10959   }
10960
10961   // There are various patterns used to build up a vector from smaller vectors,
10962   // subvectors, or elements. Scan chains of these and replace unused insertions
10963   // or components with undef.
10964   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
10965     return S;
10966
10967   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10968       Level < AfterLegalizeVectorOps &&
10969       (N1.getOpcode() == ISD::UNDEF ||
10970       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10971        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10972     SDValue V = partitionShuffleOfConcats(N, DAG);
10973
10974     if (V.getNode())
10975       return V;
10976   }
10977
10978   // If this shuffle node is simply a swizzle of another shuffle node,
10979   // then try to simplify it.
10980   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10981       N1.getOpcode() == ISD::UNDEF) {
10982
10983     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10984
10985     // The incoming shuffle must be of the same type as the result of the
10986     // current shuffle.
10987     assert(OtherSV->getOperand(0).getValueType() == VT &&
10988            "Shuffle types don't match");
10989
10990     SmallVector<int, 4> Mask;
10991     // Compute the combined shuffle mask.
10992     for (unsigned i = 0; i != NumElts; ++i) {
10993       int Idx = SVN->getMaskElt(i);
10994       assert(Idx < (int)NumElts && "Index references undef operand");
10995       // Next, this index comes from the first value, which is the incoming
10996       // shuffle. Adopt the incoming index.
10997       if (Idx >= 0)
10998         Idx = OtherSV->getMaskElt(Idx);
10999       Mask.push_back(Idx);
11000     }
11001
11002     // Check if all indices in Mask are Undef. In case, propagate Undef.
11003     bool isUndefMask = true;
11004     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11005       isUndefMask &= Mask[i] < 0;
11006
11007     if (isUndefMask)
11008       return DAG.getUNDEF(VT);
11009     
11010     bool CommuteOperands = false;
11011     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11012       // To be valid, the combine shuffle mask should only reference elements
11013       // from one of the two vectors in input to the inner shufflevector.
11014       bool IsValidMask = true;
11015       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11016         // See if the combined mask only reference undefs or elements coming
11017         // from the first shufflevector operand.
11018         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11019
11020       if (!IsValidMask) {
11021         IsValidMask = true;
11022         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11023           // Check that all the elements come from the second shuffle operand.
11024           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11025         CommuteOperands = IsValidMask;
11026       }
11027
11028       // Early exit if the combined shuffle mask is not valid.
11029       if (!IsValidMask)
11030         return SDValue();
11031     }
11032
11033     // See if this pair of shuffles can be safely folded according to either
11034     // of the following rules:
11035     //   shuffle(shuffle(x, y), undef) -> x
11036     //   shuffle(shuffle(x, undef), undef) -> x
11037     //   shuffle(shuffle(x, y), undef) -> y
11038     bool IsIdentityMask = true;
11039     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11040     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11041       // Skip Undefs.
11042       if (Mask[i] < 0)
11043         continue;
11044
11045       // The combined shuffle must map each index to itself.
11046       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11047     }
11048     
11049     if (IsIdentityMask) {
11050       if (CommuteOperands)
11051         // optimize shuffle(shuffle(x, y), undef) -> y.
11052         return OtherSV->getOperand(1);
11053       
11054       // optimize shuffle(shuffle(x, undef), undef) -> x
11055       // optimize shuffle(shuffle(x, y), undef) -> x
11056       return OtherSV->getOperand(0);
11057     }
11058
11059     // It may still be beneficial to combine the two shuffles if the
11060     // resulting shuffle is legal.
11061     if (TLI.isTypeLegal(VT)) {
11062       if (!CommuteOperands) {
11063         if (TLI.isShuffleMaskLegal(Mask, VT))
11064           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11065           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11066           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11067                                       &Mask[0]);
11068       } else {
11069         // Compute the commuted shuffle mask.
11070         for (unsigned i = 0; i != NumElts; ++i) {
11071           int idx = Mask[i];
11072           if (idx < 0)
11073             continue;
11074           else if (idx < (int)NumElts)
11075             Mask[i] = idx + NumElts;
11076           else
11077             Mask[i] = idx - NumElts;
11078         }
11079
11080         if (TLI.isShuffleMaskLegal(Mask, VT))
11081           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11082           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11083                                       &Mask[0]);
11084       }
11085     }
11086   }
11087
11088   // Canonicalize shuffles according to rules:
11089   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11090   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11091   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11092   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11093       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11094       TLI.isTypeLegal(VT)) {
11095     // The incoming shuffle must be of the same type as the result of the
11096     // current shuffle.
11097     assert(N1->getOperand(0).getValueType() == VT &&
11098            "Shuffle types don't match");
11099
11100     SDValue SV0 = N1->getOperand(0);
11101     SDValue SV1 = N1->getOperand(1);
11102     bool HasSameOp0 = N0 == SV0;
11103     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11104     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11105       // Commute the operands of this shuffle so that next rule
11106       // will trigger.
11107       return DAG.getCommutedVectorShuffle(*SVN);
11108   }
11109
11110   // Try to fold according to rules:
11111   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11112   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11113   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11114   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11115   // Don't try to fold shuffles with illegal type.
11116   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11117       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11118     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11119
11120     // The incoming shuffle must be of the same type as the result of the
11121     // current shuffle.
11122     assert(OtherSV->getOperand(0).getValueType() == VT &&
11123            "Shuffle types don't match");
11124
11125     SDValue SV0 = OtherSV->getOperand(0);
11126     SDValue SV1 = OtherSV->getOperand(1);
11127     bool HasSameOp0 = N1 == SV0;
11128     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11129     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11130       // Early exit.
11131       return SDValue();
11132
11133     SmallVector<int, 4> Mask;
11134     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11135     // operand, and SV1 as the second operand.
11136     for (unsigned i = 0; i != NumElts; ++i) {
11137       int Idx = SVN->getMaskElt(i);
11138       if (Idx < 0) {
11139         // Propagate Undef.
11140         Mask.push_back(Idx);
11141         continue;
11142       }
11143
11144       if (Idx < (int)NumElts) {
11145         Idx = OtherSV->getMaskElt(Idx);
11146         if (IsSV1Undef && Idx >= (int) NumElts)
11147           Idx = -1;  // Propagate Undef.
11148       } else
11149         Idx = HasSameOp0 ? Idx - NumElts : Idx;
11150
11151       Mask.push_back(Idx);
11152     }
11153
11154     // Check if all indices in Mask are Undef. In case, propagate Undef.
11155     bool isUndefMask = true;
11156     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11157       isUndefMask &= Mask[i] < 0;
11158
11159     if (isUndefMask)
11160       return DAG.getUNDEF(VT);
11161
11162     // Avoid introducing shuffles with illegal mask.
11163     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11164       if (IsSV1Undef)
11165         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11166         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11167         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11168       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11169     }
11170   }
11171
11172   return SDValue();
11173 }
11174
11175 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11176   SDValue N0 = N->getOperand(0);
11177   SDValue N2 = N->getOperand(2);
11178
11179   // If the input vector is a concatenation, and the insert replaces
11180   // one of the halves, we can optimize into a single concat_vectors.
11181   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11182       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11183     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11184     EVT VT = N->getValueType(0);
11185
11186     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11187     // (concat_vectors Z, Y)
11188     if (InsIdx == 0)
11189       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11190                          N->getOperand(1), N0.getOperand(1));
11191
11192     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11193     // (concat_vectors X, Z)
11194     if (InsIdx == VT.getVectorNumElements()/2)
11195       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11196                          N0.getOperand(0), N->getOperand(1));
11197   }
11198
11199   return SDValue();
11200 }
11201
11202 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11203 /// with the destination vector and a zero vector.
11204 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11205 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11206 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11207   EVT VT = N->getValueType(0);
11208   SDLoc dl(N);
11209   SDValue LHS = N->getOperand(0);
11210   SDValue RHS = N->getOperand(1);
11211   if (N->getOpcode() == ISD::AND) {
11212     if (RHS.getOpcode() == ISD::BITCAST)
11213       RHS = RHS.getOperand(0);
11214     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11215       SmallVector<int, 8> Indices;
11216       unsigned NumElts = RHS.getNumOperands();
11217       for (unsigned i = 0; i != NumElts; ++i) {
11218         SDValue Elt = RHS.getOperand(i);
11219         if (!isa<ConstantSDNode>(Elt))
11220           return SDValue();
11221
11222         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11223           Indices.push_back(i);
11224         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11225           Indices.push_back(NumElts);
11226         else
11227           return SDValue();
11228       }
11229
11230       // Let's see if the target supports this vector_shuffle.
11231       EVT RVT = RHS.getValueType();
11232       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11233         return SDValue();
11234
11235       // Return the new VECTOR_SHUFFLE node.
11236       EVT EltVT = RVT.getVectorElementType();
11237       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11238                                      DAG.getConstant(0, EltVT));
11239       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11240       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11241       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11242       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11243     }
11244   }
11245
11246   return SDValue();
11247 }
11248
11249 /// Visit a binary vector operation, like ADD.
11250 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11251   assert(N->getValueType(0).isVector() &&
11252          "SimplifyVBinOp only works on vectors!");
11253
11254   SDValue LHS = N->getOperand(0);
11255   SDValue RHS = N->getOperand(1);
11256   SDValue Shuffle = XformToShuffleWithZero(N);
11257   if (Shuffle.getNode()) return Shuffle;
11258
11259   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11260   // this operation.
11261   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11262       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11263     // Check if both vectors are constants. If not bail out.
11264     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11265           cast<BuildVectorSDNode>(RHS)->isConstant()))
11266       return SDValue();
11267
11268     SmallVector<SDValue, 8> Ops;
11269     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11270       SDValue LHSOp = LHS.getOperand(i);
11271       SDValue RHSOp = RHS.getOperand(i);
11272
11273       // Can't fold divide by zero.
11274       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11275           N->getOpcode() == ISD::FDIV) {
11276         if ((RHSOp.getOpcode() == ISD::Constant &&
11277              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11278             (RHSOp.getOpcode() == ISD::ConstantFP &&
11279              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11280           break;
11281       }
11282
11283       EVT VT = LHSOp.getValueType();
11284       EVT RVT = RHSOp.getValueType();
11285       if (RVT != VT) {
11286         // Integer BUILD_VECTOR operands may have types larger than the element
11287         // size (e.g., when the element type is not legal).  Prior to type
11288         // legalization, the types may not match between the two BUILD_VECTORS.
11289         // Truncate one of the operands to make them match.
11290         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11291           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11292         } else {
11293           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11294           VT = RVT;
11295         }
11296       }
11297       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11298                                    LHSOp, RHSOp);
11299       if (FoldOp.getOpcode() != ISD::UNDEF &&
11300           FoldOp.getOpcode() != ISD::Constant &&
11301           FoldOp.getOpcode() != ISD::ConstantFP)
11302         break;
11303       Ops.push_back(FoldOp);
11304       AddToWorklist(FoldOp.getNode());
11305     }
11306
11307     if (Ops.size() == LHS.getNumOperands())
11308       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11309   }
11310
11311   // Type legalization might introduce new shuffles in the DAG.
11312   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11313   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11314   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11315       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11316       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11317       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11318     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11319     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11320
11321     if (SVN0->getMask().equals(SVN1->getMask())) {
11322       EVT VT = N->getValueType(0);
11323       SDValue UndefVector = LHS.getOperand(1);
11324       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11325                                      LHS.getOperand(0), RHS.getOperand(0));
11326       AddUsersToWorklist(N);
11327       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11328                                   &SVN0->getMask()[0]);
11329     }
11330   }
11331
11332   return SDValue();
11333 }
11334
11335 /// Visit a binary vector operation, like FABS/FNEG.
11336 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11337   assert(N->getValueType(0).isVector() &&
11338          "SimplifyVUnaryOp only works on vectors!");
11339
11340   SDValue N0 = N->getOperand(0);
11341
11342   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11343     return SDValue();
11344
11345   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11346   SmallVector<SDValue, 8> Ops;
11347   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11348     SDValue Op = N0.getOperand(i);
11349     if (Op.getOpcode() != ISD::UNDEF &&
11350         Op.getOpcode() != ISD::ConstantFP)
11351       break;
11352     EVT EltVT = Op.getValueType();
11353     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11354     if (FoldOp.getOpcode() != ISD::UNDEF &&
11355         FoldOp.getOpcode() != ISD::ConstantFP)
11356       break;
11357     Ops.push_back(FoldOp);
11358     AddToWorklist(FoldOp.getNode());
11359   }
11360
11361   if (Ops.size() != N0.getNumOperands())
11362     return SDValue();
11363
11364   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11365 }
11366
11367 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11368                                     SDValue N1, SDValue N2){
11369   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11370
11371   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11372                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11373
11374   // If we got a simplified select_cc node back from SimplifySelectCC, then
11375   // break it down into a new SETCC node, and a new SELECT node, and then return
11376   // the SELECT node, since we were called with a SELECT node.
11377   if (SCC.getNode()) {
11378     // Check to see if we got a select_cc back (to turn into setcc/select).
11379     // Otherwise, just return whatever node we got back, like fabs.
11380     if (SCC.getOpcode() == ISD::SELECT_CC) {
11381       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11382                                   N0.getValueType(),
11383                                   SCC.getOperand(0), SCC.getOperand(1),
11384                                   SCC.getOperand(4));
11385       AddToWorklist(SETCC.getNode());
11386       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11387                            SCC.getOperand(2), SCC.getOperand(3));
11388     }
11389
11390     return SCC;
11391   }
11392   return SDValue();
11393 }
11394
11395 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11396 /// being selected between, see if we can simplify the select.  Callers of this
11397 /// should assume that TheSelect is deleted if this returns true.  As such, they
11398 /// should return the appropriate thing (e.g. the node) back to the top-level of
11399 /// the DAG combiner loop to avoid it being looked at.
11400 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11401                                     SDValue RHS) {
11402
11403   // Cannot simplify select with vector condition
11404   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11405
11406   // If this is a select from two identical things, try to pull the operation
11407   // through the select.
11408   if (LHS.getOpcode() != RHS.getOpcode() ||
11409       !LHS.hasOneUse() || !RHS.hasOneUse())
11410     return false;
11411
11412   // If this is a load and the token chain is identical, replace the select
11413   // of two loads with a load through a select of the address to load from.
11414   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11415   // constants have been dropped into the constant pool.
11416   if (LHS.getOpcode() == ISD::LOAD) {
11417     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11418     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11419
11420     // Token chains must be identical.
11421     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11422         // Do not let this transformation reduce the number of volatile loads.
11423         LLD->isVolatile() || RLD->isVolatile() ||
11424         // If this is an EXTLOAD, the VT's must match.
11425         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11426         // If this is an EXTLOAD, the kind of extension must match.
11427         (LLD->getExtensionType() != RLD->getExtensionType() &&
11428          // The only exception is if one of the extensions is anyext.
11429          LLD->getExtensionType() != ISD::EXTLOAD &&
11430          RLD->getExtensionType() != ISD::EXTLOAD) ||
11431         // FIXME: this discards src value information.  This is
11432         // over-conservative. It would be beneficial to be able to remember
11433         // both potential memory locations.  Since we are discarding
11434         // src value info, don't do the transformation if the memory
11435         // locations are not in the default address space.
11436         LLD->getPointerInfo().getAddrSpace() != 0 ||
11437         RLD->getPointerInfo().getAddrSpace() != 0 ||
11438         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11439                                       LLD->getBasePtr().getValueType()))
11440       return false;
11441
11442     // Check that the select condition doesn't reach either load.  If so,
11443     // folding this will induce a cycle into the DAG.  If not, this is safe to
11444     // xform, so create a select of the addresses.
11445     SDValue Addr;
11446     if (TheSelect->getOpcode() == ISD::SELECT) {
11447       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11448       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11449           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11450         return false;
11451       // The loads must not depend on one another.
11452       if (LLD->isPredecessorOf(RLD) ||
11453           RLD->isPredecessorOf(LLD))
11454         return false;
11455       Addr = DAG.getSelect(SDLoc(TheSelect),
11456                            LLD->getBasePtr().getValueType(),
11457                            TheSelect->getOperand(0), LLD->getBasePtr(),
11458                            RLD->getBasePtr());
11459     } else {  // Otherwise SELECT_CC
11460       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11461       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11462
11463       if ((LLD->hasAnyUseOfValue(1) &&
11464            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11465           (RLD->hasAnyUseOfValue(1) &&
11466            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11467         return false;
11468
11469       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11470                          LLD->getBasePtr().getValueType(),
11471                          TheSelect->getOperand(0),
11472                          TheSelect->getOperand(1),
11473                          LLD->getBasePtr(), RLD->getBasePtr(),
11474                          TheSelect->getOperand(4));
11475     }
11476
11477     SDValue Load;
11478     // It is safe to replace the two loads if they have different alignments,
11479     // but the new load must be the minimum (most restrictive) alignment of the
11480     // inputs.
11481     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11482     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11483     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11484       Load = DAG.getLoad(TheSelect->getValueType(0),
11485                          SDLoc(TheSelect),
11486                          // FIXME: Discards pointer and AA info.
11487                          LLD->getChain(), Addr, MachinePointerInfo(),
11488                          LLD->isVolatile(), LLD->isNonTemporal(),
11489                          isInvariant, Alignment);
11490     } else {
11491       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11492                             RLD->getExtensionType() : LLD->getExtensionType(),
11493                             SDLoc(TheSelect),
11494                             TheSelect->getValueType(0),
11495                             // FIXME: Discards pointer and AA info.
11496                             LLD->getChain(), Addr, MachinePointerInfo(),
11497                             LLD->getMemoryVT(), LLD->isVolatile(),
11498                             LLD->isNonTemporal(), isInvariant, Alignment);
11499     }
11500
11501     // Users of the select now use the result of the load.
11502     CombineTo(TheSelect, Load);
11503
11504     // Users of the old loads now use the new load's chain.  We know the
11505     // old-load value is dead now.
11506     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11507     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11508     return true;
11509   }
11510
11511   return false;
11512 }
11513
11514 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11515 /// where 'cond' is the comparison specified by CC.
11516 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11517                                       SDValue N2, SDValue N3,
11518                                       ISD::CondCode CC, bool NotExtCompare) {
11519   // (x ? y : y) -> y.
11520   if (N2 == N3) return N2;
11521
11522   EVT VT = N2.getValueType();
11523   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11524   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11525   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11526
11527   // Determine if the condition we're dealing with is constant
11528   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11529                               N0, N1, CC, DL, false);
11530   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11531   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11532
11533   // fold select_cc true, x, y -> x
11534   if (SCCC && !SCCC->isNullValue())
11535     return N2;
11536   // fold select_cc false, x, y -> y
11537   if (SCCC && SCCC->isNullValue())
11538     return N3;
11539
11540   // Check to see if we can simplify the select into an fabs node
11541   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11542     // Allow either -0.0 or 0.0
11543     if (CFP->getValueAPF().isZero()) {
11544       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11545       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11546           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11547           N2 == N3.getOperand(0))
11548         return DAG.getNode(ISD::FABS, DL, VT, N0);
11549
11550       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11551       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11552           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11553           N2.getOperand(0) == N3)
11554         return DAG.getNode(ISD::FABS, DL, VT, N3);
11555     }
11556   }
11557
11558   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11559   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11560   // in it.  This is a win when the constant is not otherwise available because
11561   // it replaces two constant pool loads with one.  We only do this if the FP
11562   // type is known to be legal, because if it isn't, then we are before legalize
11563   // types an we want the other legalization to happen first (e.g. to avoid
11564   // messing with soft float) and if the ConstantFP is not legal, because if
11565   // it is legal, we may not need to store the FP constant in a constant pool.
11566   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11567     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11568       if (TLI.isTypeLegal(N2.getValueType()) &&
11569           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11570                TargetLowering::Legal &&
11571            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11572            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11573           // If both constants have multiple uses, then we won't need to do an
11574           // extra load, they are likely around in registers for other users.
11575           (TV->hasOneUse() || FV->hasOneUse())) {
11576         Constant *Elts[] = {
11577           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11578           const_cast<ConstantFP*>(TV->getConstantFPValue())
11579         };
11580         Type *FPTy = Elts[0]->getType();
11581         const DataLayout &TD = *TLI.getDataLayout();
11582
11583         // Create a ConstantArray of the two constants.
11584         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11585         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11586                                             TD.getPrefTypeAlignment(FPTy));
11587         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11588
11589         // Get the offsets to the 0 and 1 element of the array so that we can
11590         // select between them.
11591         SDValue Zero = DAG.getIntPtrConstant(0);
11592         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11593         SDValue One = DAG.getIntPtrConstant(EltSize);
11594
11595         SDValue Cond = DAG.getSetCC(DL,
11596                                     getSetCCResultType(N0.getValueType()),
11597                                     N0, N1, CC);
11598         AddToWorklist(Cond.getNode());
11599         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11600                                           Cond, One, Zero);
11601         AddToWorklist(CstOffset.getNode());
11602         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11603                             CstOffset);
11604         AddToWorklist(CPIdx.getNode());
11605         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11606                            MachinePointerInfo::getConstantPool(), false,
11607                            false, false, Alignment);
11608
11609       }
11610     }
11611
11612   // Check to see if we can perform the "gzip trick", transforming
11613   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11614   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11615       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11616        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11617     EVT XType = N0.getValueType();
11618     EVT AType = N2.getValueType();
11619     if (XType.bitsGE(AType)) {
11620       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11621       // single-bit constant.
11622       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11623         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11624         ShCtV = XType.getSizeInBits()-ShCtV-1;
11625         SDValue ShCt = DAG.getConstant(ShCtV,
11626                                        getShiftAmountTy(N0.getValueType()));
11627         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11628                                     XType, N0, ShCt);
11629         AddToWorklist(Shift.getNode());
11630
11631         if (XType.bitsGT(AType)) {
11632           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11633           AddToWorklist(Shift.getNode());
11634         }
11635
11636         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11637       }
11638
11639       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11640                                   XType, N0,
11641                                   DAG.getConstant(XType.getSizeInBits()-1,
11642                                          getShiftAmountTy(N0.getValueType())));
11643       AddToWorklist(Shift.getNode());
11644
11645       if (XType.bitsGT(AType)) {
11646         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11647         AddToWorklist(Shift.getNode());
11648       }
11649
11650       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11651     }
11652   }
11653
11654   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11655   // where y is has a single bit set.
11656   // A plaintext description would be, we can turn the SELECT_CC into an AND
11657   // when the condition can be materialized as an all-ones register.  Any
11658   // single bit-test can be materialized as an all-ones register with
11659   // shift-left and shift-right-arith.
11660   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11661       N0->getValueType(0) == VT &&
11662       N1C && N1C->isNullValue() &&
11663       N2C && N2C->isNullValue()) {
11664     SDValue AndLHS = N0->getOperand(0);
11665     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11666     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11667       // Shift the tested bit over the sign bit.
11668       APInt AndMask = ConstAndRHS->getAPIntValue();
11669       SDValue ShlAmt =
11670         DAG.getConstant(AndMask.countLeadingZeros(),
11671                         getShiftAmountTy(AndLHS.getValueType()));
11672       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11673
11674       // Now arithmetic right shift it all the way over, so the result is either
11675       // all-ones, or zero.
11676       SDValue ShrAmt =
11677         DAG.getConstant(AndMask.getBitWidth()-1,
11678                         getShiftAmountTy(Shl.getValueType()));
11679       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11680
11681       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11682     }
11683   }
11684
11685   // fold select C, 16, 0 -> shl C, 4
11686   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11687       TLI.getBooleanContents(N0.getValueType()) ==
11688           TargetLowering::ZeroOrOneBooleanContent) {
11689
11690     // If the caller doesn't want us to simplify this into a zext of a compare,
11691     // don't do it.
11692     if (NotExtCompare && N2C->getAPIntValue() == 1)
11693       return SDValue();
11694
11695     // Get a SetCC of the condition
11696     // NOTE: Don't create a SETCC if it's not legal on this target.
11697     if (!LegalOperations ||
11698         TLI.isOperationLegal(ISD::SETCC,
11699           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11700       SDValue Temp, SCC;
11701       // cast from setcc result type to select result type
11702       if (LegalTypes) {
11703         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11704                             N0, N1, CC);
11705         if (N2.getValueType().bitsLT(SCC.getValueType()))
11706           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11707                                         N2.getValueType());
11708         else
11709           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11710                              N2.getValueType(), SCC);
11711       } else {
11712         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11713         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11714                            N2.getValueType(), SCC);
11715       }
11716
11717       AddToWorklist(SCC.getNode());
11718       AddToWorklist(Temp.getNode());
11719
11720       if (N2C->getAPIntValue() == 1)
11721         return Temp;
11722
11723       // shl setcc result by log2 n2c
11724       return DAG.getNode(
11725           ISD::SHL, DL, N2.getValueType(), Temp,
11726           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11727                           getShiftAmountTy(Temp.getValueType())));
11728     }
11729   }
11730
11731   // Check to see if this is the equivalent of setcc
11732   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11733   // otherwise, go ahead with the folds.
11734   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11735     EVT XType = N0.getValueType();
11736     if (!LegalOperations ||
11737         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11738       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11739       if (Res.getValueType() != VT)
11740         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11741       return Res;
11742     }
11743
11744     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11745     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11746         (!LegalOperations ||
11747          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11748       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11749       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11750                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11751                                        getShiftAmountTy(Ctlz.getValueType())));
11752     }
11753     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11754     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11755       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11756                                   XType, DAG.getConstant(0, XType), N0);
11757       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11758       return DAG.getNode(ISD::SRL, DL, XType,
11759                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11760                          DAG.getConstant(XType.getSizeInBits()-1,
11761                                          getShiftAmountTy(XType)));
11762     }
11763     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11764     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11765       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11766                                  DAG.getConstant(XType.getSizeInBits()-1,
11767                                          getShiftAmountTy(N0.getValueType())));
11768       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11769     }
11770   }
11771
11772   // Check to see if this is an integer abs.
11773   // select_cc setg[te] X,  0,  X, -X ->
11774   // select_cc setgt    X, -1,  X, -X ->
11775   // select_cc setl[te] X,  0, -X,  X ->
11776   // select_cc setlt    X,  1, -X,  X ->
11777   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11778   if (N1C) {
11779     ConstantSDNode *SubC = nullptr;
11780     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11781          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11782         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11783       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11784     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11785               (N1C->isOne() && CC == ISD::SETLT)) &&
11786              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11787       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11788
11789     EVT XType = N0.getValueType();
11790     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11791       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11792                                   N0,
11793                                   DAG.getConstant(XType.getSizeInBits()-1,
11794                                          getShiftAmountTy(N0.getValueType())));
11795       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11796                                 XType, N0, Shift);
11797       AddToWorklist(Shift.getNode());
11798       AddToWorklist(Add.getNode());
11799       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11800     }
11801   }
11802
11803   return SDValue();
11804 }
11805
11806 /// This is a stub for TargetLowering::SimplifySetCC.
11807 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11808                                    SDValue N1, ISD::CondCode Cond,
11809                                    SDLoc DL, bool foldBooleans) {
11810   TargetLowering::DAGCombinerInfo
11811     DagCombineInfo(DAG, Level, false, this);
11812   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11813 }
11814
11815 /// Given an ISD::SDIV node expressing a divide by constant, return
11816 /// a DAG expression to select that will generate the same value by multiplying
11817 /// by a magic number.
11818 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11819 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11820   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11821   if (!C)
11822     return SDValue();
11823
11824   // Avoid division by zero.
11825   if (!C->getAPIntValue())
11826     return SDValue();
11827
11828   std::vector<SDNode*> Built;
11829   SDValue S =
11830       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11831
11832   for (SDNode *N : Built)
11833     AddToWorklist(N);
11834   return S;
11835 }
11836
11837 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11838 /// DAG expression that will generate the same value by right shifting.
11839 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11840   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11841   if (!C)
11842     return SDValue();
11843
11844   // Avoid division by zero.
11845   if (!C->getAPIntValue())
11846     return SDValue();
11847
11848   std::vector<SDNode *> Built;
11849   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11850
11851   for (SDNode *N : Built)
11852     AddToWorklist(N);
11853   return S;
11854 }
11855
11856 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11857 /// expression that will generate the same value by multiplying by a magic
11858 /// number.
11859 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11860 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11861   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11862   if (!C)
11863     return SDValue();
11864
11865   // Avoid division by zero.
11866   if (!C->getAPIntValue())
11867     return SDValue();
11868
11869   std::vector<SDNode*> Built;
11870   SDValue S =
11871       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11872
11873   for (SDNode *N : Built)
11874     AddToWorklist(N);
11875   return S;
11876 }
11877
11878 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11879   if (Level >= AfterLegalizeDAG)
11880     return SDValue();
11881
11882   // Expose the DAG combiner to the target combiner implementations.
11883   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11884
11885   unsigned Iterations = 0;
11886   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11887     if (Iterations) {
11888       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11889       // For the reciprocal, we need to find the zero of the function:
11890       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11891       //     =>
11892       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11893       //     does not require additional intermediate precision]
11894       EVT VT = Op.getValueType();
11895       SDLoc DL(Op);
11896       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11897
11898       AddToWorklist(Est.getNode());
11899
11900       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11901       for (unsigned i = 0; i < Iterations; ++i) {
11902         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11903         AddToWorklist(NewEst.getNode());
11904
11905         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11906         AddToWorklist(NewEst.getNode());
11907
11908         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11909         AddToWorklist(NewEst.getNode());
11910
11911         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11912         AddToWorklist(Est.getNode());
11913       }
11914     }
11915     return Est;
11916   }
11917
11918   return SDValue();
11919 }
11920
11921 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
11922   if (Level >= AfterLegalizeDAG)
11923     return SDValue();
11924
11925   // Expose the DAG combiner to the target combiner implementations.
11926   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11927   unsigned Iterations = 0;
11928   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations)) {
11929     if (Iterations) {
11930       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11931       // For the reciprocal sqrt, we need to find the zero of the function:
11932       //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
11933       //     =>
11934       //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
11935       // As a result, we precompute A/2 prior to the iteration loop.
11936       EVT VT = Op.getValueType();
11937       SDLoc DL(Op);
11938       SDValue FPThreeHalves = DAG.getConstantFP(1.5, VT);
11939
11940       AddToWorklist(Est.getNode());
11941
11942       // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
11943       // this entire sequence requires only one FP constant.
11944       SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, FPThreeHalves, Op);
11945       AddToWorklist(HalfArg.getNode());
11946
11947       HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Op);
11948       AddToWorklist(HalfArg.getNode());
11949
11950       // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
11951       for (unsigned i = 0; i < Iterations; ++i) {
11952         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
11953         AddToWorklist(NewEst.getNode());
11954
11955         NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
11956         AddToWorklist(NewEst.getNode());
11957
11958         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPThreeHalves, NewEst);
11959         AddToWorklist(NewEst.getNode());
11960
11961         Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11962         AddToWorklist(Est.getNode());
11963       }
11964     }
11965     return Est;
11966   }
11967
11968   return SDValue();
11969 }
11970
11971 /// Return true if base is a frame index, which is known not to alias with
11972 /// anything but itself.  Provides base object and offset as results.
11973 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11974                            const GlobalValue *&GV, const void *&CV) {
11975   // Assume it is a primitive operation.
11976   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11977
11978   // If it's an adding a simple constant then integrate the offset.
11979   if (Base.getOpcode() == ISD::ADD) {
11980     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11981       Base = Base.getOperand(0);
11982       Offset += C->getZExtValue();
11983     }
11984   }
11985
11986   // Return the underlying GlobalValue, and update the Offset.  Return false
11987   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11988   // by multiple nodes with different offsets.
11989   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11990     GV = G->getGlobal();
11991     Offset += G->getOffset();
11992     return false;
11993   }
11994
11995   // Return the underlying Constant value, and update the Offset.  Return false
11996   // for ConstantSDNodes since the same constant pool entry may be represented
11997   // by multiple nodes with different offsets.
11998   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11999     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12000                                          : (const void *)C->getConstVal();
12001     Offset += C->getOffset();
12002     return false;
12003   }
12004   // If it's any of the following then it can't alias with anything but itself.
12005   return isa<FrameIndexSDNode>(Base);
12006 }
12007
12008 /// Return true if there is any possibility that the two addresses overlap.
12009 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12010   // If they are the same then they must be aliases.
12011   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12012
12013   // If they are both volatile then they cannot be reordered.
12014   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12015
12016   // Gather base node and offset information.
12017   SDValue Base1, Base2;
12018   int64_t Offset1, Offset2;
12019   const GlobalValue *GV1, *GV2;
12020   const void *CV1, *CV2;
12021   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12022                                       Base1, Offset1, GV1, CV1);
12023   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12024                                       Base2, Offset2, GV2, CV2);
12025
12026   // If they have a same base address then check to see if they overlap.
12027   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12028     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12029              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12030
12031   // It is possible for different frame indices to alias each other, mostly
12032   // when tail call optimization reuses return address slots for arguments.
12033   // To catch this case, look up the actual index of frame indices to compute
12034   // the real alias relationship.
12035   if (isFrameIndex1 && isFrameIndex2) {
12036     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12037     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12038     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12039     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12040              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12041   }
12042
12043   // Otherwise, if we know what the bases are, and they aren't identical, then
12044   // we know they cannot alias.
12045   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12046     return false;
12047
12048   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12049   // compared to the size and offset of the access, we may be able to prove they
12050   // do not alias.  This check is conservative for now to catch cases created by
12051   // splitting vector types.
12052   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12053       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12054       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12055        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12056       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12057     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12058     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12059
12060     // There is no overlap between these relatively aligned accesses of similar
12061     // size, return no alias.
12062     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12063         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12064       return false;
12065   }
12066
12067   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12068                    ? CombinerGlobalAA
12069                    : DAG.getSubtarget().useAA();
12070 #ifndef NDEBUG
12071   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12072       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12073     UseAA = false;
12074 #endif
12075   if (UseAA &&
12076       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12077     // Use alias analysis information.
12078     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12079                                  Op1->getSrcValueOffset());
12080     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12081         Op0->getSrcValueOffset() - MinOffset;
12082     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12083         Op1->getSrcValueOffset() - MinOffset;
12084     AliasAnalysis::AliasResult AAResult =
12085         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12086                                          Overlap1,
12087                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12088                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12089                                          Overlap2,
12090                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12091     if (AAResult == AliasAnalysis::NoAlias)
12092       return false;
12093   }
12094
12095   // Otherwise we have to assume they alias.
12096   return true;
12097 }
12098
12099 /// Walk up chain skipping non-aliasing memory nodes,
12100 /// looking for aliasing nodes and adding them to the Aliases vector.
12101 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12102                                    SmallVectorImpl<SDValue> &Aliases) {
12103   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12104   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12105
12106   // Get alias information for node.
12107   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12108
12109   // Starting off.
12110   Chains.push_back(OriginalChain);
12111   unsigned Depth = 0;
12112
12113   // Look at each chain and determine if it is an alias.  If so, add it to the
12114   // aliases list.  If not, then continue up the chain looking for the next
12115   // candidate.
12116   while (!Chains.empty()) {
12117     SDValue Chain = Chains.back();
12118     Chains.pop_back();
12119
12120     // For TokenFactor nodes, look at each operand and only continue up the
12121     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12122     // find more and revert to original chain since the xform is unlikely to be
12123     // profitable.
12124     //
12125     // FIXME: The depth check could be made to return the last non-aliasing
12126     // chain we found before we hit a tokenfactor rather than the original
12127     // chain.
12128     if (Depth > 6 || Aliases.size() == 2) {
12129       Aliases.clear();
12130       Aliases.push_back(OriginalChain);
12131       return;
12132     }
12133
12134     // Don't bother if we've been before.
12135     if (!Visited.insert(Chain.getNode()))
12136       continue;
12137
12138     switch (Chain.getOpcode()) {
12139     case ISD::EntryToken:
12140       // Entry token is ideal chain operand, but handled in FindBetterChain.
12141       break;
12142
12143     case ISD::LOAD:
12144     case ISD::STORE: {
12145       // Get alias information for Chain.
12146       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12147           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12148
12149       // If chain is alias then stop here.
12150       if (!(IsLoad && IsOpLoad) &&
12151           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12152         Aliases.push_back(Chain);
12153       } else {
12154         // Look further up the chain.
12155         Chains.push_back(Chain.getOperand(0));
12156         ++Depth;
12157       }
12158       break;
12159     }
12160
12161     case ISD::TokenFactor:
12162       // We have to check each of the operands of the token factor for "small"
12163       // token factors, so we queue them up.  Adding the operands to the queue
12164       // (stack) in reverse order maintains the original order and increases the
12165       // likelihood that getNode will find a matching token factor (CSE.)
12166       if (Chain.getNumOperands() > 16) {
12167         Aliases.push_back(Chain);
12168         break;
12169       }
12170       for (unsigned n = Chain.getNumOperands(); n;)
12171         Chains.push_back(Chain.getOperand(--n));
12172       ++Depth;
12173       break;
12174
12175     default:
12176       // For all other instructions we will just have to take what we can get.
12177       Aliases.push_back(Chain);
12178       break;
12179     }
12180   }
12181
12182   // We need to be careful here to also search for aliases through the
12183   // value operand of a store, etc. Consider the following situation:
12184   //   Token1 = ...
12185   //   L1 = load Token1, %52
12186   //   S1 = store Token1, L1, %51
12187   //   L2 = load Token1, %52+8
12188   //   S2 = store Token1, L2, %51+8
12189   //   Token2 = Token(S1, S2)
12190   //   L3 = load Token2, %53
12191   //   S3 = store Token2, L3, %52
12192   //   L4 = load Token2, %53+8
12193   //   S4 = store Token2, L4, %52+8
12194   // If we search for aliases of S3 (which loads address %52), and we look
12195   // only through the chain, then we'll miss the trivial dependence on L1
12196   // (which also loads from %52). We then might change all loads and
12197   // stores to use Token1 as their chain operand, which could result in
12198   // copying %53 into %52 before copying %52 into %51 (which should
12199   // happen first).
12200   //
12201   // The problem is, however, that searching for such data dependencies
12202   // can become expensive, and the cost is not directly related to the
12203   // chain depth. Instead, we'll rule out such configurations here by
12204   // insisting that we've visited all chain users (except for users
12205   // of the original chain, which is not necessary). When doing this,
12206   // we need to look through nodes we don't care about (otherwise, things
12207   // like register copies will interfere with trivial cases).
12208
12209   SmallVector<const SDNode *, 16> Worklist;
12210   for (const SDNode *N : Visited)
12211     if (N != OriginalChain.getNode())
12212       Worklist.push_back(N);
12213
12214   while (!Worklist.empty()) {
12215     const SDNode *M = Worklist.pop_back_val();
12216
12217     // We have already visited M, and want to make sure we've visited any uses
12218     // of M that we care about. For uses that we've not visisted, and don't
12219     // care about, queue them to the worklist.
12220
12221     for (SDNode::use_iterator UI = M->use_begin(),
12222          UIE = M->use_end(); UI != UIE; ++UI)
12223       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12224         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12225           // We've not visited this use, and we care about it (it could have an
12226           // ordering dependency with the original node).
12227           Aliases.clear();
12228           Aliases.push_back(OriginalChain);
12229           return;
12230         }
12231
12232         // We've not visited this use, but we don't care about it. Mark it as
12233         // visited and enqueue it to the worklist.
12234         Worklist.push_back(*UI);
12235       }
12236   }
12237 }
12238
12239 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12240 /// (aliasing node.)
12241 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12242   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12243
12244   // Accumulate all the aliases to this node.
12245   GatherAllAliases(N, OldChain, Aliases);
12246
12247   // If no operands then chain to entry token.
12248   if (Aliases.size() == 0)
12249     return DAG.getEntryNode();
12250
12251   // If a single operand then chain to it.  We don't need to revisit it.
12252   if (Aliases.size() == 1)
12253     return Aliases[0];
12254
12255   // Construct a custom tailored token factor.
12256   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12257 }
12258
12259 /// This is the entry point for the file.
12260 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12261                            CodeGenOpt::Level OptLevel) {
12262   /// This is the main entry point to this class.
12263   DAGCombiner(*this, AA, OptLevel).Run(Level);
12264 }