Strength reduce constant-sized vectors into arrays. No functionality change.
[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 visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306
307     SDValue XformToShuffleWithZero(SDNode *N);
308     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
309
310     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
311
312     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
313     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
314     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
315     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
316                              SDValue N3, ISD::CondCode CC,
317                              bool NotExtCompare = false);
318     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
319                           SDLoc DL, bool foldBooleans = true);
320
321     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
322                            SDValue &CC) const;
323     bool isOneUseSetCC(SDValue N) const;
324
325     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
326                                          unsigned HiOp);
327     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
328     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
329     SDValue BuildSDIV(SDNode *N);
330     SDValue BuildSDIVPow2(SDNode *N);
331     SDValue BuildUDIV(SDNode *N);
332     SDValue BuildReciprocalEstimate(SDValue Op);
333     SDValue BuildRsqrtEstimate(SDValue Op);
334     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
335                                bool DemandHighBits = true);
336     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
337     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
338                               SDValue InnerPos, SDValue InnerNeg,
339                               unsigned PosOpcode, unsigned NegOpcode,
340                               SDLoc DL);
341     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
342     SDValue ReduceLoadWidth(SDNode *N);
343     SDValue ReduceLoadOpStoreWidth(SDNode *N);
344     SDValue TransformFPLoadStorePair(SDNode *N);
345     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
346     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
347
348     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
349
350     /// Walk up chain skipping non-aliasing memory nodes,
351     /// looking for aliasing nodes and adding them to the Aliases vector.
352     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
353                           SmallVectorImpl<SDValue> &Aliases);
354
355     /// Return true if there is any possibility that the two addresses overlap.
356     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
357
358     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
359     /// chain (aliasing node.)
360     SDValue FindBetterChain(SDNode *N, SDValue Chain);
361
362     /// Merge consecutive store operations into a wide store.
363     /// This optimization uses wide integers or vectors when possible.
364     /// \return True if some memory operations were changed.
365     bool MergeConsecutiveStores(StoreSDNode *N);
366
367     /// \brief Try to transform a truncation where C is a constant:
368     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
369     ///
370     /// \p N needs to be a truncation and its first operand an AND. Other
371     /// requirements are checked by the function (e.g. that trunc is
372     /// single-use) and if missed an empty SDValue is returned.
373     SDValue distributeTruncateThroughAnd(SDNode *N);
374
375   public:
376     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
377         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
378           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
379       AttributeSet FnAttrs =
380           DAG.getMachineFunction().getFunction()->getAttributes();
381       ForCodeSize =
382           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
383                                Attribute::OptimizeForSize) ||
384           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
385     }
386
387     /// Runs the dag combiner on all nodes in the work list
388     void Run(CombineLevel AtLevel);
389
390     SelectionDAG &getDAG() const { return DAG; }
391
392     /// Returns a type large enough to hold any valid shift amount - before type
393     /// legalization these can be huge.
394     EVT getShiftAmountTy(EVT LHSTy) {
395       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
396       if (LHSTy.isVector())
397         return LHSTy;
398       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
399                         : TLI.getPointerTy();
400     }
401
402     /// This method returns true if we are running before type legalization or
403     /// if the specified VT is legal.
404     bool isTypeLegal(const EVT &VT) {
405       if (!LegalTypes) return true;
406       return TLI.isTypeLegal(VT);
407     }
408
409     /// Convenience wrapper around TargetLowering::getSetCCResultType
410     EVT getSetCCResultType(EVT VT) const {
411       return TLI.getSetCCResultType(*DAG.getContext(), VT);
412     }
413   };
414 }
415
416
417 namespace {
418 /// This class is a DAGUpdateListener that removes any deleted
419 /// nodes from the worklist.
420 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
421   DAGCombiner &DC;
422 public:
423   explicit WorklistRemover(DAGCombiner &dc)
424     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
425
426   void NodeDeleted(SDNode *N, SDNode *E) override {
427     DC.removeFromWorklist(N);
428   }
429 };
430 }
431
432 //===----------------------------------------------------------------------===//
433 //  TargetLowering::DAGCombinerInfo implementation
434 //===----------------------------------------------------------------------===//
435
436 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
437   ((DAGCombiner*)DC)->AddToWorklist(N);
438 }
439
440 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
441   ((DAGCombiner*)DC)->removeFromWorklist(N);
442 }
443
444 SDValue TargetLowering::DAGCombinerInfo::
445 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
446   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
447 }
448
449 SDValue TargetLowering::DAGCombinerInfo::
450 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
451   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
452 }
453
454
455 SDValue TargetLowering::DAGCombinerInfo::
456 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
457   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
458 }
459
460 void TargetLowering::DAGCombinerInfo::
461 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
462   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
463 }
464
465 //===----------------------------------------------------------------------===//
466 // Helper Functions
467 //===----------------------------------------------------------------------===//
468
469 void DAGCombiner::deleteAndRecombine(SDNode *N) {
470   removeFromWorklist(N);
471
472   // If the operands of this node are only used by the node, they will now be
473   // dead. Make sure to re-visit them and recursively delete dead nodes.
474   for (const SDValue &Op : N->ops())
475     // For an operand generating multiple values, one of the values may
476     // become dead allowing further simplification (e.g. split index
477     // arithmetic from an indexed load).
478     if (Op->hasOneUse() || Op->getNumValues() > 1)
479       AddToWorklist(Op.getNode());
480
481   DAG.DeleteNode(N);
482 }
483
484 /// Return 1 if we can compute the negated form of the specified expression for
485 /// the same cost as the expression itself, or 2 if we can compute the negated
486 /// form more cheaply than the expression itself.
487 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
488                                const TargetLowering &TLI,
489                                const TargetOptions *Options,
490                                unsigned Depth = 0) {
491   // fneg is removable even if it has multiple uses.
492   if (Op.getOpcode() == ISD::FNEG) return 2;
493
494   // Don't allow anything with multiple uses.
495   if (!Op.hasOneUse()) return 0;
496
497   // Don't recurse exponentially.
498   if (Depth > 6) return 0;
499
500   switch (Op.getOpcode()) {
501   default: return false;
502   case ISD::ConstantFP:
503     // Don't invert constant FP values after legalize.  The negated constant
504     // isn't necessarily legal.
505     return LegalOperations ? 0 : 1;
506   case ISD::FADD:
507     // FIXME: determine better conditions for this xform.
508     if (!Options->UnsafeFPMath) return 0;
509
510     // After operation legalization, it might not be legal to create new FSUBs.
511     if (LegalOperations &&
512         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
513       return 0;
514
515     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
516     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
517                                     Options, Depth + 1))
518       return V;
519     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
520     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
521                               Depth + 1);
522   case ISD::FSUB:
523     // We can't turn -(A-B) into B-A when we honor signed zeros.
524     if (!Options->UnsafeFPMath) return 0;
525
526     // fold (fneg (fsub A, B)) -> (fsub B, A)
527     return 1;
528
529   case ISD::FMUL:
530   case ISD::FDIV:
531     if (Options->HonorSignDependentRoundingFPMath()) return 0;
532
533     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
534     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
535                                     Options, Depth + 1))
536       return V;
537
538     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
539                               Depth + 1);
540
541   case ISD::FP_EXTEND:
542   case ISD::FP_ROUND:
543   case ISD::FSIN:
544     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
545                               Depth + 1);
546   }
547 }
548
549 /// If isNegatibleForFree returns true, return the newly negated expression.
550 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
551                                     bool LegalOperations, unsigned Depth = 0) {
552   const TargetOptions &Options = DAG.getTarget().Options;
553   // fneg is removable even if it has multiple uses.
554   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
555
556   // Don't allow anything with multiple uses.
557   assert(Op.hasOneUse() && "Unknown reuse!");
558
559   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
560   switch (Op.getOpcode()) {
561   default: llvm_unreachable("Unknown code");
562   case ISD::ConstantFP: {
563     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
564     V.changeSign();
565     return DAG.getConstantFP(V, Op.getValueType());
566   }
567   case ISD::FADD:
568     // FIXME: determine better conditions for this xform.
569     assert(Options.UnsafeFPMath);
570
571     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
572     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
574       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
575                          GetNegatedExpression(Op.getOperand(0), DAG,
576                                               LegalOperations, Depth+1),
577                          Op.getOperand(1));
578     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
579     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
580                        GetNegatedExpression(Op.getOperand(1), DAG,
581                                             LegalOperations, Depth+1),
582                        Op.getOperand(0));
583   case ISD::FSUB:
584     // We can't turn -(A-B) into B-A when we honor signed zeros.
585     assert(Options.UnsafeFPMath);
586
587     // fold (fneg (fsub 0, B)) -> B
588     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
589       if (N0CFP->getValueAPF().isZero())
590         return Op.getOperand(1);
591
592     // fold (fneg (fsub A, B)) -> (fsub B, A)
593     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
594                        Op.getOperand(1), Op.getOperand(0));
595
596   case ISD::FMUL:
597   case ISD::FDIV:
598     assert(!Options.HonorSignDependentRoundingFPMath());
599
600     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
601     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
602                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
603       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
604                          GetNegatedExpression(Op.getOperand(0), DAG,
605                                               LegalOperations, Depth+1),
606                          Op.getOperand(1));
607
608     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
609     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
610                        Op.getOperand(0),
611                        GetNegatedExpression(Op.getOperand(1), DAG,
612                                             LegalOperations, Depth+1));
613
614   case ISD::FP_EXTEND:
615   case ISD::FSIN:
616     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
617                        GetNegatedExpression(Op.getOperand(0), DAG,
618                                             LegalOperations, Depth+1));
619   case ISD::FP_ROUND:
620       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
621                          GetNegatedExpression(Op.getOperand(0), DAG,
622                                               LegalOperations, Depth+1),
623                          Op.getOperand(1));
624   }
625 }
626
627 // Return true if this node is a setcc, or is a select_cc
628 // that selects between the target values used for true and false, making it
629 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
630 // the appropriate nodes based on the type of node we are checking. This
631 // simplifies life a bit for the callers.
632 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
633                                     SDValue &CC) const {
634   if (N.getOpcode() == ISD::SETCC) {
635     LHS = N.getOperand(0);
636     RHS = N.getOperand(1);
637     CC  = N.getOperand(2);
638     return true;
639   }
640
641   if (N.getOpcode() != ISD::SELECT_CC ||
642       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
643       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
644     return false;
645
646   LHS = N.getOperand(0);
647   RHS = N.getOperand(1);
648   CC  = N.getOperand(4);
649   return true;
650 }
651
652 /// Return true if this is a SetCC-equivalent operation with only one use.
653 /// If this is true, it allows the users to invert the operation for free when
654 /// it is profitable to do so.
655 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
656   SDValue N0, N1, N2;
657   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
658     return true;
659   return false;
660 }
661
662 /// Returns true if N is a BUILD_VECTOR node whose
663 /// elements are all the same constant or undefined.
664 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
665   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
666   if (!C)
667     return false;
668
669   APInt SplatUndef;
670   unsigned SplatBitSize;
671   bool HasAnyUndefs;
672   EVT EltVT = N->getValueType(0).getVectorElementType();
673   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
674                              HasAnyUndefs) &&
675           EltVT.getSizeInBits() >= SplatBitSize);
676 }
677
678 // \brief Returns the SDNode if it is a constant BuildVector or constant.
679 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
680   if (isa<ConstantSDNode>(N))
681     return N.getNode();
682   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
683   if (BV && BV->isConstant())
684     return BV;
685   return nullptr;
686 }
687
688 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
689 // int.
690 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
691   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
692     return CN;
693
694   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
695     BitVector UndefElements;
696     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
697
698     // BuildVectors can truncate their operands. Ignore that case here.
699     // FIXME: We blindly ignore splats which include undef which is overly
700     // pessimistic.
701     if (CN && UndefElements.none() &&
702         CN->getValueType(0) == N.getValueType().getScalarType())
703       return CN;
704   }
705
706   return nullptr;
707 }
708
709 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
710 // float.
711 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
712   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
713     return CN;
714
715   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
716     BitVector UndefElements;
717     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
718
719     if (CN && UndefElements.none())
720       return CN;
721   }
722
723   return nullptr;
724 }
725
726 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
727                                     SDValue N0, SDValue N1) {
728   EVT VT = N0.getValueType();
729   if (N0.getOpcode() == Opc) {
730     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
731       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
732         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
733         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
734         if (!OpNode.getNode())
735           return SDValue();
736         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
737       }
738       if (N0.hasOneUse()) {
739         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
740         // use
741         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
742         if (!OpNode.getNode())
743           return SDValue();
744         AddToWorklist(OpNode.getNode());
745         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
746       }
747     }
748   }
749
750   if (N1.getOpcode() == Opc) {
751     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
752       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
753         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
754         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
755         if (!OpNode.getNode())
756           return SDValue();
757         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
758       }
759       if (N1.hasOneUse()) {
760         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
761         // use
762         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
763         if (!OpNode.getNode())
764           return SDValue();
765         AddToWorklist(OpNode.getNode());
766         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
767       }
768     }
769   }
770
771   return SDValue();
772 }
773
774 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
775                                bool AddTo) {
776   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
777   ++NodesCombined;
778   DEBUG(dbgs() << "\nReplacing.1 ";
779         N->dump(&DAG);
780         dbgs() << "\nWith: ";
781         To[0].getNode()->dump(&DAG);
782         dbgs() << " and " << NumTo-1 << " other values\n";
783         for (unsigned i = 0, e = NumTo; i != e; ++i)
784           assert((!To[i].getNode() ||
785                   N->getValueType(i) == To[i].getValueType()) &&
786                  "Cannot combine value to value of different type!"));
787   WorklistRemover DeadNodes(*this);
788   DAG.ReplaceAllUsesWith(N, To);
789   if (AddTo) {
790     // Push the new nodes and any users onto the worklist
791     for (unsigned i = 0, e = NumTo; i != e; ++i) {
792       if (To[i].getNode()) {
793         AddToWorklist(To[i].getNode());
794         AddUsersToWorklist(To[i].getNode());
795       }
796     }
797   }
798
799   // Finally, if the node is now dead, remove it from the graph.  The node
800   // may not be dead if the replacement process recursively simplified to
801   // something else needing this node.
802   if (N->use_empty())
803     deleteAndRecombine(N);
804   return SDValue(N, 0);
805 }
806
807 void DAGCombiner::
808 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
809   // Replace all uses.  If any nodes become isomorphic to other nodes and
810   // are deleted, make sure to remove them from our worklist.
811   WorklistRemover DeadNodes(*this);
812   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813
814   // Push the new node and any (possibly new) users onto the worklist.
815   AddToWorklist(TLO.New.getNode());
816   AddUsersToWorklist(TLO.New.getNode());
817
818   // Finally, if the node is now dead, remove it from the graph.  The node
819   // may not be dead if the replacement process recursively simplified to
820   // something else needing this node.
821   if (TLO.Old.getNode()->use_empty())
822     deleteAndRecombine(TLO.Old.getNode());
823 }
824
825 /// Check the specified integer node value to see if it can be simplified or if
826 /// things it uses can be simplified by bit propagation. If so, return true.
827 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
828   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
829   APInt KnownZero, KnownOne;
830   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
831     return false;
832
833   // Revisit the node.
834   AddToWorklist(Op.getNode());
835
836   // Replace the old value with the new one.
837   ++NodesCombined;
838   DEBUG(dbgs() << "\nReplacing.2 ";
839         TLO.Old.getNode()->dump(&DAG);
840         dbgs() << "\nWith: ";
841         TLO.New.getNode()->dump(&DAG);
842         dbgs() << '\n');
843
844   CommitTargetLoweringOpt(TLO);
845   return true;
846 }
847
848 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
849   SDLoc dl(Load);
850   EVT VT = Load->getValueType(0);
851   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852
853   DEBUG(dbgs() << "\nReplacing.9 ";
854         Load->dump(&DAG);
855         dbgs() << "\nWith: ";
856         Trunc.getNode()->dump(&DAG);
857         dbgs() << '\n');
858   WorklistRemover DeadNodes(*this);
859   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
860   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
861   deleteAndRecombine(Load);
862   AddToWorklist(Trunc.getNode());
863 }
864
865 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
866   Replace = false;
867   SDLoc dl(Op);
868   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
869     EVT MemVT = LD->getMemoryVT();
870     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
871       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
872                                                   : ISD::EXTLOAD)
873       : LD->getExtensionType();
874     Replace = true;
875     return DAG.getExtLoad(ExtType, dl, PVT,
876                           LD->getChain(), LD->getBasePtr(),
877                           MemVT, LD->getMemOperand());
878   }
879
880   unsigned Opc = Op.getOpcode();
881   switch (Opc) {
882   default: break;
883   case ISD::AssertSext:
884     return DAG.getNode(ISD::AssertSext, dl, PVT,
885                        SExtPromoteOperand(Op.getOperand(0), PVT),
886                        Op.getOperand(1));
887   case ISD::AssertZext:
888     return DAG.getNode(ISD::AssertZext, dl, PVT,
889                        ZExtPromoteOperand(Op.getOperand(0), PVT),
890                        Op.getOperand(1));
891   case ISD::Constant: {
892     unsigned ExtOpc =
893       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
894     return DAG.getNode(ExtOpc, dl, PVT, Op);
895   }
896   }
897
898   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
899     return SDValue();
900   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
901 }
902
903 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
904   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
905     return SDValue();
906   EVT OldVT = Op.getValueType();
907   SDLoc dl(Op);
908   bool Replace = false;
909   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
910   if (!NewOp.getNode())
911     return SDValue();
912   AddToWorklist(NewOp.getNode());
913
914   if (Replace)
915     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
916   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
917                      DAG.getValueType(OldVT));
918 }
919
920 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
921   EVT OldVT = Op.getValueType();
922   SDLoc dl(Op);
923   bool Replace = false;
924   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
925   if (!NewOp.getNode())
926     return SDValue();
927   AddToWorklist(NewOp.getNode());
928
929   if (Replace)
930     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
931   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
932 }
933
934 /// Promote the specified integer binary operation if the target indicates it is
935 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
936 /// i32 since i16 instructions are longer.
937 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
938   if (!LegalOperations)
939     return SDValue();
940
941   EVT VT = Op.getValueType();
942   if (VT.isVector() || !VT.isInteger())
943     return SDValue();
944
945   // If operation type is 'undesirable', e.g. i16 on x86, consider
946   // promoting it.
947   unsigned Opc = Op.getOpcode();
948   if (TLI.isTypeDesirableForOp(Opc, VT))
949     return SDValue();
950
951   EVT PVT = VT;
952   // Consult target whether it is a good idea to promote this operation and
953   // what's the right type to promote it to.
954   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
955     assert(PVT != VT && "Don't know what type to promote to!");
956
957     bool Replace0 = false;
958     SDValue N0 = Op.getOperand(0);
959     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
960     if (!NN0.getNode())
961       return SDValue();
962
963     bool Replace1 = false;
964     SDValue N1 = Op.getOperand(1);
965     SDValue NN1;
966     if (N0 == N1)
967       NN1 = NN0;
968     else {
969       NN1 = PromoteOperand(N1, PVT, Replace1);
970       if (!NN1.getNode())
971         return SDValue();
972     }
973
974     AddToWorklist(NN0.getNode());
975     if (NN1.getNode())
976       AddToWorklist(NN1.getNode());
977
978     if (Replace0)
979       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
980     if (Replace1)
981       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982
983     DEBUG(dbgs() << "\nPromoting ";
984           Op.getNode()->dump(&DAG));
985     SDLoc dl(Op);
986     return DAG.getNode(ISD::TRUNCATE, dl, VT,
987                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
988   }
989   return SDValue();
990 }
991
992 /// Promote the specified integer shift operation if the target indicates it is
993 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
994 /// i32 since i16 instructions are longer.
995 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
996   if (!LegalOperations)
997     return SDValue();
998
999   EVT VT = Op.getValueType();
1000   if (VT.isVector() || !VT.isInteger())
1001     return SDValue();
1002
1003   // If operation type is 'undesirable', e.g. i16 on x86, consider
1004   // promoting it.
1005   unsigned Opc = Op.getOpcode();
1006   if (TLI.isTypeDesirableForOp(Opc, VT))
1007     return SDValue();
1008
1009   EVT PVT = VT;
1010   // Consult target whether it is a good idea to promote this operation and
1011   // what's the right type to promote it to.
1012   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1013     assert(PVT != VT && "Don't know what type to promote to!");
1014
1015     bool Replace = false;
1016     SDValue N0 = Op.getOperand(0);
1017     if (Opc == ISD::SRA)
1018       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1019     else if (Opc == ISD::SRL)
1020       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1021     else
1022       N0 = PromoteOperand(N0, PVT, Replace);
1023     if (!N0.getNode())
1024       return SDValue();
1025
1026     AddToWorklist(N0.getNode());
1027     if (Replace)
1028       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029
1030     DEBUG(dbgs() << "\nPromoting ";
1031           Op.getNode()->dump(&DAG));
1032     SDLoc dl(Op);
1033     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1034                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1035   }
1036   return SDValue();
1037 }
1038
1039 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1040   if (!LegalOperations)
1041     return SDValue();
1042
1043   EVT VT = Op.getValueType();
1044   if (VT.isVector() || !VT.isInteger())
1045     return SDValue();
1046
1047   // If operation type is 'undesirable', e.g. i16 on x86, consider
1048   // promoting it.
1049   unsigned Opc = Op.getOpcode();
1050   if (TLI.isTypeDesirableForOp(Opc, VT))
1051     return SDValue();
1052
1053   EVT PVT = VT;
1054   // Consult target whether it is a good idea to promote this operation and
1055   // what's the right type to promote it to.
1056   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1057     assert(PVT != VT && "Don't know what type to promote to!");
1058     // fold (aext (aext x)) -> (aext x)
1059     // fold (aext (zext x)) -> (zext x)
1060     // fold (aext (sext x)) -> (sext x)
1061     DEBUG(dbgs() << "\nPromoting ";
1062           Op.getNode()->dump(&DAG));
1063     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1064   }
1065   return SDValue();
1066 }
1067
1068 bool DAGCombiner::PromoteLoad(SDValue Op) {
1069   if (!LegalOperations)
1070     return false;
1071
1072   EVT VT = Op.getValueType();
1073   if (VT.isVector() || !VT.isInteger())
1074     return false;
1075
1076   // If operation type is 'undesirable', e.g. i16 on x86, consider
1077   // promoting it.
1078   unsigned Opc = Op.getOpcode();
1079   if (TLI.isTypeDesirableForOp(Opc, VT))
1080     return false;
1081
1082   EVT PVT = VT;
1083   // Consult target whether it is a good idea to promote this operation and
1084   // what's the right type to promote it to.
1085   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1086     assert(PVT != VT && "Don't know what type to promote to!");
1087
1088     SDLoc dl(Op);
1089     SDNode *N = Op.getNode();
1090     LoadSDNode *LD = cast<LoadSDNode>(N);
1091     EVT MemVT = LD->getMemoryVT();
1092     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1093       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1094                                                   : ISD::EXTLOAD)
1095       : LD->getExtensionType();
1096     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1097                                    LD->getChain(), LD->getBasePtr(),
1098                                    MemVT, LD->getMemOperand());
1099     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100
1101     DEBUG(dbgs() << "\nPromoting ";
1102           N->dump(&DAG);
1103           dbgs() << "\nTo: ";
1104           Result.getNode()->dump(&DAG);
1105           dbgs() << '\n');
1106     WorklistRemover DeadNodes(*this);
1107     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1108     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1109     deleteAndRecombine(N);
1110     AddToWorklist(Result.getNode());
1111     return true;
1112   }
1113   return false;
1114 }
1115
1116 /// \brief Recursively delete a node which has no uses and any operands for
1117 /// which it is the only use.
1118 ///
1119 /// Note that this both deletes the nodes and removes them from the worklist.
1120 /// It also adds any nodes who have had a user deleted to the worklist as they
1121 /// may now have only one use and subject to other combines.
1122 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1123   if (!N->use_empty())
1124     return false;
1125
1126   SmallSetVector<SDNode *, 16> Nodes;
1127   Nodes.insert(N);
1128   do {
1129     N = Nodes.pop_back_val();
1130     if (!N)
1131       continue;
1132
1133     if (N->use_empty()) {
1134       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1135         Nodes.insert(N->getOperand(i).getNode());
1136
1137       removeFromWorklist(N);
1138       DAG.DeleteNode(N);
1139     } else {
1140       AddToWorklist(N);
1141     }
1142   } while (!Nodes.empty());
1143   return true;
1144 }
1145
1146 //===----------------------------------------------------------------------===//
1147 //  Main DAG Combiner implementation
1148 //===----------------------------------------------------------------------===//
1149
1150 void DAGCombiner::Run(CombineLevel AtLevel) {
1151   // set the instance variables, so that the various visit routines may use it.
1152   Level = AtLevel;
1153   LegalOperations = Level >= AfterLegalizeVectorOps;
1154   LegalTypes = Level >= AfterLegalizeTypes;
1155
1156   // Add all the dag nodes to the worklist.
1157   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1158        E = DAG.allnodes_end(); I != E; ++I)
1159     AddToWorklist(I);
1160
1161   // Create a dummy node (which is not added to allnodes), that adds a reference
1162   // to the root node, preventing it from being deleted, and tracking any
1163   // changes of the root.
1164   HandleSDNode Dummy(DAG.getRoot());
1165
1166   // while the worklist isn't empty, find a node and
1167   // try and combine it.
1168   while (!WorklistMap.empty()) {
1169     SDNode *N;
1170     // The Worklist holds the SDNodes in order, but it may contain null entries.
1171     do {
1172       N = Worklist.pop_back_val();
1173     } while (!N);
1174
1175     bool GoodWorklistEntry = WorklistMap.erase(N);
1176     (void)GoodWorklistEntry;
1177     assert(GoodWorklistEntry &&
1178            "Found a worklist entry without a corresponding map entry!");
1179
1180     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1181     // N is deleted from the DAG, since they too may now be dead or may have a
1182     // reduced number of uses, allowing other xforms.
1183     if (recursivelyDeleteUnusedNodes(N))
1184       continue;
1185
1186     WorklistRemover DeadNodes(*this);
1187
1188     // If this combine is running after legalizing the DAG, re-legalize any
1189     // nodes pulled off the worklist.
1190     if (Level == AfterLegalizeDAG) {
1191       SmallSetVector<SDNode *, 16> UpdatedNodes;
1192       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193
1194       for (SDNode *LN : UpdatedNodes) {
1195         AddToWorklist(LN);
1196         AddUsersToWorklist(LN);
1197       }
1198       if (!NIsValid)
1199         continue;
1200     }
1201
1202     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203
1204     // Add any operands of the new node which have not yet been combined to the
1205     // worklist as well. Because the worklist uniques things already, this
1206     // won't repeatedly process the same operand.
1207     CombinedNodes.insert(N);
1208     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1209       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1210         AddToWorklist(N->getOperand(i).getNode());
1211
1212     SDValue RV = combine(N);
1213
1214     if (!RV.getNode())
1215       continue;
1216
1217     ++NodesCombined;
1218
1219     // If we get back the same node we passed in, rather than a new node or
1220     // zero, we know that the node must have defined multiple values and
1221     // CombineTo was used.  Since CombineTo takes care of the worklist
1222     // mechanics for us, we have no work to do in this case.
1223     if (RV.getNode() == N)
1224       continue;
1225
1226     assert(N->getOpcode() != ISD::DELETED_NODE &&
1227            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1228            "Node was deleted but visit returned new node!");
1229
1230     DEBUG(dbgs() << " ... into: ";
1231           RV.getNode()->dump(&DAG));
1232
1233     // Transfer debug value.
1234     DAG.TransferDbgValues(SDValue(N, 0), RV);
1235     if (N->getNumValues() == RV.getNode()->getNumValues())
1236       DAG.ReplaceAllUsesWith(N, RV.getNode());
1237     else {
1238       assert(N->getValueType(0) == RV.getValueType() &&
1239              N->getNumValues() == 1 && "Type mismatch");
1240       SDValue OpV = RV;
1241       DAG.ReplaceAllUsesWith(N, &OpV);
1242     }
1243
1244     // Push the new node and any users onto the worklist
1245     AddToWorklist(RV.getNode());
1246     AddUsersToWorklist(RV.getNode());
1247
1248     // Finally, if the node is now dead, remove it from the graph.  The node
1249     // may not be dead if the replacement process recursively simplified to
1250     // something else needing this node. This will also take care of adding any
1251     // operands which have lost a user to the worklist.
1252     recursivelyDeleteUnusedNodes(N);
1253   }
1254
1255   // If the root changed (e.g. it was a dead load, update the root).
1256   DAG.setRoot(Dummy.getValue());
1257   DAG.RemoveDeadNodes();
1258 }
1259
1260 SDValue DAGCombiner::visit(SDNode *N) {
1261   switch (N->getOpcode()) {
1262   default: break;
1263   case ISD::TokenFactor:        return visitTokenFactor(N);
1264   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1265   case ISD::ADD:                return visitADD(N);
1266   case ISD::SUB:                return visitSUB(N);
1267   case ISD::ADDC:               return visitADDC(N);
1268   case ISD::SUBC:               return visitSUBC(N);
1269   case ISD::ADDE:               return visitADDE(N);
1270   case ISD::SUBE:               return visitSUBE(N);
1271   case ISD::MUL:                return visitMUL(N);
1272   case ISD::SDIV:               return visitSDIV(N);
1273   case ISD::UDIV:               return visitUDIV(N);
1274   case ISD::SREM:               return visitSREM(N);
1275   case ISD::UREM:               return visitUREM(N);
1276   case ISD::MULHU:              return visitMULHU(N);
1277   case ISD::MULHS:              return visitMULHS(N);
1278   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1279   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1280   case ISD::SMULO:              return visitSMULO(N);
1281   case ISD::UMULO:              return visitUMULO(N);
1282   case ISD::SDIVREM:            return visitSDIVREM(N);
1283   case ISD::UDIVREM:            return visitUDIVREM(N);
1284   case ISD::AND:                return visitAND(N);
1285   case ISD::OR:                 return visitOR(N);
1286   case ISD::XOR:                return visitXOR(N);
1287   case ISD::SHL:                return visitSHL(N);
1288   case ISD::SRA:                return visitSRA(N);
1289   case ISD::SRL:                return visitSRL(N);
1290   case ISD::ROTR:
1291   case ISD::ROTL:               return visitRotate(N);
1292   case ISD::CTLZ:               return visitCTLZ(N);
1293   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1294   case ISD::CTTZ:               return visitCTTZ(N);
1295   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1296   case ISD::CTPOP:              return visitCTPOP(N);
1297   case ISD::SELECT:             return visitSELECT(N);
1298   case ISD::VSELECT:            return visitVSELECT(N);
1299   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1300   case ISD::SETCC:              return visitSETCC(N);
1301   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1302   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1303   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1304   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1305   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1306   case ISD::BITCAST:            return visitBITCAST(N);
1307   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1308   case ISD::FADD:               return visitFADD(N);
1309   case ISD::FSUB:               return visitFSUB(N);
1310   case ISD::FMUL:               return visitFMUL(N);
1311   case ISD::FMA:                return visitFMA(N);
1312   case ISD::FDIV:               return visitFDIV(N);
1313   case ISD::FREM:               return visitFREM(N);
1314   case ISD::FSQRT:              return visitFSQRT(N);
1315   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1316   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1317   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1318   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1319   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1320   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1321   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1322   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1323   case ISD::FNEG:               return visitFNEG(N);
1324   case ISD::FABS:               return visitFABS(N);
1325   case ISD::FFLOOR:             return visitFFLOOR(N);
1326   case ISD::FMINNUM:            return visitFMINNUM(N);
1327   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1328   case ISD::FCEIL:              return visitFCEIL(N);
1329   case ISD::FTRUNC:             return visitFTRUNC(N);
1330   case ISD::BRCOND:             return visitBRCOND(N);
1331   case ISD::BR_CC:              return visitBR_CC(N);
1332   case ISD::LOAD:               return visitLOAD(N);
1333   case ISD::STORE:              return visitSTORE(N);
1334   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1335   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1336   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1337   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1338   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1339   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1340   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1341   }
1342   return SDValue();
1343 }
1344
1345 SDValue DAGCombiner::combine(SDNode *N) {
1346   SDValue RV = visit(N);
1347
1348   // If nothing happened, try a target-specific DAG combine.
1349   if (!RV.getNode()) {
1350     assert(N->getOpcode() != ISD::DELETED_NODE &&
1351            "Node was deleted but visit returned NULL!");
1352
1353     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1354         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1355
1356       // Expose the DAG combiner to the target combiner impls.
1357       TargetLowering::DAGCombinerInfo
1358         DagCombineInfo(DAG, Level, false, this);
1359
1360       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1361     }
1362   }
1363
1364   // If nothing happened still, try promoting the operation.
1365   if (!RV.getNode()) {
1366     switch (N->getOpcode()) {
1367     default: break;
1368     case ISD::ADD:
1369     case ISD::SUB:
1370     case ISD::MUL:
1371     case ISD::AND:
1372     case ISD::OR:
1373     case ISD::XOR:
1374       RV = PromoteIntBinOp(SDValue(N, 0));
1375       break;
1376     case ISD::SHL:
1377     case ISD::SRA:
1378     case ISD::SRL:
1379       RV = PromoteIntShiftOp(SDValue(N, 0));
1380       break;
1381     case ISD::SIGN_EXTEND:
1382     case ISD::ZERO_EXTEND:
1383     case ISD::ANY_EXTEND:
1384       RV = PromoteExtend(SDValue(N, 0));
1385       break;
1386     case ISD::LOAD:
1387       if (PromoteLoad(SDValue(N, 0)))
1388         RV = SDValue(N, 0);
1389       break;
1390     }
1391   }
1392
1393   // If N is a commutative binary node, try commuting it to enable more
1394   // sdisel CSE.
1395   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1396       N->getNumValues() == 1) {
1397     SDValue N0 = N->getOperand(0);
1398     SDValue N1 = N->getOperand(1);
1399
1400     // Constant operands are canonicalized to RHS.
1401     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1402       SDValue Ops[] = {N1, N0};
1403       SDNode *CSENode;
1404       if (const BinaryWithFlagsSDNode *BinNode =
1405               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1406         CSENode = DAG.getNodeIfExists(
1407             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1408             BinNode->hasNoSignedWrap(), BinNode->isExact());
1409       } else {
1410         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1411       }
1412       if (CSENode)
1413         return SDValue(CSENode, 0);
1414     }
1415   }
1416
1417   return RV;
1418 }
1419
1420 /// Given a node, return its input chain if it has one, otherwise return a null
1421 /// sd operand.
1422 static SDValue getInputChainForNode(SDNode *N) {
1423   if (unsigned NumOps = N->getNumOperands()) {
1424     if (N->getOperand(0).getValueType() == MVT::Other)
1425       return N->getOperand(0);
1426     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1427       return N->getOperand(NumOps-1);
1428     for (unsigned i = 1; i < NumOps-1; ++i)
1429       if (N->getOperand(i).getValueType() == MVT::Other)
1430         return N->getOperand(i);
1431   }
1432   return SDValue();
1433 }
1434
1435 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1436   // If N has two operands, where one has an input chain equal to the other,
1437   // the 'other' chain is redundant.
1438   if (N->getNumOperands() == 2) {
1439     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1440       return N->getOperand(0);
1441     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1442       return N->getOperand(1);
1443   }
1444
1445   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1446   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1447   SmallPtrSet<SDNode*, 16> SeenOps;
1448   bool Changed = false;             // If we should replace this token factor.
1449
1450   // Start out with this token factor.
1451   TFs.push_back(N);
1452
1453   // Iterate through token factors.  The TFs grows when new token factors are
1454   // encountered.
1455   for (unsigned i = 0; i < TFs.size(); ++i) {
1456     SDNode *TF = TFs[i];
1457
1458     // Check each of the operands.
1459     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1460       SDValue Op = TF->getOperand(i);
1461
1462       switch (Op.getOpcode()) {
1463       case ISD::EntryToken:
1464         // Entry tokens don't need to be added to the list. They are
1465         // rededundant.
1466         Changed = true;
1467         break;
1468
1469       case ISD::TokenFactor:
1470         if (Op.hasOneUse() &&
1471             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1472           // Queue up for processing.
1473           TFs.push_back(Op.getNode());
1474           // Clean up in case the token factor is removed.
1475           AddToWorklist(Op.getNode());
1476           Changed = true;
1477           break;
1478         }
1479         // Fall thru
1480
1481       default:
1482         // Only add if it isn't already in the list.
1483         if (SeenOps.insert(Op.getNode()))
1484           Ops.push_back(Op);
1485         else
1486           Changed = true;
1487         break;
1488       }
1489     }
1490   }
1491
1492   SDValue Result;
1493
1494   // If we've change things around then replace token factor.
1495   if (Changed) {
1496     if (Ops.empty()) {
1497       // The entry token is the only possible outcome.
1498       Result = DAG.getEntryNode();
1499     } else {
1500       // New and improved token factor.
1501       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1502     }
1503
1504     // Don't add users to work list.
1505     return CombineTo(N, Result, false);
1506   }
1507
1508   return Result;
1509 }
1510
1511 /// MERGE_VALUES can always be eliminated.
1512 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1513   WorklistRemover DeadNodes(*this);
1514   // Replacing results may cause a different MERGE_VALUES to suddenly
1515   // be CSE'd with N, and carry its uses with it. Iterate until no
1516   // uses remain, to ensure that the node can be safely deleted.
1517   // First add the users of this node to the work list so that they
1518   // can be tried again once they have new operands.
1519   AddUsersToWorklist(N);
1520   do {
1521     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1522       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1523   } while (!N->use_empty());
1524   deleteAndRecombine(N);
1525   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1526 }
1527
1528 SDValue DAGCombiner::visitADD(SDNode *N) {
1529   SDValue N0 = N->getOperand(0);
1530   SDValue N1 = N->getOperand(1);
1531   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1532   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1533   EVT VT = N0.getValueType();
1534
1535   // fold vector ops
1536   if (VT.isVector()) {
1537     SDValue FoldedVOp = SimplifyVBinOp(N);
1538     if (FoldedVOp.getNode()) return FoldedVOp;
1539
1540     // fold (add x, 0) -> x, vector edition
1541     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1542       return N0;
1543     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1544       return N1;
1545   }
1546
1547   // fold (add x, undef) -> undef
1548   if (N0.getOpcode() == ISD::UNDEF)
1549     return N0;
1550   if (N1.getOpcode() == ISD::UNDEF)
1551     return N1;
1552   // fold (add c1, c2) -> c1+c2
1553   if (N0C && N1C)
1554     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1555   // canonicalize constant to RHS
1556   if (N0C && !N1C)
1557     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1558   // fold (add x, 0) -> x
1559   if (N1C && N1C->isNullValue())
1560     return N0;
1561   // fold (add Sym, c) -> Sym+c
1562   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1563     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1564         GA->getOpcode() == ISD::GlobalAddress)
1565       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1566                                   GA->getOffset() +
1567                                     (uint64_t)N1C->getSExtValue());
1568   // fold ((c1-A)+c2) -> (c1+c2)-A
1569   if (N1C && N0.getOpcode() == ISD::SUB)
1570     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1571       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1572                          DAG.getConstant(N1C->getAPIntValue()+
1573                                          N0C->getAPIntValue(), VT),
1574                          N0.getOperand(1));
1575   // reassociate add
1576   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1577   if (RADD.getNode())
1578     return RADD;
1579   // fold ((0-A) + B) -> B-A
1580   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1581       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1582     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1583   // fold (A + (0-B)) -> A-B
1584   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1585       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1586     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1587   // fold (A+(B-A)) -> B
1588   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1589     return N1.getOperand(0);
1590   // fold ((B-A)+A) -> B
1591   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1592     return N0.getOperand(0);
1593   // fold (A+(B-(A+C))) to (B-C)
1594   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1595       N0 == N1.getOperand(1).getOperand(0))
1596     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1597                        N1.getOperand(1).getOperand(1));
1598   // fold (A+(B-(C+A))) to (B-C)
1599   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1600       N0 == N1.getOperand(1).getOperand(1))
1601     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1602                        N1.getOperand(1).getOperand(0));
1603   // fold (A+((B-A)+or-C)) to (B+or-C)
1604   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1605       N1.getOperand(0).getOpcode() == ISD::SUB &&
1606       N0 == N1.getOperand(0).getOperand(1))
1607     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1608                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1609
1610   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1611   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1612     SDValue N00 = N0.getOperand(0);
1613     SDValue N01 = N0.getOperand(1);
1614     SDValue N10 = N1.getOperand(0);
1615     SDValue N11 = N1.getOperand(1);
1616
1617     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1618       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1619                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1620                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1621   }
1622
1623   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1624     return SDValue(N, 0);
1625
1626   // fold (a+b) -> (a|b) iff a and b share no bits.
1627   if (VT.isInteger() && !VT.isVector()) {
1628     APInt LHSZero, LHSOne;
1629     APInt RHSZero, RHSOne;
1630     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1631
1632     if (LHSZero.getBoolValue()) {
1633       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1634
1635       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1636       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1637       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1638         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1639           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1640       }
1641     }
1642   }
1643
1644   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1645   if (N1.getOpcode() == ISD::SHL &&
1646       N1.getOperand(0).getOpcode() == ISD::SUB)
1647     if (ConstantSDNode *C =
1648           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1649       if (C->getAPIntValue() == 0)
1650         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1651                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1652                                        N1.getOperand(0).getOperand(1),
1653                                        N1.getOperand(1)));
1654   if (N0.getOpcode() == ISD::SHL &&
1655       N0.getOperand(0).getOpcode() == ISD::SUB)
1656     if (ConstantSDNode *C =
1657           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1658       if (C->getAPIntValue() == 0)
1659         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1660                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1661                                        N0.getOperand(0).getOperand(1),
1662                                        N0.getOperand(1)));
1663
1664   if (N1.getOpcode() == ISD::AND) {
1665     SDValue AndOp0 = N1.getOperand(0);
1666     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1667     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1668     unsigned DestBits = VT.getScalarType().getSizeInBits();
1669
1670     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1671     // and similar xforms where the inner op is either ~0 or 0.
1672     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1673       SDLoc DL(N);
1674       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1675     }
1676   }
1677
1678   // add (sext i1), X -> sub X, (zext i1)
1679   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1680       N0.getOperand(0).getValueType() == MVT::i1 &&
1681       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1682     SDLoc DL(N);
1683     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1684     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1685   }
1686
1687   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1688   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1689     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1690     if (TN->getVT() == MVT::i1) {
1691       SDLoc DL(N);
1692       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1693                                  DAG.getConstant(1, VT));
1694       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1695     }
1696   }
1697
1698   return SDValue();
1699 }
1700
1701 SDValue DAGCombiner::visitADDC(SDNode *N) {
1702   SDValue N0 = N->getOperand(0);
1703   SDValue N1 = N->getOperand(1);
1704   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1705   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1706   EVT VT = N0.getValueType();
1707
1708   // If the flag result is dead, turn this into an ADD.
1709   if (!N->hasAnyUseOfValue(1))
1710     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1711                      DAG.getNode(ISD::CARRY_FALSE,
1712                                  SDLoc(N), MVT::Glue));
1713
1714   // canonicalize constant to RHS.
1715   if (N0C && !N1C)
1716     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1717
1718   // fold (addc x, 0) -> x + no carry out
1719   if (N1C && N1C->isNullValue())
1720     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1721                                         SDLoc(N), MVT::Glue));
1722
1723   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1724   APInt LHSZero, LHSOne;
1725   APInt RHSZero, RHSOne;
1726   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1727
1728   if (LHSZero.getBoolValue()) {
1729     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1730
1731     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1732     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1733     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1734       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1735                        DAG.getNode(ISD::CARRY_FALSE,
1736                                    SDLoc(N), MVT::Glue));
1737   }
1738
1739   return SDValue();
1740 }
1741
1742 SDValue DAGCombiner::visitADDE(SDNode *N) {
1743   SDValue N0 = N->getOperand(0);
1744   SDValue N1 = N->getOperand(1);
1745   SDValue CarryIn = N->getOperand(2);
1746   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1747   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1748
1749   // canonicalize constant to RHS
1750   if (N0C && !N1C)
1751     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1752                        N1, N0, CarryIn);
1753
1754   // fold (adde x, y, false) -> (addc x, y)
1755   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1756     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1757
1758   return SDValue();
1759 }
1760
1761 // Since it may not be valid to emit a fold to zero for vector initializers
1762 // check if we can before folding.
1763 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1764                              SelectionDAG &DAG,
1765                              bool LegalOperations, bool LegalTypes) {
1766   if (!VT.isVector())
1767     return DAG.getConstant(0, VT);
1768   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1769     return DAG.getConstant(0, VT);
1770   return SDValue();
1771 }
1772
1773 SDValue DAGCombiner::visitSUB(SDNode *N) {
1774   SDValue N0 = N->getOperand(0);
1775   SDValue N1 = N->getOperand(1);
1776   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1777   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1778   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1779     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1780   EVT VT = N0.getValueType();
1781
1782   // fold vector ops
1783   if (VT.isVector()) {
1784     SDValue FoldedVOp = SimplifyVBinOp(N);
1785     if (FoldedVOp.getNode()) return FoldedVOp;
1786
1787     // fold (sub x, 0) -> x, vector edition
1788     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1789       return N0;
1790   }
1791
1792   // fold (sub x, x) -> 0
1793   // FIXME: Refactor this and xor and other similar operations together.
1794   if (N0 == N1)
1795     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1796   // fold (sub c1, c2) -> c1-c2
1797   if (N0C && N1C)
1798     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1799   // fold (sub x, c) -> (add x, -c)
1800   if (N1C)
1801     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1802                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1803   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1804   if (N0C && N0C->isAllOnesValue())
1805     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1806   // fold A-(A-B) -> B
1807   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1808     return N1.getOperand(1);
1809   // fold (A+B)-A -> B
1810   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1811     return N0.getOperand(1);
1812   // fold (A+B)-B -> A
1813   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1814     return N0.getOperand(0);
1815   // fold C2-(A+C1) -> (C2-C1)-A
1816   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1817     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1818                                    VT);
1819     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1820                        N1.getOperand(0));
1821   }
1822   // fold ((A+(B+or-C))-B) -> A+or-C
1823   if (N0.getOpcode() == ISD::ADD &&
1824       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1825        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1826       N0.getOperand(1).getOperand(0) == N1)
1827     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1828                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1829   // fold ((A+(C+B))-B) -> A+C
1830   if (N0.getOpcode() == ISD::ADD &&
1831       N0.getOperand(1).getOpcode() == ISD::ADD &&
1832       N0.getOperand(1).getOperand(1) == N1)
1833     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1834                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1835   // fold ((A-(B-C))-C) -> A-B
1836   if (N0.getOpcode() == ISD::SUB &&
1837       N0.getOperand(1).getOpcode() == ISD::SUB &&
1838       N0.getOperand(1).getOperand(1) == N1)
1839     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1840                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1841
1842   // If either operand of a sub is undef, the result is undef
1843   if (N0.getOpcode() == ISD::UNDEF)
1844     return N0;
1845   if (N1.getOpcode() == ISD::UNDEF)
1846     return N1;
1847
1848   // If the relocation model supports it, consider symbol offsets.
1849   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1850     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1851       // fold (sub Sym, c) -> Sym-c
1852       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1853         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1854                                     GA->getOffset() -
1855                                       (uint64_t)N1C->getSExtValue());
1856       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1857       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1858         if (GA->getGlobal() == GB->getGlobal())
1859           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1860                                  VT);
1861     }
1862
1863   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1864   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1865     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1866     if (TN->getVT() == MVT::i1) {
1867       SDLoc DL(N);
1868       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1869                                  DAG.getConstant(1, VT));
1870       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1871     }
1872   }
1873
1874   return SDValue();
1875 }
1876
1877 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1878   SDValue N0 = N->getOperand(0);
1879   SDValue N1 = N->getOperand(1);
1880   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1881   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1882   EVT VT = N0.getValueType();
1883
1884   // If the flag result is dead, turn this into an SUB.
1885   if (!N->hasAnyUseOfValue(1))
1886     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1887                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1888                                  MVT::Glue));
1889
1890   // fold (subc x, x) -> 0 + no borrow
1891   if (N0 == N1)
1892     return CombineTo(N, DAG.getConstant(0, VT),
1893                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1894                                  MVT::Glue));
1895
1896   // fold (subc x, 0) -> x + no borrow
1897   if (N1C && N1C->isNullValue())
1898     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1899                                         MVT::Glue));
1900
1901   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1902   if (N0C && N0C->isAllOnesValue())
1903     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1904                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905                                  MVT::Glue));
1906
1907   return SDValue();
1908 }
1909
1910 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1911   SDValue N0 = N->getOperand(0);
1912   SDValue N1 = N->getOperand(1);
1913   SDValue CarryIn = N->getOperand(2);
1914
1915   // fold (sube x, y, false) -> (subc x, y)
1916   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1917     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1918
1919   return SDValue();
1920 }
1921
1922 SDValue DAGCombiner::visitMUL(SDNode *N) {
1923   SDValue N0 = N->getOperand(0);
1924   SDValue N1 = N->getOperand(1);
1925   EVT VT = N0.getValueType();
1926
1927   // fold (mul x, undef) -> 0
1928   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1929     return DAG.getConstant(0, VT);
1930
1931   bool N0IsConst = false;
1932   bool N1IsConst = false;
1933   APInt ConstValue0, ConstValue1;
1934   // fold vector ops
1935   if (VT.isVector()) {
1936     SDValue FoldedVOp = SimplifyVBinOp(N);
1937     if (FoldedVOp.getNode()) return FoldedVOp;
1938
1939     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1940     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1941   } else {
1942     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1943     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1944                             : APInt();
1945     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1946     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1947                             : APInt();
1948   }
1949
1950   // fold (mul c1, c2) -> c1*c2
1951   if (N0IsConst && N1IsConst)
1952     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1953
1954   // canonicalize constant to RHS
1955   if (N0IsConst && !N1IsConst)
1956     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1957   // fold (mul x, 0) -> 0
1958   if (N1IsConst && ConstValue1 == 0)
1959     return N1;
1960   // We require a splat of the entire scalar bit width for non-contiguous
1961   // bit patterns.
1962   bool IsFullSplat =
1963     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1964   // fold (mul x, 1) -> x
1965   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1966     return N0;
1967   // fold (mul x, -1) -> 0-x
1968   if (N1IsConst && ConstValue1.isAllOnesValue())
1969     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1970                        DAG.getConstant(0, VT), N0);
1971   // fold (mul x, (1 << c)) -> x << c
1972   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1973     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1974                        DAG.getConstant(ConstValue1.logBase2(),
1975                                        getShiftAmountTy(N0.getValueType())));
1976   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1977   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1978     unsigned Log2Val = (-ConstValue1).logBase2();
1979     // FIXME: If the input is something that is easily negated (e.g. a
1980     // single-use add), we should put the negate there.
1981     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1982                        DAG.getConstant(0, VT),
1983                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1984                             DAG.getConstant(Log2Val,
1985                                       getShiftAmountTy(N0.getValueType()))));
1986   }
1987
1988   APInt Val;
1989   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1990   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1991       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1992                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1993     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1994                              N1, N0.getOperand(1));
1995     AddToWorklist(C3.getNode());
1996     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1997                        N0.getOperand(0), C3);
1998   }
1999
2000   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2001   // use.
2002   {
2003     SDValue Sh(nullptr,0), Y(nullptr,0);
2004     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2005     if (N0.getOpcode() == ISD::SHL &&
2006         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2007                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2008         N0.getNode()->hasOneUse()) {
2009       Sh = N0; Y = N1;
2010     } else if (N1.getOpcode() == ISD::SHL &&
2011                isa<ConstantSDNode>(N1.getOperand(1)) &&
2012                N1.getNode()->hasOneUse()) {
2013       Sh = N1; Y = N0;
2014     }
2015
2016     if (Sh.getNode()) {
2017       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2018                                 Sh.getOperand(0), Y);
2019       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2020                          Mul, Sh.getOperand(1));
2021     }
2022   }
2023
2024   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2025   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2026       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2027                      isa<ConstantSDNode>(N0.getOperand(1))))
2028     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2029                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2030                                    N0.getOperand(0), N1),
2031                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2032                                    N0.getOperand(1), N1));
2033
2034   // reassociate mul
2035   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2036   if (RMUL.getNode())
2037     return RMUL;
2038
2039   return SDValue();
2040 }
2041
2042 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2043   SDValue N0 = N->getOperand(0);
2044   SDValue N1 = N->getOperand(1);
2045   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2046   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2047   EVT VT = N->getValueType(0);
2048
2049   // fold vector ops
2050   if (VT.isVector()) {
2051     SDValue FoldedVOp = SimplifyVBinOp(N);
2052     if (FoldedVOp.getNode()) return FoldedVOp;
2053   }
2054
2055   // fold (sdiv c1, c2) -> c1/c2
2056   if (N0C && N1C && !N1C->isNullValue())
2057     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2058   // fold (sdiv X, 1) -> X
2059   if (N1C && N1C->getAPIntValue() == 1LL)
2060     return N0;
2061   // fold (sdiv X, -1) -> 0-X
2062   if (N1C && N1C->isAllOnesValue())
2063     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2064                        DAG.getConstant(0, VT), N0);
2065   // If we know the sign bits of both operands are zero, strength reduce to a
2066   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2067   if (!VT.isVector()) {
2068     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2069       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2070                          N0, N1);
2071   }
2072
2073   // fold (sdiv X, pow2) -> simple ops after legalize
2074   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2075                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2076     // If dividing by powers of two is cheap, then don't perform the following
2077     // fold.
2078     if (TLI.isPow2SDivCheap())
2079       return SDValue();
2080
2081     // Target-specific implementation of sdiv x, pow2.
2082     SDValue Res = BuildSDIVPow2(N);
2083     if (Res.getNode())
2084       return Res;
2085
2086     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2087
2088     // Splat the sign bit into the register
2089     SDValue SGN =
2090         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2091                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2092                                     getShiftAmountTy(N0.getValueType())));
2093     AddToWorklist(SGN.getNode());
2094
2095     // Add (N0 < 0) ? abs2 - 1 : 0;
2096     SDValue SRL =
2097         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2098                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2099                                     getShiftAmountTy(SGN.getValueType())));
2100     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2101     AddToWorklist(SRL.getNode());
2102     AddToWorklist(ADD.getNode());    // Divide by pow2
2103     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2104                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2105
2106     // If we're dividing by a positive value, we're done.  Otherwise, we must
2107     // negate the result.
2108     if (N1C->getAPIntValue().isNonNegative())
2109       return SRA;
2110
2111     AddToWorklist(SRA.getNode());
2112     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2113   }
2114
2115   // if integer divide is expensive and we satisfy the requirements, emit an
2116   // alternate sequence.
2117   if (N1C && !TLI.isIntDivCheap()) {
2118     SDValue Op = BuildSDIV(N);
2119     if (Op.getNode()) return Op;
2120   }
2121
2122   // undef / X -> 0
2123   if (N0.getOpcode() == ISD::UNDEF)
2124     return DAG.getConstant(0, VT);
2125   // X / undef -> undef
2126   if (N1.getOpcode() == ISD::UNDEF)
2127     return N1;
2128
2129   return SDValue();
2130 }
2131
2132 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2133   SDValue N0 = N->getOperand(0);
2134   SDValue N1 = N->getOperand(1);
2135   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2136   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2137   EVT VT = N->getValueType(0);
2138
2139   // fold vector ops
2140   if (VT.isVector()) {
2141     SDValue FoldedVOp = SimplifyVBinOp(N);
2142     if (FoldedVOp.getNode()) return FoldedVOp;
2143   }
2144
2145   // fold (udiv c1, c2) -> c1/c2
2146   if (N0C && N1C && !N1C->isNullValue())
2147     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2148   // fold (udiv x, (1 << c)) -> x >>u c
2149   if (N1C && N1C->getAPIntValue().isPowerOf2())
2150     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2151                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2152                                        getShiftAmountTy(N0.getValueType())));
2153   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2154   if (N1.getOpcode() == ISD::SHL) {
2155     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2156       if (SHC->getAPIntValue().isPowerOf2()) {
2157         EVT ADDVT = N1.getOperand(1).getValueType();
2158         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2159                                   N1.getOperand(1),
2160                                   DAG.getConstant(SHC->getAPIntValue()
2161                                                                   .logBase2(),
2162                                                   ADDVT));
2163         AddToWorklist(Add.getNode());
2164         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2165       }
2166     }
2167   }
2168   // fold (udiv x, c) -> alternate
2169   if (N1C && !TLI.isIntDivCheap()) {
2170     SDValue Op = BuildUDIV(N);
2171     if (Op.getNode()) return Op;
2172   }
2173
2174   // undef / X -> 0
2175   if (N0.getOpcode() == ISD::UNDEF)
2176     return DAG.getConstant(0, VT);
2177   // X / undef -> undef
2178   if (N1.getOpcode() == ISD::UNDEF)
2179     return N1;
2180
2181   return SDValue();
2182 }
2183
2184 SDValue DAGCombiner::visitSREM(SDNode *N) {
2185   SDValue N0 = N->getOperand(0);
2186   SDValue N1 = N->getOperand(1);
2187   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2188   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2189   EVT VT = N->getValueType(0);
2190
2191   // fold (srem c1, c2) -> c1%c2
2192   if (N0C && N1C && !N1C->isNullValue())
2193     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2194   // If we know the sign bits of both operands are zero, strength reduce to a
2195   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2196   if (!VT.isVector()) {
2197     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2198       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2199   }
2200
2201   // If X/C can be simplified by the division-by-constant logic, lower
2202   // X%C to the equivalent of X-X/C*C.
2203   if (N1C && !N1C->isNullValue()) {
2204     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2205     AddToWorklist(Div.getNode());
2206     SDValue OptimizedDiv = combine(Div.getNode());
2207     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2208       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2209                                 OptimizedDiv, N1);
2210       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2211       AddToWorklist(Mul.getNode());
2212       return Sub;
2213     }
2214   }
2215
2216   // undef % X -> 0
2217   if (N0.getOpcode() == ISD::UNDEF)
2218     return DAG.getConstant(0, VT);
2219   // X % undef -> undef
2220   if (N1.getOpcode() == ISD::UNDEF)
2221     return N1;
2222
2223   return SDValue();
2224 }
2225
2226 SDValue DAGCombiner::visitUREM(SDNode *N) {
2227   SDValue N0 = N->getOperand(0);
2228   SDValue N1 = N->getOperand(1);
2229   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2230   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2231   EVT VT = N->getValueType(0);
2232
2233   // fold (urem c1, c2) -> c1%c2
2234   if (N0C && N1C && !N1C->isNullValue())
2235     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2236   // fold (urem x, pow2) -> (and x, pow2-1)
2237   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2238     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2239                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2240   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2241   if (N1.getOpcode() == ISD::SHL) {
2242     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2243       if (SHC->getAPIntValue().isPowerOf2()) {
2244         SDValue Add =
2245           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2246                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2247                                  VT));
2248         AddToWorklist(Add.getNode());
2249         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2250       }
2251     }
2252   }
2253
2254   // If X/C can be simplified by the division-by-constant logic, lower
2255   // X%C to the equivalent of X-X/C*C.
2256   if (N1C && !N1C->isNullValue()) {
2257     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2258     AddToWorklist(Div.getNode());
2259     SDValue OptimizedDiv = combine(Div.getNode());
2260     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2261       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2262                                 OptimizedDiv, N1);
2263       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2264       AddToWorklist(Mul.getNode());
2265       return Sub;
2266     }
2267   }
2268
2269   // undef % X -> 0
2270   if (N0.getOpcode() == ISD::UNDEF)
2271     return DAG.getConstant(0, VT);
2272   // X % undef -> undef
2273   if (N1.getOpcode() == ISD::UNDEF)
2274     return N1;
2275
2276   return SDValue();
2277 }
2278
2279 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2280   SDValue N0 = N->getOperand(0);
2281   SDValue N1 = N->getOperand(1);
2282   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2283   EVT VT = N->getValueType(0);
2284   SDLoc DL(N);
2285
2286   // fold (mulhs x, 0) -> 0
2287   if (N1C && N1C->isNullValue())
2288     return N1;
2289   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2290   if (N1C && N1C->getAPIntValue() == 1)
2291     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2292                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2293                                        getShiftAmountTy(N0.getValueType())));
2294   // fold (mulhs x, undef) -> 0
2295   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2296     return DAG.getConstant(0, VT);
2297
2298   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2299   // plus a shift.
2300   if (VT.isSimple() && !VT.isVector()) {
2301     MVT Simple = VT.getSimpleVT();
2302     unsigned SimpleSize = Simple.getSizeInBits();
2303     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2304     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2305       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2306       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2307       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2308       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2309             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2310       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2311     }
2312   }
2313
2314   return SDValue();
2315 }
2316
2317 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2318   SDValue N0 = N->getOperand(0);
2319   SDValue N1 = N->getOperand(1);
2320   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2321   EVT VT = N->getValueType(0);
2322   SDLoc DL(N);
2323
2324   // fold (mulhu x, 0) -> 0
2325   if (N1C && N1C->isNullValue())
2326     return N1;
2327   // fold (mulhu x, 1) -> 0
2328   if (N1C && N1C->getAPIntValue() == 1)
2329     return DAG.getConstant(0, N0.getValueType());
2330   // fold (mulhu x, undef) -> 0
2331   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2332     return DAG.getConstant(0, VT);
2333
2334   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2335   // plus a shift.
2336   if (VT.isSimple() && !VT.isVector()) {
2337     MVT Simple = VT.getSimpleVT();
2338     unsigned SimpleSize = Simple.getSizeInBits();
2339     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2340     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2341       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2342       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2343       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2344       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2345             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2346       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2347     }
2348   }
2349
2350   return SDValue();
2351 }
2352
2353 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2354 /// give the opcodes for the two computations that are being performed. Return
2355 /// true if a simplification was made.
2356 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2357                                                 unsigned HiOp) {
2358   // If the high half is not needed, just compute the low half.
2359   bool HiExists = N->hasAnyUseOfValue(1);
2360   if (!HiExists &&
2361       (!LegalOperations ||
2362        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2363     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2364     return CombineTo(N, Res, Res);
2365   }
2366
2367   // If the low half is not needed, just compute the high half.
2368   bool LoExists = N->hasAnyUseOfValue(0);
2369   if (!LoExists &&
2370       (!LegalOperations ||
2371        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2372     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2373     return CombineTo(N, Res, Res);
2374   }
2375
2376   // If both halves are used, return as it is.
2377   if (LoExists && HiExists)
2378     return SDValue();
2379
2380   // If the two computed results can be simplified separately, separate them.
2381   if (LoExists) {
2382     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2383     AddToWorklist(Lo.getNode());
2384     SDValue LoOpt = combine(Lo.getNode());
2385     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2386         (!LegalOperations ||
2387          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2388       return CombineTo(N, LoOpt, LoOpt);
2389   }
2390
2391   if (HiExists) {
2392     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2393     AddToWorklist(Hi.getNode());
2394     SDValue HiOpt = combine(Hi.getNode());
2395     if (HiOpt.getNode() && HiOpt != Hi &&
2396         (!LegalOperations ||
2397          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2398       return CombineTo(N, HiOpt, HiOpt);
2399   }
2400
2401   return SDValue();
2402 }
2403
2404 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2405   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2406   if (Res.getNode()) return Res;
2407
2408   EVT VT = N->getValueType(0);
2409   SDLoc DL(N);
2410
2411   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2412   // plus a shift.
2413   if (VT.isSimple() && !VT.isVector()) {
2414     MVT Simple = VT.getSimpleVT();
2415     unsigned SimpleSize = Simple.getSizeInBits();
2416     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2417     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2418       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2419       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2420       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2421       // Compute the high part as N1.
2422       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2423             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2424       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2425       // Compute the low part as N0.
2426       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2427       return CombineTo(N, Lo, Hi);
2428     }
2429   }
2430
2431   return SDValue();
2432 }
2433
2434 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2435   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2436   if (Res.getNode()) return Res;
2437
2438   EVT VT = N->getValueType(0);
2439   SDLoc DL(N);
2440
2441   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2442   // plus a shift.
2443   if (VT.isSimple() && !VT.isVector()) {
2444     MVT Simple = VT.getSimpleVT();
2445     unsigned SimpleSize = Simple.getSizeInBits();
2446     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2447     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2448       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2449       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2450       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2451       // Compute the high part as N1.
2452       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2453             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2454       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2455       // Compute the low part as N0.
2456       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2457       return CombineTo(N, Lo, Hi);
2458     }
2459   }
2460
2461   return SDValue();
2462 }
2463
2464 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2465   // (smulo x, 2) -> (saddo x, x)
2466   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2467     if (C2->getAPIntValue() == 2)
2468       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2469                          N->getOperand(0), N->getOperand(0));
2470
2471   return SDValue();
2472 }
2473
2474 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2475   // (umulo x, 2) -> (uaddo x, x)
2476   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2477     if (C2->getAPIntValue() == 2)
2478       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2479                          N->getOperand(0), N->getOperand(0));
2480
2481   return SDValue();
2482 }
2483
2484 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2485   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2486   if (Res.getNode()) return Res;
2487
2488   return SDValue();
2489 }
2490
2491 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2492   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2493   if (Res.getNode()) return Res;
2494
2495   return SDValue();
2496 }
2497
2498 /// If this is a binary operator with two operands of the same opcode, try to
2499 /// simplify it.
2500 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2501   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2502   EVT VT = N0.getValueType();
2503   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2504
2505   // Bail early if none of these transforms apply.
2506   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2507
2508   // For each of OP in AND/OR/XOR:
2509   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2510   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2511   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2512   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2513   //
2514   // do not sink logical op inside of a vector extend, since it may combine
2515   // into a vsetcc.
2516   EVT Op0VT = N0.getOperand(0).getValueType();
2517   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2518        N0.getOpcode() == ISD::SIGN_EXTEND ||
2519        // Avoid infinite looping with PromoteIntBinOp.
2520        (N0.getOpcode() == ISD::ANY_EXTEND &&
2521         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2522        (N0.getOpcode() == ISD::TRUNCATE &&
2523         (!TLI.isZExtFree(VT, Op0VT) ||
2524          !TLI.isTruncateFree(Op0VT, VT)) &&
2525         TLI.isTypeLegal(Op0VT))) &&
2526       !VT.isVector() &&
2527       Op0VT == N1.getOperand(0).getValueType() &&
2528       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2529     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2530                                  N0.getOperand(0).getValueType(),
2531                                  N0.getOperand(0), N1.getOperand(0));
2532     AddToWorklist(ORNode.getNode());
2533     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2534   }
2535
2536   // For each of OP in SHL/SRL/SRA/AND...
2537   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2538   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2539   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2540   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2541        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2542       N0.getOperand(1) == N1.getOperand(1)) {
2543     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2544                                  N0.getOperand(0).getValueType(),
2545                                  N0.getOperand(0), N1.getOperand(0));
2546     AddToWorklist(ORNode.getNode());
2547     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2548                        ORNode, N0.getOperand(1));
2549   }
2550
2551   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2552   // Only perform this optimization after type legalization and before
2553   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2554   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2555   // we don't want to undo this promotion.
2556   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2557   // on scalars.
2558   if ((N0.getOpcode() == ISD::BITCAST ||
2559        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2560       Level == AfterLegalizeTypes) {
2561     SDValue In0 = N0.getOperand(0);
2562     SDValue In1 = N1.getOperand(0);
2563     EVT In0Ty = In0.getValueType();
2564     EVT In1Ty = In1.getValueType();
2565     SDLoc DL(N);
2566     // If both incoming values are integers, and the original types are the
2567     // same.
2568     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2569       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2570       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2571       AddToWorklist(Op.getNode());
2572       return BC;
2573     }
2574   }
2575
2576   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2577   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2578   // If both shuffles use the same mask, and both shuffle within a single
2579   // vector, then it is worthwhile to move the swizzle after the operation.
2580   // The type-legalizer generates this pattern when loading illegal
2581   // vector types from memory. In many cases this allows additional shuffle
2582   // optimizations.
2583   // There are other cases where moving the shuffle after the xor/and/or
2584   // is profitable even if shuffles don't perform a swizzle.
2585   // If both shuffles use the same mask, and both shuffles have the same first
2586   // or second operand, then it might still be profitable to move the shuffle
2587   // after the xor/and/or operation.
2588   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2589     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2590     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2591
2592     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2593            "Inputs to shuffles are not the same type");
2594
2595     // Check that both shuffles use the same mask. The masks are known to be of
2596     // the same length because the result vector type is the same.
2597     // Check also that shuffles have only one use to avoid introducing extra
2598     // instructions.
2599     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2600         SVN0->getMask().equals(SVN1->getMask())) {
2601       SDValue ShOp = N0->getOperand(1);
2602
2603       // Don't try to fold this node if it requires introducing a
2604       // build vector of all zeros that might be illegal at this stage.
2605       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2606         if (!LegalTypes)
2607           ShOp = DAG.getConstant(0, VT);
2608         else
2609           ShOp = SDValue();
2610       }
2611
2612       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2613       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2614       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2615       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2616         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2617                                       N0->getOperand(0), N1->getOperand(0));
2618         AddToWorklist(NewNode.getNode());
2619         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2620                                     &SVN0->getMask()[0]);
2621       }
2622
2623       // Don't try to fold this node if it requires introducing a
2624       // build vector of all zeros that might be illegal at this stage.
2625       ShOp = N0->getOperand(0);
2626       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2627         if (!LegalTypes)
2628           ShOp = DAG.getConstant(0, VT);
2629         else
2630           ShOp = SDValue();
2631       }
2632
2633       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2634       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2635       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2636       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2637         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2638                                       N0->getOperand(1), N1->getOperand(1));
2639         AddToWorklist(NewNode.getNode());
2640         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2641                                     &SVN0->getMask()[0]);
2642       }
2643     }
2644   }
2645
2646   return SDValue();
2647 }
2648
2649 SDValue DAGCombiner::visitAND(SDNode *N) {
2650   SDValue N0 = N->getOperand(0);
2651   SDValue N1 = N->getOperand(1);
2652   SDValue LL, LR, RL, RR, CC0, CC1;
2653   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2654   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2655   EVT VT = N1.getValueType();
2656   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2657
2658   // fold vector ops
2659   if (VT.isVector()) {
2660     SDValue FoldedVOp = SimplifyVBinOp(N);
2661     if (FoldedVOp.getNode()) return FoldedVOp;
2662
2663     // fold (and x, 0) -> 0, vector edition
2664     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2665       // do not return N0, because undef node may exist in N0
2666       return DAG.getConstant(
2667           APInt::getNullValue(
2668               N0.getValueType().getScalarType().getSizeInBits()),
2669           N0.getValueType());
2670     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2671       // do not return N1, because undef node may exist in N1
2672       return DAG.getConstant(
2673           APInt::getNullValue(
2674               N1.getValueType().getScalarType().getSizeInBits()),
2675           N1.getValueType());
2676
2677     // fold (and x, -1) -> x, vector edition
2678     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2679       return N1;
2680     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2681       return N0;
2682   }
2683
2684   // fold (and x, undef) -> 0
2685   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2686     return DAG.getConstant(0, VT);
2687   // fold (and c1, c2) -> c1&c2
2688   if (N0C && N1C)
2689     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2690   // canonicalize constant to RHS
2691   if (N0C && !N1C)
2692     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2693   // fold (and x, -1) -> x
2694   if (N1C && N1C->isAllOnesValue())
2695     return N0;
2696   // if (and x, c) is known to be zero, return 0
2697   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2698                                    APInt::getAllOnesValue(BitWidth)))
2699     return DAG.getConstant(0, VT);
2700   // reassociate and
2701   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2702   if (RAND.getNode())
2703     return RAND;
2704   // fold (and (or x, C), D) -> D if (C & D) == D
2705   if (N1C && N0.getOpcode() == ISD::OR)
2706     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2707       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2708         return N1;
2709   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2710   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2711     SDValue N0Op0 = N0.getOperand(0);
2712     APInt Mask = ~N1C->getAPIntValue();
2713     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2714     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2715       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2716                                  N0.getValueType(), N0Op0);
2717
2718       // Replace uses of the AND with uses of the Zero extend node.
2719       CombineTo(N, Zext);
2720
2721       // We actually want to replace all uses of the any_extend with the
2722       // zero_extend, to avoid duplicating things.  This will later cause this
2723       // AND to be folded.
2724       CombineTo(N0.getNode(), Zext);
2725       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2726     }
2727   }
2728   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2729   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2730   // already be zero by virtue of the width of the base type of the load.
2731   //
2732   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2733   // more cases.
2734   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2735        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2736       N0.getOpcode() == ISD::LOAD) {
2737     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2738                                          N0 : N0.getOperand(0) );
2739
2740     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2741     // This can be a pure constant or a vector splat, in which case we treat the
2742     // vector as a scalar and use the splat value.
2743     APInt Constant = APInt::getNullValue(1);
2744     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2745       Constant = C->getAPIntValue();
2746     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2747       APInt SplatValue, SplatUndef;
2748       unsigned SplatBitSize;
2749       bool HasAnyUndefs;
2750       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2751                                              SplatBitSize, HasAnyUndefs);
2752       if (IsSplat) {
2753         // Undef bits can contribute to a possible optimisation if set, so
2754         // set them.
2755         SplatValue |= SplatUndef;
2756
2757         // The splat value may be something like "0x00FFFFFF", which means 0 for
2758         // the first vector value and FF for the rest, repeating. We need a mask
2759         // that will apply equally to all members of the vector, so AND all the
2760         // lanes of the constant together.
2761         EVT VT = Vector->getValueType(0);
2762         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2763
2764         // If the splat value has been compressed to a bitlength lower
2765         // than the size of the vector lane, we need to re-expand it to
2766         // the lane size.
2767         if (BitWidth > SplatBitSize)
2768           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2769                SplatBitSize < BitWidth;
2770                SplatBitSize = SplatBitSize * 2)
2771             SplatValue |= SplatValue.shl(SplatBitSize);
2772
2773         Constant = APInt::getAllOnesValue(BitWidth);
2774         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2775           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2776       }
2777     }
2778
2779     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2780     // actually legal and isn't going to get expanded, else this is a false
2781     // optimisation.
2782     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2783                                                     Load->getMemoryVT());
2784
2785     // Resize the constant to the same size as the original memory access before
2786     // extension. If it is still the AllOnesValue then this AND is completely
2787     // unneeded.
2788     Constant =
2789       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2790
2791     bool B;
2792     switch (Load->getExtensionType()) {
2793     default: B = false; break;
2794     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2795     case ISD::ZEXTLOAD:
2796     case ISD::NON_EXTLOAD: B = true; break;
2797     }
2798
2799     if (B && Constant.isAllOnesValue()) {
2800       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2801       // preserve semantics once we get rid of the AND.
2802       SDValue NewLoad(Load, 0);
2803       if (Load->getExtensionType() == ISD::EXTLOAD) {
2804         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2805                               Load->getValueType(0), SDLoc(Load),
2806                               Load->getChain(), Load->getBasePtr(),
2807                               Load->getOffset(), Load->getMemoryVT(),
2808                               Load->getMemOperand());
2809         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2810         if (Load->getNumValues() == 3) {
2811           // PRE/POST_INC loads have 3 values.
2812           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2813                            NewLoad.getValue(2) };
2814           CombineTo(Load, To, 3, true);
2815         } else {
2816           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2817         }
2818       }
2819
2820       // Fold the AND away, taking care not to fold to the old load node if we
2821       // replaced it.
2822       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2823
2824       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2825     }
2826   }
2827   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2828   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2829     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2830     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2831
2832     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2833         LL.getValueType().isInteger()) {
2834       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2835       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2836         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2837                                      LR.getValueType(), LL, RL);
2838         AddToWorklist(ORNode.getNode());
2839         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2840       }
2841       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2842       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2843         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2844                                       LR.getValueType(), LL, RL);
2845         AddToWorklist(ANDNode.getNode());
2846         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2847       }
2848       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2849       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2850         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2851                                      LR.getValueType(), LL, RL);
2852         AddToWorklist(ORNode.getNode());
2853         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2854       }
2855     }
2856     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2857     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2858         Op0 == Op1 && LL.getValueType().isInteger() &&
2859       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2860                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2861                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2862                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2863       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2864                                     LL, DAG.getConstant(1, LL.getValueType()));
2865       AddToWorklist(ADDNode.getNode());
2866       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2867                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2868     }
2869     // canonicalize equivalent to ll == rl
2870     if (LL == RR && LR == RL) {
2871       Op1 = ISD::getSetCCSwappedOperands(Op1);
2872       std::swap(RL, RR);
2873     }
2874     if (LL == RL && LR == RR) {
2875       bool isInteger = LL.getValueType().isInteger();
2876       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2877       if (Result != ISD::SETCC_INVALID &&
2878           (!LegalOperations ||
2879            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2880             TLI.isOperationLegal(ISD::SETCC,
2881                             getSetCCResultType(N0.getSimpleValueType())))))
2882         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2883                             LL, LR, Result);
2884     }
2885   }
2886
2887   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2888   if (N0.getOpcode() == N1.getOpcode()) {
2889     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2890     if (Tmp.getNode()) return Tmp;
2891   }
2892
2893   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2894   // fold (and (sra)) -> (and (srl)) when possible.
2895   if (!VT.isVector() &&
2896       SimplifyDemandedBits(SDValue(N, 0)))
2897     return SDValue(N, 0);
2898
2899   // fold (zext_inreg (extload x)) -> (zextload x)
2900   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2901     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2902     EVT MemVT = LN0->getMemoryVT();
2903     // If we zero all the possible extended bits, then we can turn this into
2904     // a zextload if we are running before legalize or the operation is legal.
2905     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2906     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2907                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2908         ((!LegalOperations && !LN0->isVolatile()) ||
2909          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2910       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2911                                        LN0->getChain(), LN0->getBasePtr(),
2912                                        MemVT, LN0->getMemOperand());
2913       AddToWorklist(N);
2914       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2915       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2916     }
2917   }
2918   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2919   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2920       N0.hasOneUse()) {
2921     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2922     EVT MemVT = LN0->getMemoryVT();
2923     // If we zero all the possible extended bits, then we can turn this into
2924     // a zextload if we are running before legalize or the operation is legal.
2925     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2926     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2927                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2928         ((!LegalOperations && !LN0->isVolatile()) ||
2929          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2930       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2931                                        LN0->getChain(), LN0->getBasePtr(),
2932                                        MemVT, LN0->getMemOperand());
2933       AddToWorklist(N);
2934       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2935       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2936     }
2937   }
2938
2939   // fold (and (load x), 255) -> (zextload x, i8)
2940   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2941   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2942   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2943               (N0.getOpcode() == ISD::ANY_EXTEND &&
2944                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2945     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2946     LoadSDNode *LN0 = HasAnyExt
2947       ? cast<LoadSDNode>(N0.getOperand(0))
2948       : cast<LoadSDNode>(N0);
2949     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2950         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2951       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2952       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2953         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2954         EVT LoadedVT = LN0->getMemoryVT();
2955
2956         if (ExtVT == LoadedVT &&
2957             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2958           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2959
2960           SDValue NewLoad =
2961             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2962                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2963                            LN0->getMemOperand());
2964           AddToWorklist(N);
2965           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2966           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2967         }
2968
2969         // Do not change the width of a volatile load.
2970         // Do not generate loads of non-round integer types since these can
2971         // be expensive (and would be wrong if the type is not byte sized).
2972         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2973             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2974           EVT PtrType = LN0->getOperand(1).getValueType();
2975
2976           unsigned Alignment = LN0->getAlignment();
2977           SDValue NewPtr = LN0->getBasePtr();
2978
2979           // For big endian targets, we need to add an offset to the pointer
2980           // to load the correct bytes.  For little endian systems, we merely
2981           // need to read fewer bytes from the same pointer.
2982           if (TLI.isBigEndian()) {
2983             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2984             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2985             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2986             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2987                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2988             Alignment = MinAlign(Alignment, PtrOff);
2989           }
2990
2991           AddToWorklist(NewPtr.getNode());
2992
2993           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2994           SDValue Load =
2995             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2996                            LN0->getChain(), NewPtr,
2997                            LN0->getPointerInfo(),
2998                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2999                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3000           AddToWorklist(N);
3001           CombineTo(LN0, Load, Load.getValue(1));
3002           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3003         }
3004       }
3005     }
3006   }
3007
3008   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3009       VT.getSizeInBits() <= 64) {
3010     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3011       APInt ADDC = ADDI->getAPIntValue();
3012       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3013         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3014         // immediate for an add, but it is legal if its top c2 bits are set,
3015         // transform the ADD so the immediate doesn't need to be materialized
3016         // in a register.
3017         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3018           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3019                                              SRLI->getZExtValue());
3020           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3021             ADDC |= Mask;
3022             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3023               SDValue NewAdd =
3024                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3025                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3026               CombineTo(N0.getNode(), NewAdd);
3027               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3028             }
3029           }
3030         }
3031       }
3032     }
3033   }
3034
3035   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3036   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3037     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3038                                        N0.getOperand(1), false);
3039     if (BSwap.getNode())
3040       return BSwap;
3041   }
3042
3043   return SDValue();
3044 }
3045
3046 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3047 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3048                                         bool DemandHighBits) {
3049   if (!LegalOperations)
3050     return SDValue();
3051
3052   EVT VT = N->getValueType(0);
3053   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3054     return SDValue();
3055   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3056     return SDValue();
3057
3058   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3059   bool LookPassAnd0 = false;
3060   bool LookPassAnd1 = false;
3061   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3062       std::swap(N0, N1);
3063   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3064       std::swap(N0, N1);
3065   if (N0.getOpcode() == ISD::AND) {
3066     if (!N0.getNode()->hasOneUse())
3067       return SDValue();
3068     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3069     if (!N01C || N01C->getZExtValue() != 0xFF00)
3070       return SDValue();
3071     N0 = N0.getOperand(0);
3072     LookPassAnd0 = true;
3073   }
3074
3075   if (N1.getOpcode() == ISD::AND) {
3076     if (!N1.getNode()->hasOneUse())
3077       return SDValue();
3078     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3079     if (!N11C || N11C->getZExtValue() != 0xFF)
3080       return SDValue();
3081     N1 = N1.getOperand(0);
3082     LookPassAnd1 = true;
3083   }
3084
3085   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3086     std::swap(N0, N1);
3087   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3088     return SDValue();
3089   if (!N0.getNode()->hasOneUse() ||
3090       !N1.getNode()->hasOneUse())
3091     return SDValue();
3092
3093   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3094   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3095   if (!N01C || !N11C)
3096     return SDValue();
3097   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3098     return SDValue();
3099
3100   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3101   SDValue N00 = N0->getOperand(0);
3102   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3103     if (!N00.getNode()->hasOneUse())
3104       return SDValue();
3105     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3106     if (!N001C || N001C->getZExtValue() != 0xFF)
3107       return SDValue();
3108     N00 = N00.getOperand(0);
3109     LookPassAnd0 = true;
3110   }
3111
3112   SDValue N10 = N1->getOperand(0);
3113   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3114     if (!N10.getNode()->hasOneUse())
3115       return SDValue();
3116     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3117     if (!N101C || N101C->getZExtValue() != 0xFF00)
3118       return SDValue();
3119     N10 = N10.getOperand(0);
3120     LookPassAnd1 = true;
3121   }
3122
3123   if (N00 != N10)
3124     return SDValue();
3125
3126   // Make sure everything beyond the low halfword gets set to zero since the SRL
3127   // 16 will clear the top bits.
3128   unsigned OpSizeInBits = VT.getSizeInBits();
3129   if (DemandHighBits && OpSizeInBits > 16) {
3130     // If the left-shift isn't masked out then the only way this is a bswap is
3131     // if all bits beyond the low 8 are 0. In that case the entire pattern
3132     // reduces to a left shift anyway: leave it for other parts of the combiner.
3133     if (!LookPassAnd0)
3134       return SDValue();
3135
3136     // However, if the right shift isn't masked out then it might be because
3137     // it's not needed. See if we can spot that too.
3138     if (!LookPassAnd1 &&
3139         !DAG.MaskedValueIsZero(
3140             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3141       return SDValue();
3142   }
3143
3144   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3145   if (OpSizeInBits > 16)
3146     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3147                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3148   return Res;
3149 }
3150
3151 /// Return true if the specified node is an element that makes up a 32-bit
3152 /// packed halfword byteswap.
3153 /// ((x & 0x000000ff) << 8) |
3154 /// ((x & 0x0000ff00) >> 8) |
3155 /// ((x & 0x00ff0000) << 8) |
3156 /// ((x & 0xff000000) >> 8)
3157 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3158   if (!N.getNode()->hasOneUse())
3159     return false;
3160
3161   unsigned Opc = N.getOpcode();
3162   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3163     return false;
3164
3165   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3166   if (!N1C)
3167     return false;
3168
3169   unsigned Num;
3170   switch (N1C->getZExtValue()) {
3171   default:
3172     return false;
3173   case 0xFF:       Num = 0; break;
3174   case 0xFF00:     Num = 1; break;
3175   case 0xFF0000:   Num = 2; break;
3176   case 0xFF000000: Num = 3; break;
3177   }
3178
3179   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3180   SDValue N0 = N.getOperand(0);
3181   if (Opc == ISD::AND) {
3182     if (Num == 0 || Num == 2) {
3183       // (x >> 8) & 0xff
3184       // (x >> 8) & 0xff0000
3185       if (N0.getOpcode() != ISD::SRL)
3186         return false;
3187       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3188       if (!C || C->getZExtValue() != 8)
3189         return false;
3190     } else {
3191       // (x << 8) & 0xff00
3192       // (x << 8) & 0xff000000
3193       if (N0.getOpcode() != ISD::SHL)
3194         return false;
3195       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3196       if (!C || C->getZExtValue() != 8)
3197         return false;
3198     }
3199   } else if (Opc == ISD::SHL) {
3200     // (x & 0xff) << 8
3201     // (x & 0xff0000) << 8
3202     if (Num != 0 && Num != 2)
3203       return false;
3204     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3205     if (!C || C->getZExtValue() != 8)
3206       return false;
3207   } else { // Opc == ISD::SRL
3208     // (x & 0xff00) >> 8
3209     // (x & 0xff000000) >> 8
3210     if (Num != 1 && Num != 3)
3211       return false;
3212     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3213     if (!C || C->getZExtValue() != 8)
3214       return false;
3215   }
3216
3217   if (Parts[Num])
3218     return false;
3219
3220   Parts[Num] = N0.getOperand(0).getNode();
3221   return true;
3222 }
3223
3224 /// Match a 32-bit packed halfword bswap. That is
3225 /// ((x & 0x000000ff) << 8) |
3226 /// ((x & 0x0000ff00) >> 8) |
3227 /// ((x & 0x00ff0000) << 8) |
3228 /// ((x & 0xff000000) >> 8)
3229 /// => (rotl (bswap x), 16)
3230 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3231   if (!LegalOperations)
3232     return SDValue();
3233
3234   EVT VT = N->getValueType(0);
3235   if (VT != MVT::i32)
3236     return SDValue();
3237   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3238     return SDValue();
3239
3240   // Look for either
3241   // (or (or (and), (and)), (or (and), (and)))
3242   // (or (or (or (and), (and)), (and)), (and))
3243   if (N0.getOpcode() != ISD::OR)
3244     return SDValue();
3245   SDValue N00 = N0.getOperand(0);
3246   SDValue N01 = N0.getOperand(1);
3247   SDNode *Parts[4] = {};
3248
3249   if (N1.getOpcode() == ISD::OR &&
3250       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3251     // (or (or (and), (and)), (or (and), (and)))
3252     SDValue N000 = N00.getOperand(0);
3253     if (!isBSwapHWordElement(N000, Parts))
3254       return SDValue();
3255
3256     SDValue N001 = N00.getOperand(1);
3257     if (!isBSwapHWordElement(N001, Parts))
3258       return SDValue();
3259     SDValue N010 = N01.getOperand(0);
3260     if (!isBSwapHWordElement(N010, Parts))
3261       return SDValue();
3262     SDValue N011 = N01.getOperand(1);
3263     if (!isBSwapHWordElement(N011, Parts))
3264       return SDValue();
3265   } else {
3266     // (or (or (or (and), (and)), (and)), (and))
3267     if (!isBSwapHWordElement(N1, Parts))
3268       return SDValue();
3269     if (!isBSwapHWordElement(N01, Parts))
3270       return SDValue();
3271     if (N00.getOpcode() != ISD::OR)
3272       return SDValue();
3273     SDValue N000 = N00.getOperand(0);
3274     if (!isBSwapHWordElement(N000, Parts))
3275       return SDValue();
3276     SDValue N001 = N00.getOperand(1);
3277     if (!isBSwapHWordElement(N001, Parts))
3278       return SDValue();
3279   }
3280
3281   // Make sure the parts are all coming from the same node.
3282   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3283     return SDValue();
3284
3285   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3286                               SDValue(Parts[0],0));
3287
3288   // Result of the bswap should be rotated by 16. If it's not legal, then
3289   // do  (x << 16) | (x >> 16).
3290   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3291   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3292     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3293   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3294     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3295   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3296                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3297                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3298 }
3299
3300 SDValue DAGCombiner::visitOR(SDNode *N) {
3301   SDValue N0 = N->getOperand(0);
3302   SDValue N1 = N->getOperand(1);
3303   SDValue LL, LR, RL, RR, CC0, CC1;
3304   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3305   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3306   EVT VT = N1.getValueType();
3307
3308   // fold vector ops
3309   if (VT.isVector()) {
3310     SDValue FoldedVOp = SimplifyVBinOp(N);
3311     if (FoldedVOp.getNode()) return FoldedVOp;
3312
3313     // fold (or x, 0) -> x, vector edition
3314     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3315       return N1;
3316     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3317       return N0;
3318
3319     // fold (or x, -1) -> -1, vector edition
3320     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3321       // do not return N0, because undef node may exist in N0
3322       return DAG.getConstant(
3323           APInt::getAllOnesValue(
3324               N0.getValueType().getScalarType().getSizeInBits()),
3325           N0.getValueType());
3326     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3327       // do not return N1, because undef node may exist in N1
3328       return DAG.getConstant(
3329           APInt::getAllOnesValue(
3330               N1.getValueType().getScalarType().getSizeInBits()),
3331           N1.getValueType());
3332
3333     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3334     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3335     // Do this only if the resulting shuffle is legal.
3336     if (isa<ShuffleVectorSDNode>(N0) &&
3337         isa<ShuffleVectorSDNode>(N1) &&
3338         // Avoid folding a node with illegal type.
3339         TLI.isTypeLegal(VT) &&
3340         N0->getOperand(1) == N1->getOperand(1) &&
3341         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3342       bool CanFold = true;
3343       unsigned NumElts = VT.getVectorNumElements();
3344       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3345       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3346       // We construct two shuffle masks:
3347       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3348       // and N1 as the second operand.
3349       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3350       // and N0 as the second operand.
3351       // We do this because OR is commutable and therefore there might be
3352       // two ways to fold this node into a shuffle.
3353       SmallVector<int,4> Mask1;
3354       SmallVector<int,4> Mask2;
3355
3356       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3357         int M0 = SV0->getMaskElt(i);
3358         int M1 = SV1->getMaskElt(i);
3359
3360         // Both shuffle indexes are undef. Propagate Undef.
3361         if (M0 < 0 && M1 < 0) {
3362           Mask1.push_back(M0);
3363           Mask2.push_back(M0);
3364           continue;
3365         }
3366
3367         if (M0 < 0 || M1 < 0 ||
3368             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3369             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3370           CanFold = false;
3371           break;
3372         }
3373
3374         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3375         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3376       }
3377
3378       if (CanFold) {
3379         // Fold this sequence only if the resulting shuffle is 'legal'.
3380         if (TLI.isShuffleMaskLegal(Mask1, VT))
3381           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3382                                       N1->getOperand(0), &Mask1[0]);
3383         if (TLI.isShuffleMaskLegal(Mask2, VT))
3384           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3385                                       N0->getOperand(0), &Mask2[0]);
3386       }
3387     }
3388   }
3389
3390   // fold (or x, undef) -> -1
3391   if (!LegalOperations &&
3392       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3393     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3394     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3395   }
3396   // fold (or c1, c2) -> c1|c2
3397   if (N0C && N1C)
3398     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3399   // canonicalize constant to RHS
3400   if (N0C && !N1C)
3401     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3402   // fold (or x, 0) -> x
3403   if (N1C && N1C->isNullValue())
3404     return N0;
3405   // fold (or x, -1) -> -1
3406   if (N1C && N1C->isAllOnesValue())
3407     return N1;
3408   // fold (or x, c) -> c iff (x & ~c) == 0
3409   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3410     return N1;
3411
3412   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3413   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3414   if (BSwap.getNode())
3415     return BSwap;
3416   BSwap = MatchBSwapHWordLow(N, N0, N1);
3417   if (BSwap.getNode())
3418     return BSwap;
3419
3420   // reassociate or
3421   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3422   if (ROR.getNode())
3423     return ROR;
3424   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3425   // iff (c1 & c2) == 0.
3426   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3427              isa<ConstantSDNode>(N0.getOperand(1))) {
3428     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3429     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3430       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3431       if (!COR.getNode())
3432         return SDValue();
3433       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3434                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3435                                      N0.getOperand(0), N1), COR);
3436     }
3437   }
3438   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3439   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3440     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3441     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3442
3443     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3444         LL.getValueType().isInteger()) {
3445       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3446       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3447       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3448           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3449         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3450                                      LR.getValueType(), LL, RL);
3451         AddToWorklist(ORNode.getNode());
3452         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3453       }
3454       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3455       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3456       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3457           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3458         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3459                                       LR.getValueType(), LL, RL);
3460         AddToWorklist(ANDNode.getNode());
3461         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3462       }
3463     }
3464     // canonicalize equivalent to ll == rl
3465     if (LL == RR && LR == RL) {
3466       Op1 = ISD::getSetCCSwappedOperands(Op1);
3467       std::swap(RL, RR);
3468     }
3469     if (LL == RL && LR == RR) {
3470       bool isInteger = LL.getValueType().isInteger();
3471       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3472       if (Result != ISD::SETCC_INVALID &&
3473           (!LegalOperations ||
3474            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3475             TLI.isOperationLegal(ISD::SETCC,
3476               getSetCCResultType(N0.getValueType())))))
3477         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3478                             LL, LR, Result);
3479     }
3480   }
3481
3482   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3483   if (N0.getOpcode() == N1.getOpcode()) {
3484     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3485     if (Tmp.getNode()) return Tmp;
3486   }
3487
3488   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3489   if (N0.getOpcode() == ISD::AND &&
3490       N1.getOpcode() == ISD::AND &&
3491       N0.getOperand(1).getOpcode() == ISD::Constant &&
3492       N1.getOperand(1).getOpcode() == ISD::Constant &&
3493       // Don't increase # computations.
3494       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3495     // We can only do this xform if we know that bits from X that are set in C2
3496     // but not in C1 are already zero.  Likewise for Y.
3497     const APInt &LHSMask =
3498       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3499     const APInt &RHSMask =
3500       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3501
3502     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3503         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3504       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3505                               N0.getOperand(0), N1.getOperand(0));
3506       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3507                          DAG.getConstant(LHSMask | RHSMask, VT));
3508     }
3509   }
3510
3511   // See if this is some rotate idiom.
3512   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3513     return SDValue(Rot, 0);
3514
3515   // Simplify the operands using demanded-bits information.
3516   if (!VT.isVector() &&
3517       SimplifyDemandedBits(SDValue(N, 0)))
3518     return SDValue(N, 0);
3519
3520   return SDValue();
3521 }
3522
3523 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3524 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3525   if (Op.getOpcode() == ISD::AND) {
3526     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3527       Mask = Op.getOperand(1);
3528       Op = Op.getOperand(0);
3529     } else {
3530       return false;
3531     }
3532   }
3533
3534   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3535     Shift = Op;
3536     return true;
3537   }
3538
3539   return false;
3540 }
3541
3542 // Return true if we can prove that, whenever Neg and Pos are both in the
3543 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3544 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3545 //
3546 //     (or (shift1 X, Neg), (shift2 X, Pos))
3547 //
3548 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3549 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3550 // to consider shift amounts with defined behavior.
3551 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3552   // If OpSize is a power of 2 then:
3553   //
3554   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3555   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3556   //
3557   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3558   // for the stronger condition:
3559   //
3560   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3561   //
3562   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3563   // we can just replace Neg with Neg' for the rest of the function.
3564   //
3565   // In other cases we check for the even stronger condition:
3566   //
3567   //     Neg == OpSize - Pos                                    [B]
3568   //
3569   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3570   // behavior if Pos == 0 (and consequently Neg == OpSize).
3571   //
3572   // We could actually use [A] whenever OpSize is a power of 2, but the
3573   // only extra cases that it would match are those uninteresting ones
3574   // where Neg and Pos are never in range at the same time.  E.g. for
3575   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3576   // as well as (sub 32, Pos), but:
3577   //
3578   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3579   //
3580   // always invokes undefined behavior for 32-bit X.
3581   //
3582   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3583   unsigned MaskLoBits = 0;
3584   if (Neg.getOpcode() == ISD::AND &&
3585       isPowerOf2_64(OpSize) &&
3586       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3587       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3588     Neg = Neg.getOperand(0);
3589     MaskLoBits = Log2_64(OpSize);
3590   }
3591
3592   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3593   if (Neg.getOpcode() != ISD::SUB)
3594     return 0;
3595   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3596   if (!NegC)
3597     return 0;
3598   SDValue NegOp1 = Neg.getOperand(1);
3599
3600   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3601   // Pos'.  The truncation is redundant for the purpose of the equality.
3602   if (MaskLoBits &&
3603       Pos.getOpcode() == ISD::AND &&
3604       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3605       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3606     Pos = Pos.getOperand(0);
3607
3608   // The condition we need is now:
3609   //
3610   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3611   //
3612   // If NegOp1 == Pos then we need:
3613   //
3614   //              OpSize & Mask == NegC & Mask
3615   //
3616   // (because "x & Mask" is a truncation and distributes through subtraction).
3617   APInt Width;
3618   if (Pos == NegOp1)
3619     Width = NegC->getAPIntValue();
3620   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3621   // Then the condition we want to prove becomes:
3622   //
3623   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3624   //
3625   // which, again because "x & Mask" is a truncation, becomes:
3626   //
3627   //                NegC & Mask == (OpSize - PosC) & Mask
3628   //              OpSize & Mask == (NegC + PosC) & Mask
3629   else if (Pos.getOpcode() == ISD::ADD &&
3630            Pos.getOperand(0) == NegOp1 &&
3631            Pos.getOperand(1).getOpcode() == ISD::Constant)
3632     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3633              NegC->getAPIntValue());
3634   else
3635     return false;
3636
3637   // Now we just need to check that OpSize & Mask == Width & Mask.
3638   if (MaskLoBits)
3639     // Opsize & Mask is 0 since Mask is Opsize - 1.
3640     return Width.getLoBits(MaskLoBits) == 0;
3641   return Width == OpSize;
3642 }
3643
3644 // A subroutine of MatchRotate used once we have found an OR of two opposite
3645 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3646 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3647 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3648 // Neg with outer conversions stripped away.
3649 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3650                                        SDValue Neg, SDValue InnerPos,
3651                                        SDValue InnerNeg, unsigned PosOpcode,
3652                                        unsigned NegOpcode, SDLoc DL) {
3653   // fold (or (shl x, (*ext y)),
3654   //          (srl x, (*ext (sub 32, y)))) ->
3655   //   (rotl x, y) or (rotr x, (sub 32, y))
3656   //
3657   // fold (or (shl x, (*ext (sub 32, y))),
3658   //          (srl x, (*ext y))) ->
3659   //   (rotr x, y) or (rotl x, (sub 32, y))
3660   EVT VT = Shifted.getValueType();
3661   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3662     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3663     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3664                        HasPos ? Pos : Neg).getNode();
3665   }
3666
3667   return nullptr;
3668 }
3669
3670 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3671 // idioms for rotate, and if the target supports rotation instructions, generate
3672 // a rot[lr].
3673 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3674   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3675   EVT VT = LHS.getValueType();
3676   if (!TLI.isTypeLegal(VT)) return nullptr;
3677
3678   // The target must have at least one rotate flavor.
3679   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3680   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3681   if (!HasROTL && !HasROTR) return nullptr;
3682
3683   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3684   SDValue LHSShift;   // The shift.
3685   SDValue LHSMask;    // AND value if any.
3686   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3687     return nullptr; // Not part of a rotate.
3688
3689   SDValue RHSShift;   // The shift.
3690   SDValue RHSMask;    // AND value if any.
3691   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3692     return nullptr; // Not part of a rotate.
3693
3694   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3695     return nullptr;   // Not shifting the same value.
3696
3697   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3698     return nullptr;   // Shifts must disagree.
3699
3700   // Canonicalize shl to left side in a shl/srl pair.
3701   if (RHSShift.getOpcode() == ISD::SHL) {
3702     std::swap(LHS, RHS);
3703     std::swap(LHSShift, RHSShift);
3704     std::swap(LHSMask , RHSMask );
3705   }
3706
3707   unsigned OpSizeInBits = VT.getSizeInBits();
3708   SDValue LHSShiftArg = LHSShift.getOperand(0);
3709   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3710   SDValue RHSShiftArg = RHSShift.getOperand(0);
3711   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3712
3713   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3714   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3715   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3716       RHSShiftAmt.getOpcode() == ISD::Constant) {
3717     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3718     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3719     if ((LShVal + RShVal) != OpSizeInBits)
3720       return nullptr;
3721
3722     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3723                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3724
3725     // If there is an AND of either shifted operand, apply it to the result.
3726     if (LHSMask.getNode() || RHSMask.getNode()) {
3727       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3728
3729       if (LHSMask.getNode()) {
3730         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3731         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3732       }
3733       if (RHSMask.getNode()) {
3734         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3735         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3736       }
3737
3738       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3739     }
3740
3741     return Rot.getNode();
3742   }
3743
3744   // If there is a mask here, and we have a variable shift, we can't be sure
3745   // that we're masking out the right stuff.
3746   if (LHSMask.getNode() || RHSMask.getNode())
3747     return nullptr;
3748
3749   // If the shift amount is sign/zext/any-extended just peel it off.
3750   SDValue LExtOp0 = LHSShiftAmt;
3751   SDValue RExtOp0 = RHSShiftAmt;
3752   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3753        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3754        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3755        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3756       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3757        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3758        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3759        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3760     LExtOp0 = LHSShiftAmt.getOperand(0);
3761     RExtOp0 = RHSShiftAmt.getOperand(0);
3762   }
3763
3764   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3765                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3766   if (TryL)
3767     return TryL;
3768
3769   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3770                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3771   if (TryR)
3772     return TryR;
3773
3774   return nullptr;
3775 }
3776
3777 SDValue DAGCombiner::visitXOR(SDNode *N) {
3778   SDValue N0 = N->getOperand(0);
3779   SDValue N1 = N->getOperand(1);
3780   SDValue LHS, RHS, CC;
3781   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3782   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3783   EVT VT = N0.getValueType();
3784
3785   // fold vector ops
3786   if (VT.isVector()) {
3787     SDValue FoldedVOp = SimplifyVBinOp(N);
3788     if (FoldedVOp.getNode()) return FoldedVOp;
3789
3790     // fold (xor x, 0) -> x, vector edition
3791     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3792       return N1;
3793     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3794       return N0;
3795   }
3796
3797   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3798   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3799     return DAG.getConstant(0, VT);
3800   // fold (xor x, undef) -> undef
3801   if (N0.getOpcode() == ISD::UNDEF)
3802     return N0;
3803   if (N1.getOpcode() == ISD::UNDEF)
3804     return N1;
3805   // fold (xor c1, c2) -> c1^c2
3806   if (N0C && N1C)
3807     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3808   // canonicalize constant to RHS
3809   if (N0C && !N1C)
3810     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3811   // fold (xor x, 0) -> x
3812   if (N1C && N1C->isNullValue())
3813     return N0;
3814   // reassociate xor
3815   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3816   if (RXOR.getNode())
3817     return RXOR;
3818
3819   // fold !(x cc y) -> (x !cc y)
3820   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3821     bool isInt = LHS.getValueType().isInteger();
3822     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3823                                                isInt);
3824
3825     if (!LegalOperations ||
3826         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3827       switch (N0.getOpcode()) {
3828       default:
3829         llvm_unreachable("Unhandled SetCC Equivalent!");
3830       case ISD::SETCC:
3831         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3832       case ISD::SELECT_CC:
3833         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3834                                N0.getOperand(3), NotCC);
3835       }
3836     }
3837   }
3838
3839   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3840   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3841       N0.getNode()->hasOneUse() &&
3842       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3843     SDValue V = N0.getOperand(0);
3844     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3845                     DAG.getConstant(1, V.getValueType()));
3846     AddToWorklist(V.getNode());
3847     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3848   }
3849
3850   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3851   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3852       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3853     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3854     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3855       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3856       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3857       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3858       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3859       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3860     }
3861   }
3862   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3863   if (N1C && N1C->isAllOnesValue() &&
3864       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3865     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3866     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3867       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3868       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3869       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3870       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3871       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3872     }
3873   }
3874   // fold (xor (and x, y), y) -> (and (not x), y)
3875   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3876       N0->getOperand(1) == N1) {
3877     SDValue X = N0->getOperand(0);
3878     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3879     AddToWorklist(NotX.getNode());
3880     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3881   }
3882   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3883   if (N1C && N0.getOpcode() == ISD::XOR) {
3884     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3885     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3886     if (N00C)
3887       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3888                          DAG.getConstant(N1C->getAPIntValue() ^
3889                                          N00C->getAPIntValue(), VT));
3890     if (N01C)
3891       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3892                          DAG.getConstant(N1C->getAPIntValue() ^
3893                                          N01C->getAPIntValue(), VT));
3894   }
3895   // fold (xor x, x) -> 0
3896   if (N0 == N1)
3897     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3898
3899   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3900   if (N0.getOpcode() == N1.getOpcode()) {
3901     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3902     if (Tmp.getNode()) return Tmp;
3903   }
3904
3905   // Simplify the expression using non-local knowledge.
3906   if (!VT.isVector() &&
3907       SimplifyDemandedBits(SDValue(N, 0)))
3908     return SDValue(N, 0);
3909
3910   return SDValue();
3911 }
3912
3913 /// Handle transforms common to the three shifts, when the shift amount is a
3914 /// constant.
3915 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3916   // We can't and shouldn't fold opaque constants.
3917   if (Amt->isOpaque())
3918     return SDValue();
3919
3920   SDNode *LHS = N->getOperand(0).getNode();
3921   if (!LHS->hasOneUse()) return SDValue();
3922
3923   // We want to pull some binops through shifts, so that we have (and (shift))
3924   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3925   // thing happens with address calculations, so it's important to canonicalize
3926   // it.
3927   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3928
3929   switch (LHS->getOpcode()) {
3930   default: return SDValue();
3931   case ISD::OR:
3932   case ISD::XOR:
3933     HighBitSet = false; // We can only transform sra if the high bit is clear.
3934     break;
3935   case ISD::AND:
3936     HighBitSet = true;  // We can only transform sra if the high bit is set.
3937     break;
3938   case ISD::ADD:
3939     if (N->getOpcode() != ISD::SHL)
3940       return SDValue(); // only shl(add) not sr[al](add).
3941     HighBitSet = false; // We can only transform sra if the high bit is clear.
3942     break;
3943   }
3944
3945   // We require the RHS of the binop to be a constant and not opaque as well.
3946   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3947   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3948
3949   // FIXME: disable this unless the input to the binop is a shift by a constant.
3950   // If it is not a shift, it pessimizes some common cases like:
3951   //
3952   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3953   //    int bar(int *X, int i) { return X[i & 255]; }
3954   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3955   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3956        BinOpLHSVal->getOpcode() != ISD::SRA &&
3957        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3958       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3959     return SDValue();
3960
3961   EVT VT = N->getValueType(0);
3962
3963   // If this is a signed shift right, and the high bit is modified by the
3964   // logical operation, do not perform the transformation. The highBitSet
3965   // boolean indicates the value of the high bit of the constant which would
3966   // cause it to be modified for this operation.
3967   if (N->getOpcode() == ISD::SRA) {
3968     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3969     if (BinOpRHSSignSet != HighBitSet)
3970       return SDValue();
3971   }
3972
3973   if (!TLI.isDesirableToCommuteWithShift(LHS))
3974     return SDValue();
3975
3976   // Fold the constants, shifting the binop RHS by the shift amount.
3977   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3978                                N->getValueType(0),
3979                                LHS->getOperand(1), N->getOperand(1));
3980   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3981
3982   // Create the new shift.
3983   SDValue NewShift = DAG.getNode(N->getOpcode(),
3984                                  SDLoc(LHS->getOperand(0)),
3985                                  VT, LHS->getOperand(0), N->getOperand(1));
3986
3987   // Create the new binop.
3988   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3989 }
3990
3991 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3992   assert(N->getOpcode() == ISD::TRUNCATE);
3993   assert(N->getOperand(0).getOpcode() == ISD::AND);
3994
3995   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3996   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3997     SDValue N01 = N->getOperand(0).getOperand(1);
3998
3999     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4000       EVT TruncVT = N->getValueType(0);
4001       SDValue N00 = N->getOperand(0).getOperand(0);
4002       APInt TruncC = N01C->getAPIntValue();
4003       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4004
4005       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4006                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4007                          DAG.getConstant(TruncC, TruncVT));
4008     }
4009   }
4010
4011   return SDValue();
4012 }
4013
4014 SDValue DAGCombiner::visitRotate(SDNode *N) {
4015   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4016   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4017       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4018     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4019     if (NewOp1.getNode())
4020       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4021                          N->getOperand(0), NewOp1);
4022   }
4023   return SDValue();
4024 }
4025
4026 SDValue DAGCombiner::visitSHL(SDNode *N) {
4027   SDValue N0 = N->getOperand(0);
4028   SDValue N1 = N->getOperand(1);
4029   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4030   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4031   EVT VT = N0.getValueType();
4032   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4033
4034   // fold vector ops
4035   if (VT.isVector()) {
4036     SDValue FoldedVOp = SimplifyVBinOp(N);
4037     if (FoldedVOp.getNode()) return FoldedVOp;
4038
4039     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4040     // If setcc produces all-one true value then:
4041     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4042     if (N1CV && N1CV->isConstant()) {
4043       if (N0.getOpcode() == ISD::AND) {
4044         SDValue N00 = N0->getOperand(0);
4045         SDValue N01 = N0->getOperand(1);
4046         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4047
4048         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4049             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4050                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4051           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4052           if (C.getNode())
4053             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4054         }
4055       } else {
4056         N1C = isConstOrConstSplat(N1);
4057       }
4058     }
4059   }
4060
4061   // fold (shl c1, c2) -> c1<<c2
4062   if (N0C && N1C)
4063     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4064   // fold (shl 0, x) -> 0
4065   if (N0C && N0C->isNullValue())
4066     return N0;
4067   // fold (shl x, c >= size(x)) -> undef
4068   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4069     return DAG.getUNDEF(VT);
4070   // fold (shl x, 0) -> x
4071   if (N1C && N1C->isNullValue())
4072     return N0;
4073   // fold (shl undef, x) -> 0
4074   if (N0.getOpcode() == ISD::UNDEF)
4075     return DAG.getConstant(0, VT);
4076   // if (shl x, c) is known to be zero, return 0
4077   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4078                             APInt::getAllOnesValue(OpSizeInBits)))
4079     return DAG.getConstant(0, VT);
4080   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4081   if (N1.getOpcode() == ISD::TRUNCATE &&
4082       N1.getOperand(0).getOpcode() == ISD::AND) {
4083     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4084     if (NewOp1.getNode())
4085       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4086   }
4087
4088   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4089     return SDValue(N, 0);
4090
4091   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4092   if (N1C && N0.getOpcode() == ISD::SHL) {
4093     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4094       uint64_t c1 = N0C1->getZExtValue();
4095       uint64_t c2 = N1C->getZExtValue();
4096       if (c1 + c2 >= OpSizeInBits)
4097         return DAG.getConstant(0, VT);
4098       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4099                          DAG.getConstant(c1 + c2, N1.getValueType()));
4100     }
4101   }
4102
4103   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4104   // For this to be valid, the second form must not preserve any of the bits
4105   // that are shifted out by the inner shift in the first form.  This means
4106   // the outer shift size must be >= the number of bits added by the ext.
4107   // As a corollary, we don't care what kind of ext it is.
4108   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4109               N0.getOpcode() == ISD::ANY_EXTEND ||
4110               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4111       N0.getOperand(0).getOpcode() == ISD::SHL) {
4112     SDValue N0Op0 = N0.getOperand(0);
4113     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4114       uint64_t c1 = N0Op0C1->getZExtValue();
4115       uint64_t c2 = N1C->getZExtValue();
4116       EVT InnerShiftVT = N0Op0.getValueType();
4117       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4118       if (c2 >= OpSizeInBits - InnerShiftSize) {
4119         if (c1 + c2 >= OpSizeInBits)
4120           return DAG.getConstant(0, VT);
4121         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4122                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4123                                        N0Op0->getOperand(0)),
4124                            DAG.getConstant(c1 + c2, N1.getValueType()));
4125       }
4126     }
4127   }
4128
4129   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4130   // Only fold this if the inner zext has no other uses to avoid increasing
4131   // the total number of instructions.
4132   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4133       N0.getOperand(0).getOpcode() == ISD::SRL) {
4134     SDValue N0Op0 = N0.getOperand(0);
4135     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4136       uint64_t c1 = N0Op0C1->getZExtValue();
4137       if (c1 < VT.getScalarSizeInBits()) {
4138         uint64_t c2 = N1C->getZExtValue();
4139         if (c1 == c2) {
4140           SDValue NewOp0 = N0.getOperand(0);
4141           EVT CountVT = NewOp0.getOperand(1).getValueType();
4142           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4143                                        NewOp0, DAG.getConstant(c2, CountVT));
4144           AddToWorklist(NewSHL.getNode());
4145           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4146         }
4147       }
4148     }
4149   }
4150
4151   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4152   //                               (and (srl x, (sub c1, c2), MASK)
4153   // Only fold this if the inner shift has no other uses -- if it does, folding
4154   // this will increase the total number of instructions.
4155   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4156     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4157       uint64_t c1 = N0C1->getZExtValue();
4158       if (c1 < OpSizeInBits) {
4159         uint64_t c2 = N1C->getZExtValue();
4160         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4161         SDValue Shift;
4162         if (c2 > c1) {
4163           Mask = Mask.shl(c2 - c1);
4164           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4165                               DAG.getConstant(c2 - c1, N1.getValueType()));
4166         } else {
4167           Mask = Mask.lshr(c1 - c2);
4168           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4169                               DAG.getConstant(c1 - c2, N1.getValueType()));
4170         }
4171         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4172                            DAG.getConstant(Mask, VT));
4173       }
4174     }
4175   }
4176   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4177   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4178     unsigned BitSize = VT.getScalarSizeInBits();
4179     SDValue HiBitsMask =
4180       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4181                                             BitSize - N1C->getZExtValue()), VT);
4182     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4183                        HiBitsMask);
4184   }
4185
4186   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4187   // Variant of version done on multiply, except mul by a power of 2 is turned
4188   // into a shift.
4189   APInt Val;
4190   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4191       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4192        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4193     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4194     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4195     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4196   }
4197
4198   if (N1C) {
4199     SDValue NewSHL = visitShiftByConstant(N, N1C);
4200     if (NewSHL.getNode())
4201       return NewSHL;
4202   }
4203
4204   return SDValue();
4205 }
4206
4207 SDValue DAGCombiner::visitSRA(SDNode *N) {
4208   SDValue N0 = N->getOperand(0);
4209   SDValue N1 = N->getOperand(1);
4210   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4211   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4212   EVT VT = N0.getValueType();
4213   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4214
4215   // fold vector ops
4216   if (VT.isVector()) {
4217     SDValue FoldedVOp = SimplifyVBinOp(N);
4218     if (FoldedVOp.getNode()) return FoldedVOp;
4219
4220     N1C = isConstOrConstSplat(N1);
4221   }
4222
4223   // fold (sra c1, c2) -> (sra c1, c2)
4224   if (N0C && N1C)
4225     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4226   // fold (sra 0, x) -> 0
4227   if (N0C && N0C->isNullValue())
4228     return N0;
4229   // fold (sra -1, x) -> -1
4230   if (N0C && N0C->isAllOnesValue())
4231     return N0;
4232   // fold (sra x, (setge c, size(x))) -> undef
4233   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4234     return DAG.getUNDEF(VT);
4235   // fold (sra x, 0) -> x
4236   if (N1C && N1C->isNullValue())
4237     return N0;
4238   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4239   // sext_inreg.
4240   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4241     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4242     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4243     if (VT.isVector())
4244       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4245                                ExtVT, VT.getVectorNumElements());
4246     if ((!LegalOperations ||
4247          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4248       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4249                          N0.getOperand(0), DAG.getValueType(ExtVT));
4250   }
4251
4252   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4253   if (N1C && N0.getOpcode() == ISD::SRA) {
4254     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4255       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4256       if (Sum >= OpSizeInBits)
4257         Sum = OpSizeInBits - 1;
4258       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4259                          DAG.getConstant(Sum, N1.getValueType()));
4260     }
4261   }
4262
4263   // fold (sra (shl X, m), (sub result_size, n))
4264   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4265   // result_size - n != m.
4266   // If truncate is free for the target sext(shl) is likely to result in better
4267   // code.
4268   if (N0.getOpcode() == ISD::SHL && N1C) {
4269     // Get the two constanst of the shifts, CN0 = m, CN = n.
4270     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4271     if (N01C) {
4272       LLVMContext &Ctx = *DAG.getContext();
4273       // Determine what the truncate's result bitsize and type would be.
4274       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4275
4276       if (VT.isVector())
4277         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4278
4279       // Determine the residual right-shift amount.
4280       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4281
4282       // If the shift is not a no-op (in which case this should be just a sign
4283       // extend already), the truncated to type is legal, sign_extend is legal
4284       // on that type, and the truncate to that type is both legal and free,
4285       // perform the transform.
4286       if ((ShiftAmt > 0) &&
4287           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4288           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4289           TLI.isTruncateFree(VT, TruncVT)) {
4290
4291           SDValue Amt = DAG.getConstant(ShiftAmt,
4292               getShiftAmountTy(N0.getOperand(0).getValueType()));
4293           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4294                                       N0.getOperand(0), Amt);
4295           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4296                                       Shift);
4297           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4298                              N->getValueType(0), Trunc);
4299       }
4300     }
4301   }
4302
4303   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4304   if (N1.getOpcode() == ISD::TRUNCATE &&
4305       N1.getOperand(0).getOpcode() == ISD::AND) {
4306     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4307     if (NewOp1.getNode())
4308       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4309   }
4310
4311   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4312   //      if c1 is equal to the number of bits the trunc removes
4313   if (N0.getOpcode() == ISD::TRUNCATE &&
4314       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4315        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4316       N0.getOperand(0).hasOneUse() &&
4317       N0.getOperand(0).getOperand(1).hasOneUse() &&
4318       N1C) {
4319     SDValue N0Op0 = N0.getOperand(0);
4320     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4321       unsigned LargeShiftVal = LargeShift->getZExtValue();
4322       EVT LargeVT = N0Op0.getValueType();
4323
4324       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4325         SDValue Amt =
4326           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4327                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4328         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4329                                   N0Op0.getOperand(0), Amt);
4330         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4331       }
4332     }
4333   }
4334
4335   // Simplify, based on bits shifted out of the LHS.
4336   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4337     return SDValue(N, 0);
4338
4339
4340   // If the sign bit is known to be zero, switch this to a SRL.
4341   if (DAG.SignBitIsZero(N0))
4342     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4343
4344   if (N1C) {
4345     SDValue NewSRA = visitShiftByConstant(N, N1C);
4346     if (NewSRA.getNode())
4347       return NewSRA;
4348   }
4349
4350   return SDValue();
4351 }
4352
4353 SDValue DAGCombiner::visitSRL(SDNode *N) {
4354   SDValue N0 = N->getOperand(0);
4355   SDValue N1 = N->getOperand(1);
4356   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4357   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4358   EVT VT = N0.getValueType();
4359   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4360
4361   // fold vector ops
4362   if (VT.isVector()) {
4363     SDValue FoldedVOp = SimplifyVBinOp(N);
4364     if (FoldedVOp.getNode()) return FoldedVOp;
4365
4366     N1C = isConstOrConstSplat(N1);
4367   }
4368
4369   // fold (srl c1, c2) -> c1 >>u c2
4370   if (N0C && N1C)
4371     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4372   // fold (srl 0, x) -> 0
4373   if (N0C && N0C->isNullValue())
4374     return N0;
4375   // fold (srl x, c >= size(x)) -> undef
4376   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4377     return DAG.getUNDEF(VT);
4378   // fold (srl x, 0) -> x
4379   if (N1C && N1C->isNullValue())
4380     return N0;
4381   // if (srl x, c) is known to be zero, return 0
4382   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4383                                    APInt::getAllOnesValue(OpSizeInBits)))
4384     return DAG.getConstant(0, VT);
4385
4386   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4387   if (N1C && N0.getOpcode() == ISD::SRL) {
4388     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4389       uint64_t c1 = N01C->getZExtValue();
4390       uint64_t c2 = N1C->getZExtValue();
4391       if (c1 + c2 >= OpSizeInBits)
4392         return DAG.getConstant(0, VT);
4393       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4394                          DAG.getConstant(c1 + c2, N1.getValueType()));
4395     }
4396   }
4397
4398   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4399   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4400       N0.getOperand(0).getOpcode() == ISD::SRL &&
4401       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4402     uint64_t c1 =
4403       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4404     uint64_t c2 = N1C->getZExtValue();
4405     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4406     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4407     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4408     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4409     if (c1 + OpSizeInBits == InnerShiftSize) {
4410       if (c1 + c2 >= InnerShiftSize)
4411         return DAG.getConstant(0, VT);
4412       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4413                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4414                                      N0.getOperand(0)->getOperand(0),
4415                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4416     }
4417   }
4418
4419   // fold (srl (shl x, c), c) -> (and x, cst2)
4420   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4421     unsigned BitSize = N0.getScalarValueSizeInBits();
4422     if (BitSize <= 64) {
4423       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4424       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4425                          DAG.getConstant(~0ULL >> ShAmt, VT));
4426     }
4427   }
4428
4429   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4430   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4431     // Shifting in all undef bits?
4432     EVT SmallVT = N0.getOperand(0).getValueType();
4433     unsigned BitSize = SmallVT.getScalarSizeInBits();
4434     if (N1C->getZExtValue() >= BitSize)
4435       return DAG.getUNDEF(VT);
4436
4437     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4438       uint64_t ShiftAmt = N1C->getZExtValue();
4439       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4440                                        N0.getOperand(0),
4441                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4442       AddToWorklist(SmallShift.getNode());
4443       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4444       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4445                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4446                          DAG.getConstant(Mask, VT));
4447     }
4448   }
4449
4450   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4451   // bit, which is unmodified by sra.
4452   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4453     if (N0.getOpcode() == ISD::SRA)
4454       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4455   }
4456
4457   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4458   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4459       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4460     APInt KnownZero, KnownOne;
4461     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4462
4463     // If any of the input bits are KnownOne, then the input couldn't be all
4464     // zeros, thus the result of the srl will always be zero.
4465     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4466
4467     // If all of the bits input the to ctlz node are known to be zero, then
4468     // the result of the ctlz is "32" and the result of the shift is one.
4469     APInt UnknownBits = ~KnownZero;
4470     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4471
4472     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4473     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4474       // Okay, we know that only that the single bit specified by UnknownBits
4475       // could be set on input to the CTLZ node. If this bit is set, the SRL
4476       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4477       // to an SRL/XOR pair, which is likely to simplify more.
4478       unsigned ShAmt = UnknownBits.countTrailingZeros();
4479       SDValue Op = N0.getOperand(0);
4480
4481       if (ShAmt) {
4482         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4483                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4484         AddToWorklist(Op.getNode());
4485       }
4486
4487       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4488                          Op, DAG.getConstant(1, VT));
4489     }
4490   }
4491
4492   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4493   if (N1.getOpcode() == ISD::TRUNCATE &&
4494       N1.getOperand(0).getOpcode() == ISD::AND) {
4495     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4496     if (NewOp1.getNode())
4497       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4498   }
4499
4500   // fold operands of srl based on knowledge that the low bits are not
4501   // demanded.
4502   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4503     return SDValue(N, 0);
4504
4505   if (N1C) {
4506     SDValue NewSRL = visitShiftByConstant(N, N1C);
4507     if (NewSRL.getNode())
4508       return NewSRL;
4509   }
4510
4511   // Attempt to convert a srl of a load into a narrower zero-extending load.
4512   SDValue NarrowLoad = ReduceLoadWidth(N);
4513   if (NarrowLoad.getNode())
4514     return NarrowLoad;
4515
4516   // Here is a common situation. We want to optimize:
4517   //
4518   //   %a = ...
4519   //   %b = and i32 %a, 2
4520   //   %c = srl i32 %b, 1
4521   //   brcond i32 %c ...
4522   //
4523   // into
4524   //
4525   //   %a = ...
4526   //   %b = and %a, 2
4527   //   %c = setcc eq %b, 0
4528   //   brcond %c ...
4529   //
4530   // However when after the source operand of SRL is optimized into AND, the SRL
4531   // itself may not be optimized further. Look for it and add the BRCOND into
4532   // the worklist.
4533   if (N->hasOneUse()) {
4534     SDNode *Use = *N->use_begin();
4535     if (Use->getOpcode() == ISD::BRCOND)
4536       AddToWorklist(Use);
4537     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4538       // Also look pass the truncate.
4539       Use = *Use->use_begin();
4540       if (Use->getOpcode() == ISD::BRCOND)
4541         AddToWorklist(Use);
4542     }
4543   }
4544
4545   return SDValue();
4546 }
4547
4548 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4549   SDValue N0 = N->getOperand(0);
4550   EVT VT = N->getValueType(0);
4551
4552   // fold (ctlz c1) -> c2
4553   if (isa<ConstantSDNode>(N0))
4554     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4555   return SDValue();
4556 }
4557
4558 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4559   SDValue N0 = N->getOperand(0);
4560   EVT VT = N->getValueType(0);
4561
4562   // fold (ctlz_zero_undef c1) -> c2
4563   if (isa<ConstantSDNode>(N0))
4564     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4565   return SDValue();
4566 }
4567
4568 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4569   SDValue N0 = N->getOperand(0);
4570   EVT VT = N->getValueType(0);
4571
4572   // fold (cttz c1) -> c2
4573   if (isa<ConstantSDNode>(N0))
4574     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4575   return SDValue();
4576 }
4577
4578 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4579   SDValue N0 = N->getOperand(0);
4580   EVT VT = N->getValueType(0);
4581
4582   // fold (cttz_zero_undef c1) -> c2
4583   if (isa<ConstantSDNode>(N0))
4584     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4585   return SDValue();
4586 }
4587
4588 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4589   SDValue N0 = N->getOperand(0);
4590   EVT VT = N->getValueType(0);
4591
4592   // fold (ctpop c1) -> c2
4593   if (isa<ConstantSDNode>(N0))
4594     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4595   return SDValue();
4596 }
4597
4598 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4599   SDValue N0 = N->getOperand(0);
4600   SDValue N1 = N->getOperand(1);
4601   SDValue N2 = N->getOperand(2);
4602   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4604   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4605   EVT VT = N->getValueType(0);
4606   EVT VT0 = N0.getValueType();
4607
4608   // fold (select C, X, X) -> X
4609   if (N1 == N2)
4610     return N1;
4611   // fold (select true, X, Y) -> X
4612   if (N0C && !N0C->isNullValue())
4613     return N1;
4614   // fold (select false, X, Y) -> Y
4615   if (N0C && N0C->isNullValue())
4616     return N2;
4617   // fold (select C, 1, X) -> (or C, X)
4618   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4619     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4620   // fold (select C, 0, 1) -> (xor C, 1)
4621   // We can't do this reliably if integer based booleans have different contents
4622   // to floating point based booleans. This is because we can't tell whether we
4623   // have an integer-based boolean or a floating-point-based boolean unless we
4624   // can find the SETCC that produced it and inspect its operands. This is
4625   // fairly easy if C is the SETCC node, but it can potentially be
4626   // undiscoverable (or not reasonably discoverable). For example, it could be
4627   // in another basic block or it could require searching a complicated
4628   // expression.
4629   if (VT.isInteger() &&
4630       (VT0 == MVT::i1 || (VT0.isInteger() &&
4631                           TLI.getBooleanContents(false, false) ==
4632                               TLI.getBooleanContents(false, true) &&
4633                           TLI.getBooleanContents(false, false) ==
4634                               TargetLowering::ZeroOrOneBooleanContent)) &&
4635       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4636     SDValue XORNode;
4637     if (VT == VT0)
4638       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4639                          N0, DAG.getConstant(1, VT0));
4640     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4641                           N0, DAG.getConstant(1, VT0));
4642     AddToWorklist(XORNode.getNode());
4643     if (VT.bitsGT(VT0))
4644       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4645     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4646   }
4647   // fold (select C, 0, X) -> (and (not C), X)
4648   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4649     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4650     AddToWorklist(NOTNode.getNode());
4651     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4652   }
4653   // fold (select C, X, 1) -> (or (not C), X)
4654   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4655     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4656     AddToWorklist(NOTNode.getNode());
4657     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4658   }
4659   // fold (select C, X, 0) -> (and C, X)
4660   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4661     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4662   // fold (select X, X, Y) -> (or X, Y)
4663   // fold (select X, 1, Y) -> (or X, Y)
4664   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4665     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4666   // fold (select X, Y, X) -> (and X, Y)
4667   // fold (select X, Y, 0) -> (and X, Y)
4668   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4669     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4670
4671   // If we can fold this based on the true/false value, do so.
4672   if (SimplifySelectOps(N, N1, N2))
4673     return SDValue(N, 0);  // Don't revisit N.
4674
4675   // fold selects based on a setcc into other things, such as min/max/abs
4676   if (N0.getOpcode() == ISD::SETCC) {
4677     if ((!LegalOperations &&
4678          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4679         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4680       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4681                          N0.getOperand(0), N0.getOperand(1),
4682                          N1, N2, N0.getOperand(2));
4683     return SimplifySelect(SDLoc(N), N0, N1, N2);
4684   }
4685
4686   return SDValue();
4687 }
4688
4689 static
4690 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4691   SDLoc DL(N);
4692   EVT LoVT, HiVT;
4693   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4694
4695   // Split the inputs.
4696   SDValue Lo, Hi, LL, LH, RL, RH;
4697   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4698   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4699
4700   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4701   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4702
4703   return std::make_pair(Lo, Hi);
4704 }
4705
4706 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4707 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4708 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4709   SDLoc dl(N);
4710   SDValue Cond = N->getOperand(0);
4711   SDValue LHS = N->getOperand(1);
4712   SDValue RHS = N->getOperand(2);
4713   EVT VT = N->getValueType(0);
4714   int NumElems = VT.getVectorNumElements();
4715   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4716          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4717          Cond.getOpcode() == ISD::BUILD_VECTOR);
4718
4719   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4720   // binary ones here.
4721   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4722     return SDValue();
4723
4724   // We're sure we have an even number of elements due to the
4725   // concat_vectors we have as arguments to vselect.
4726   // Skip BV elements until we find one that's not an UNDEF
4727   // After we find an UNDEF element, keep looping until we get to half the
4728   // length of the BV and see if all the non-undef nodes are the same.
4729   ConstantSDNode *BottomHalf = nullptr;
4730   for (int i = 0; i < NumElems / 2; ++i) {
4731     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4732       continue;
4733
4734     if (BottomHalf == nullptr)
4735       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4736     else if (Cond->getOperand(i).getNode() != BottomHalf)
4737       return SDValue();
4738   }
4739
4740   // Do the same for the second half of the BuildVector
4741   ConstantSDNode *TopHalf = nullptr;
4742   for (int i = NumElems / 2; i < NumElems; ++i) {
4743     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4744       continue;
4745
4746     if (TopHalf == nullptr)
4747       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4748     else if (Cond->getOperand(i).getNode() != TopHalf)
4749       return SDValue();
4750   }
4751
4752   assert(TopHalf && BottomHalf &&
4753          "One half of the selector was all UNDEFs and the other was all the "
4754          "same value. This should have been addressed before this function.");
4755   return DAG.getNode(
4756       ISD::CONCAT_VECTORS, dl, VT,
4757       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4758       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4759 }
4760
4761 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4762   SDValue N0 = N->getOperand(0);
4763   SDValue N1 = N->getOperand(1);
4764   SDValue N2 = N->getOperand(2);
4765   SDLoc DL(N);
4766
4767   // Canonicalize integer abs.
4768   // vselect (setg[te] X,  0),  X, -X ->
4769   // vselect (setgt    X, -1),  X, -X ->
4770   // vselect (setl[te] X,  0), -X,  X ->
4771   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4772   if (N0.getOpcode() == ISD::SETCC) {
4773     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4774     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4775     bool isAbs = false;
4776     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4777
4778     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4779          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4780         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4781       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4782     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4783              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4784       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4785
4786     if (isAbs) {
4787       EVT VT = LHS.getValueType();
4788       SDValue Shift = DAG.getNode(
4789           ISD::SRA, DL, VT, LHS,
4790           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4791       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4792       AddToWorklist(Shift.getNode());
4793       AddToWorklist(Add.getNode());
4794       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4795     }
4796   }
4797
4798   // If the VSELECT result requires splitting and the mask is provided by a
4799   // SETCC, then split both nodes and its operands before legalization. This
4800   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4801   // and enables future optimizations (e.g. min/max pattern matching on X86).
4802   if (N0.getOpcode() == ISD::SETCC) {
4803     EVT VT = N->getValueType(0);
4804
4805     // Check if any splitting is required.
4806     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4807         TargetLowering::TypeSplitVector)
4808       return SDValue();
4809
4810     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4811     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4812     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4813     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4814
4815     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4816     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4817
4818     // Add the new VSELECT nodes to the work list in case they need to be split
4819     // again.
4820     AddToWorklist(Lo.getNode());
4821     AddToWorklist(Hi.getNode());
4822
4823     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4824   }
4825
4826   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4827   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4828     return N1;
4829   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4830   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4831     return N2;
4832
4833   // The ConvertSelectToConcatVector function is assuming both the above
4834   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4835   // and addressed.
4836   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4837       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4838       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4839     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4840     if (CV.getNode())
4841       return CV;
4842   }
4843
4844   return SDValue();
4845 }
4846
4847 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4848   SDValue N0 = N->getOperand(0);
4849   SDValue N1 = N->getOperand(1);
4850   SDValue N2 = N->getOperand(2);
4851   SDValue N3 = N->getOperand(3);
4852   SDValue N4 = N->getOperand(4);
4853   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4854
4855   // fold select_cc lhs, rhs, x, x, cc -> x
4856   if (N2 == N3)
4857     return N2;
4858
4859   // Determine if the condition we're dealing with is constant
4860   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4861                               N0, N1, CC, SDLoc(N), false);
4862   if (SCC.getNode()) {
4863     AddToWorklist(SCC.getNode());
4864
4865     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4866       if (!SCCC->isNullValue())
4867         return N2;    // cond always true -> true val
4868       else
4869         return N3;    // cond always false -> false val
4870     }
4871
4872     // Fold to a simpler select_cc
4873     if (SCC.getOpcode() == ISD::SETCC)
4874       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4875                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4876                          SCC.getOperand(2));
4877   }
4878
4879   // If we can fold this based on the true/false value, do so.
4880   if (SimplifySelectOps(N, N2, N3))
4881     return SDValue(N, 0);  // Don't revisit N.
4882
4883   // fold select_cc into other things, such as min/max/abs
4884   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4885 }
4886
4887 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4888   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4889                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4890                        SDLoc(N));
4891 }
4892
4893 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4894 // dag node into a ConstantSDNode or a build_vector of constants.
4895 // This function is called by the DAGCombiner when visiting sext/zext/aext
4896 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4897 // Vector extends are not folded if operations are legal; this is to
4898 // avoid introducing illegal build_vector dag nodes.
4899 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4900                                          SelectionDAG &DAG, bool LegalTypes,
4901                                          bool LegalOperations) {
4902   unsigned Opcode = N->getOpcode();
4903   SDValue N0 = N->getOperand(0);
4904   EVT VT = N->getValueType(0);
4905
4906   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4907          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4908
4909   // fold (sext c1) -> c1
4910   // fold (zext c1) -> c1
4911   // fold (aext c1) -> c1
4912   if (isa<ConstantSDNode>(N0))
4913     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4914
4915   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4916   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4917   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4918   EVT SVT = VT.getScalarType();
4919   if (!(VT.isVector() &&
4920       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4921       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4922     return nullptr;
4923
4924   // We can fold this node into a build_vector.
4925   unsigned VTBits = SVT.getSizeInBits();
4926   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4927   unsigned ShAmt = VTBits - EVTBits;
4928   SmallVector<SDValue, 8> Elts;
4929   unsigned NumElts = N0->getNumOperands();
4930   SDLoc DL(N);
4931
4932   for (unsigned i=0; i != NumElts; ++i) {
4933     SDValue Op = N0->getOperand(i);
4934     if (Op->getOpcode() == ISD::UNDEF) {
4935       Elts.push_back(DAG.getUNDEF(SVT));
4936       continue;
4937     }
4938
4939     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4940     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4941     if (Opcode == ISD::SIGN_EXTEND)
4942       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4943                                      SVT));
4944     else
4945       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4946                                      SVT));
4947   }
4948
4949   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4950 }
4951
4952 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4953 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4954 // transformation. Returns true if extension are possible and the above
4955 // mentioned transformation is profitable.
4956 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4957                                     unsigned ExtOpc,
4958                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4959                                     const TargetLowering &TLI) {
4960   bool HasCopyToRegUses = false;
4961   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4962   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4963                             UE = N0.getNode()->use_end();
4964        UI != UE; ++UI) {
4965     SDNode *User = *UI;
4966     if (User == N)
4967       continue;
4968     if (UI.getUse().getResNo() != N0.getResNo())
4969       continue;
4970     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4971     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4972       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4973       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4974         // Sign bits will be lost after a zext.
4975         return false;
4976       bool Add = false;
4977       for (unsigned i = 0; i != 2; ++i) {
4978         SDValue UseOp = User->getOperand(i);
4979         if (UseOp == N0)
4980           continue;
4981         if (!isa<ConstantSDNode>(UseOp))
4982           return false;
4983         Add = true;
4984       }
4985       if (Add)
4986         ExtendNodes.push_back(User);
4987       continue;
4988     }
4989     // If truncates aren't free and there are users we can't
4990     // extend, it isn't worthwhile.
4991     if (!isTruncFree)
4992       return false;
4993     // Remember if this value is live-out.
4994     if (User->getOpcode() == ISD::CopyToReg)
4995       HasCopyToRegUses = true;
4996   }
4997
4998   if (HasCopyToRegUses) {
4999     bool BothLiveOut = false;
5000     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5001          UI != UE; ++UI) {
5002       SDUse &Use = UI.getUse();
5003       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5004         BothLiveOut = true;
5005         break;
5006       }
5007     }
5008     if (BothLiveOut)
5009       // Both unextended and extended values are live out. There had better be
5010       // a good reason for the transformation.
5011       return ExtendNodes.size();
5012   }
5013   return true;
5014 }
5015
5016 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5017                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5018                                   ISD::NodeType ExtType) {
5019   // Extend SetCC uses if necessary.
5020   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5021     SDNode *SetCC = SetCCs[i];
5022     SmallVector<SDValue, 4> Ops;
5023
5024     for (unsigned j = 0; j != 2; ++j) {
5025       SDValue SOp = SetCC->getOperand(j);
5026       if (SOp == Trunc)
5027         Ops.push_back(ExtLoad);
5028       else
5029         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5030     }
5031
5032     Ops.push_back(SetCC->getOperand(2));
5033     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5034   }
5035 }
5036
5037 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5038   SDValue N0 = N->getOperand(0);
5039   EVT VT = N->getValueType(0);
5040
5041   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5042                                               LegalOperations))
5043     return SDValue(Res, 0);
5044
5045   // fold (sext (sext x)) -> (sext x)
5046   // fold (sext (aext x)) -> (sext x)
5047   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5048     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5049                        N0.getOperand(0));
5050
5051   if (N0.getOpcode() == ISD::TRUNCATE) {
5052     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5053     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5054     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5055     if (NarrowLoad.getNode()) {
5056       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5057       if (NarrowLoad.getNode() != N0.getNode()) {
5058         CombineTo(N0.getNode(), NarrowLoad);
5059         // CombineTo deleted the truncate, if needed, but not what's under it.
5060         AddToWorklist(oye);
5061       }
5062       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5063     }
5064
5065     // See if the value being truncated is already sign extended.  If so, just
5066     // eliminate the trunc/sext pair.
5067     SDValue Op = N0.getOperand(0);
5068     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5069     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5070     unsigned DestBits = VT.getScalarType().getSizeInBits();
5071     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5072
5073     if (OpBits == DestBits) {
5074       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5075       // bits, it is already ready.
5076       if (NumSignBits > DestBits-MidBits)
5077         return Op;
5078     } else if (OpBits < DestBits) {
5079       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5080       // bits, just sext from i32.
5081       if (NumSignBits > OpBits-MidBits)
5082         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5083     } else {
5084       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5085       // bits, just truncate to i32.
5086       if (NumSignBits > OpBits-MidBits)
5087         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5088     }
5089
5090     // fold (sext (truncate x)) -> (sextinreg x).
5091     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5092                                                  N0.getValueType())) {
5093       if (OpBits < DestBits)
5094         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5095       else if (OpBits > DestBits)
5096         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5097       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5098                          DAG.getValueType(N0.getValueType()));
5099     }
5100   }
5101
5102   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5103   // None of the supported targets knows how to perform load and sign extend
5104   // on vectors in one instruction.  We only perform this transformation on
5105   // scalars.
5106   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5107       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5108       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5109        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5110     bool DoXform = true;
5111     SmallVector<SDNode*, 4> SetCCs;
5112     if (!N0.hasOneUse())
5113       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5114     if (DoXform) {
5115       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5116       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5117                                        LN0->getChain(),
5118                                        LN0->getBasePtr(), N0.getValueType(),
5119                                        LN0->getMemOperand());
5120       CombineTo(N, ExtLoad);
5121       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5122                                   N0.getValueType(), ExtLoad);
5123       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5124       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5125                       ISD::SIGN_EXTEND);
5126       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5127     }
5128   }
5129
5130   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5131   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5132   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5133       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5134     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5135     EVT MemVT = LN0->getMemoryVT();
5136     if ((!LegalOperations && !LN0->isVolatile()) ||
5137         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5138       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5139                                        LN0->getChain(),
5140                                        LN0->getBasePtr(), MemVT,
5141                                        LN0->getMemOperand());
5142       CombineTo(N, ExtLoad);
5143       CombineTo(N0.getNode(),
5144                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5145                             N0.getValueType(), ExtLoad),
5146                 ExtLoad.getValue(1));
5147       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5148     }
5149   }
5150
5151   // fold (sext (and/or/xor (load x), cst)) ->
5152   //      (and/or/xor (sextload x), (sext cst))
5153   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5154        N0.getOpcode() == ISD::XOR) &&
5155       isa<LoadSDNode>(N0.getOperand(0)) &&
5156       N0.getOperand(1).getOpcode() == ISD::Constant &&
5157       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5158       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5159     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5160     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5161       bool DoXform = true;
5162       SmallVector<SDNode*, 4> SetCCs;
5163       if (!N0.hasOneUse())
5164         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5165                                           SetCCs, TLI);
5166       if (DoXform) {
5167         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5168                                          LN0->getChain(), LN0->getBasePtr(),
5169                                          LN0->getMemoryVT(),
5170                                          LN0->getMemOperand());
5171         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5172         Mask = Mask.sext(VT.getSizeInBits());
5173         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5174                                   ExtLoad, DAG.getConstant(Mask, VT));
5175         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5176                                     SDLoc(N0.getOperand(0)),
5177                                     N0.getOperand(0).getValueType(), ExtLoad);
5178         CombineTo(N, And);
5179         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5180         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5181                         ISD::SIGN_EXTEND);
5182         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5183       }
5184     }
5185   }
5186
5187   if (N0.getOpcode() == ISD::SETCC) {
5188     EVT N0VT = N0.getOperand(0).getValueType();
5189     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5190     // Only do this before legalize for now.
5191     if (VT.isVector() && !LegalOperations &&
5192         TLI.getBooleanContents(N0VT) ==
5193             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5194       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5195       // of the same size as the compared operands. Only optimize sext(setcc())
5196       // if this is the case.
5197       EVT SVT = getSetCCResultType(N0VT);
5198
5199       // We know that the # elements of the results is the same as the
5200       // # elements of the compare (and the # elements of the compare result
5201       // for that matter).  Check to see that they are the same size.  If so,
5202       // we know that the element size of the sext'd result matches the
5203       // element size of the compare operands.
5204       if (VT.getSizeInBits() == SVT.getSizeInBits())
5205         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5206                              N0.getOperand(1),
5207                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5208
5209       // If the desired elements are smaller or larger than the source
5210       // elements we can use a matching integer vector type and then
5211       // truncate/sign extend
5212       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5213       if (SVT == MatchingVectorType) {
5214         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5215                                N0.getOperand(0), N0.getOperand(1),
5216                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5217         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5218       }
5219     }
5220
5221     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5222     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5223     SDValue NegOne =
5224       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5225     SDValue SCC =
5226       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5227                        NegOne, DAG.getConstant(0, VT),
5228                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5229     if (SCC.getNode()) return SCC;
5230
5231     if (!VT.isVector()) {
5232       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5233       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5234         SDLoc DL(N);
5235         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5236         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5237                                      N0.getOperand(0), N0.getOperand(1), CC);
5238         return DAG.getSelect(DL, VT, SetCC,
5239                              NegOne, DAG.getConstant(0, VT));
5240       }
5241     }
5242   }
5243
5244   // fold (sext x) -> (zext x) if the sign bit is known zero.
5245   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5246       DAG.SignBitIsZero(N0))
5247     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5248
5249   return SDValue();
5250 }
5251
5252 // isTruncateOf - If N is a truncate of some other value, return true, record
5253 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5254 // This function computes KnownZero to avoid a duplicated call to
5255 // computeKnownBits in the caller.
5256 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5257                          APInt &KnownZero) {
5258   APInt KnownOne;
5259   if (N->getOpcode() == ISD::TRUNCATE) {
5260     Op = N->getOperand(0);
5261     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5262     return true;
5263   }
5264
5265   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5266       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5267     return false;
5268
5269   SDValue Op0 = N->getOperand(0);
5270   SDValue Op1 = N->getOperand(1);
5271   assert(Op0.getValueType() == Op1.getValueType());
5272
5273   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5274   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5275   if (COp0 && COp0->isNullValue())
5276     Op = Op1;
5277   else if (COp1 && COp1->isNullValue())
5278     Op = Op0;
5279   else
5280     return false;
5281
5282   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5283
5284   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5285     return false;
5286
5287   return true;
5288 }
5289
5290 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5291   SDValue N0 = N->getOperand(0);
5292   EVT VT = N->getValueType(0);
5293
5294   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5295                                               LegalOperations))
5296     return SDValue(Res, 0);
5297
5298   // fold (zext (zext x)) -> (zext x)
5299   // fold (zext (aext x)) -> (zext x)
5300   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5301     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5302                        N0.getOperand(0));
5303
5304   // fold (zext (truncate x)) -> (zext x) or
5305   //      (zext (truncate x)) -> (truncate x)
5306   // This is valid when the truncated bits of x are already zero.
5307   // FIXME: We should extend this to work for vectors too.
5308   SDValue Op;
5309   APInt KnownZero;
5310   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5311     APInt TruncatedBits =
5312       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5313       APInt(Op.getValueSizeInBits(), 0) :
5314       APInt::getBitsSet(Op.getValueSizeInBits(),
5315                         N0.getValueSizeInBits(),
5316                         std::min(Op.getValueSizeInBits(),
5317                                  VT.getSizeInBits()));
5318     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5319       if (VT.bitsGT(Op.getValueType()))
5320         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5321       if (VT.bitsLT(Op.getValueType()))
5322         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5323
5324       return Op;
5325     }
5326   }
5327
5328   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5329   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5330   if (N0.getOpcode() == ISD::TRUNCATE) {
5331     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5332     if (NarrowLoad.getNode()) {
5333       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5334       if (NarrowLoad.getNode() != N0.getNode()) {
5335         CombineTo(N0.getNode(), NarrowLoad);
5336         // CombineTo deleted the truncate, if needed, but not what's under it.
5337         AddToWorklist(oye);
5338       }
5339       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5340     }
5341   }
5342
5343   // fold (zext (truncate x)) -> (and x, mask)
5344   if (N0.getOpcode() == ISD::TRUNCATE &&
5345       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5346
5347     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5348     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5349     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5350     if (NarrowLoad.getNode()) {
5351       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5352       if (NarrowLoad.getNode() != N0.getNode()) {
5353         CombineTo(N0.getNode(), NarrowLoad);
5354         // CombineTo deleted the truncate, if needed, but not what's under it.
5355         AddToWorklist(oye);
5356       }
5357       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5358     }
5359
5360     SDValue Op = N0.getOperand(0);
5361     if (Op.getValueType().bitsLT(VT)) {
5362       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5363       AddToWorklist(Op.getNode());
5364     } else if (Op.getValueType().bitsGT(VT)) {
5365       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5366       AddToWorklist(Op.getNode());
5367     }
5368     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5369                                   N0.getValueType().getScalarType());
5370   }
5371
5372   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5373   // if either of the casts is not free.
5374   if (N0.getOpcode() == ISD::AND &&
5375       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5376       N0.getOperand(1).getOpcode() == ISD::Constant &&
5377       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5378                            N0.getValueType()) ||
5379        !TLI.isZExtFree(N0.getValueType(), VT))) {
5380     SDValue X = N0.getOperand(0).getOperand(0);
5381     if (X.getValueType().bitsLT(VT)) {
5382       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5383     } else if (X.getValueType().bitsGT(VT)) {
5384       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5385     }
5386     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5387     Mask = Mask.zext(VT.getSizeInBits());
5388     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5389                        X, DAG.getConstant(Mask, VT));
5390   }
5391
5392   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5393   // None of the supported targets knows how to perform load and vector_zext
5394   // on vectors in one instruction.  We only perform this transformation on
5395   // scalars.
5396   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5397       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5398       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5399        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5400     bool DoXform = true;
5401     SmallVector<SDNode*, 4> SetCCs;
5402     if (!N0.hasOneUse())
5403       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5404     if (DoXform) {
5405       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5406       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5407                                        LN0->getChain(),
5408                                        LN0->getBasePtr(), N0.getValueType(),
5409                                        LN0->getMemOperand());
5410       CombineTo(N, ExtLoad);
5411       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5412                                   N0.getValueType(), ExtLoad);
5413       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5414
5415       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5416                       ISD::ZERO_EXTEND);
5417       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5418     }
5419   }
5420
5421   // fold (zext (and/or/xor (load x), cst)) ->
5422   //      (and/or/xor (zextload x), (zext cst))
5423   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5424        N0.getOpcode() == ISD::XOR) &&
5425       isa<LoadSDNode>(N0.getOperand(0)) &&
5426       N0.getOperand(1).getOpcode() == ISD::Constant &&
5427       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5428       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5429     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5430     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5431       bool DoXform = true;
5432       SmallVector<SDNode*, 4> SetCCs;
5433       if (!N0.hasOneUse())
5434         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5435                                           SetCCs, TLI);
5436       if (DoXform) {
5437         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5438                                          LN0->getChain(), LN0->getBasePtr(),
5439                                          LN0->getMemoryVT(),
5440                                          LN0->getMemOperand());
5441         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5442         Mask = Mask.zext(VT.getSizeInBits());
5443         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5444                                   ExtLoad, DAG.getConstant(Mask, VT));
5445         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5446                                     SDLoc(N0.getOperand(0)),
5447                                     N0.getOperand(0).getValueType(), ExtLoad);
5448         CombineTo(N, And);
5449         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5450         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5451                         ISD::ZERO_EXTEND);
5452         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5453       }
5454     }
5455   }
5456
5457   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5458   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5459   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5460       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5461     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5462     EVT MemVT = LN0->getMemoryVT();
5463     if ((!LegalOperations && !LN0->isVolatile()) ||
5464         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5465       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5466                                        LN0->getChain(),
5467                                        LN0->getBasePtr(), MemVT,
5468                                        LN0->getMemOperand());
5469       CombineTo(N, ExtLoad);
5470       CombineTo(N0.getNode(),
5471                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5472                             ExtLoad),
5473                 ExtLoad.getValue(1));
5474       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5475     }
5476   }
5477
5478   if (N0.getOpcode() == ISD::SETCC) {
5479     if (!LegalOperations && VT.isVector() &&
5480         N0.getValueType().getVectorElementType() == MVT::i1) {
5481       EVT N0VT = N0.getOperand(0).getValueType();
5482       if (getSetCCResultType(N0VT) == N0.getValueType())
5483         return SDValue();
5484
5485       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5486       // Only do this before legalize for now.
5487       EVT EltVT = VT.getVectorElementType();
5488       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5489                                     DAG.getConstant(1, EltVT));
5490       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5491         // We know that the # elements of the results is the same as the
5492         // # elements of the compare (and the # elements of the compare result
5493         // for that matter).  Check to see that they are the same size.  If so,
5494         // we know that the element size of the sext'd result matches the
5495         // element size of the compare operands.
5496         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5497                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5498                                          N0.getOperand(1),
5499                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5500                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5501                                        OneOps));
5502
5503       // If the desired elements are smaller or larger than the source
5504       // elements we can use a matching integer vector type and then
5505       // truncate/sign extend
5506       EVT MatchingElementType =
5507         EVT::getIntegerVT(*DAG.getContext(),
5508                           N0VT.getScalarType().getSizeInBits());
5509       EVT MatchingVectorType =
5510         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5511                          N0VT.getVectorNumElements());
5512       SDValue VsetCC =
5513         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5514                       N0.getOperand(1),
5515                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5516       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5517                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5518                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5519     }
5520
5521     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5522     SDValue SCC =
5523       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5524                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5525                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5526     if (SCC.getNode()) return SCC;
5527   }
5528
5529   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5530   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5531       isa<ConstantSDNode>(N0.getOperand(1)) &&
5532       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5533       N0.hasOneUse()) {
5534     SDValue ShAmt = N0.getOperand(1);
5535     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5536     if (N0.getOpcode() == ISD::SHL) {
5537       SDValue InnerZExt = N0.getOperand(0);
5538       // If the original shl may be shifting out bits, do not perform this
5539       // transformation.
5540       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5541         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5542       if (ShAmtVal > KnownZeroBits)
5543         return SDValue();
5544     }
5545
5546     SDLoc DL(N);
5547
5548     // Ensure that the shift amount is wide enough for the shifted value.
5549     if (VT.getSizeInBits() >= 256)
5550       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5551
5552     return DAG.getNode(N0.getOpcode(), DL, VT,
5553                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5554                        ShAmt);
5555   }
5556
5557   return SDValue();
5558 }
5559
5560 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5561   SDValue N0 = N->getOperand(0);
5562   EVT VT = N->getValueType(0);
5563
5564   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5565                                               LegalOperations))
5566     return SDValue(Res, 0);
5567
5568   // fold (aext (aext x)) -> (aext x)
5569   // fold (aext (zext x)) -> (zext x)
5570   // fold (aext (sext x)) -> (sext x)
5571   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5572       N0.getOpcode() == ISD::ZERO_EXTEND ||
5573       N0.getOpcode() == ISD::SIGN_EXTEND)
5574     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5575
5576   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5577   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5578   if (N0.getOpcode() == ISD::TRUNCATE) {
5579     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5580     if (NarrowLoad.getNode()) {
5581       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5582       if (NarrowLoad.getNode() != N0.getNode()) {
5583         CombineTo(N0.getNode(), NarrowLoad);
5584         // CombineTo deleted the truncate, if needed, but not what's under it.
5585         AddToWorklist(oye);
5586       }
5587       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5588     }
5589   }
5590
5591   // fold (aext (truncate x))
5592   if (N0.getOpcode() == ISD::TRUNCATE) {
5593     SDValue TruncOp = N0.getOperand(0);
5594     if (TruncOp.getValueType() == VT)
5595       return TruncOp; // x iff x size == zext size.
5596     if (TruncOp.getValueType().bitsGT(VT))
5597       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5598     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5599   }
5600
5601   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5602   // if the trunc is not free.
5603   if (N0.getOpcode() == ISD::AND &&
5604       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5605       N0.getOperand(1).getOpcode() == ISD::Constant &&
5606       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5607                           N0.getValueType())) {
5608     SDValue X = N0.getOperand(0).getOperand(0);
5609     if (X.getValueType().bitsLT(VT)) {
5610       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5611     } else if (X.getValueType().bitsGT(VT)) {
5612       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5613     }
5614     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5615     Mask = Mask.zext(VT.getSizeInBits());
5616     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5617                        X, DAG.getConstant(Mask, VT));
5618   }
5619
5620   // fold (aext (load x)) -> (aext (truncate (extload x)))
5621   // None of the supported targets knows how to perform load and any_ext
5622   // on vectors in one instruction.  We only perform this transformation on
5623   // scalars.
5624   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5625       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5626       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5627     bool DoXform = true;
5628     SmallVector<SDNode*, 4> SetCCs;
5629     if (!N0.hasOneUse())
5630       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5631     if (DoXform) {
5632       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5633       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5634                                        LN0->getChain(),
5635                                        LN0->getBasePtr(), N0.getValueType(),
5636                                        LN0->getMemOperand());
5637       CombineTo(N, ExtLoad);
5638       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5639                                   N0.getValueType(), ExtLoad);
5640       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5641       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5642                       ISD::ANY_EXTEND);
5643       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5644     }
5645   }
5646
5647   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5648   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5649   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5650   if (N0.getOpcode() == ISD::LOAD &&
5651       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5652       N0.hasOneUse()) {
5653     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5654     ISD::LoadExtType ExtType = LN0->getExtensionType();
5655     EVT MemVT = LN0->getMemoryVT();
5656     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5657       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5658                                        VT, LN0->getChain(), LN0->getBasePtr(),
5659                                        MemVT, LN0->getMemOperand());
5660       CombineTo(N, ExtLoad);
5661       CombineTo(N0.getNode(),
5662                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5663                             N0.getValueType(), ExtLoad),
5664                 ExtLoad.getValue(1));
5665       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5666     }
5667   }
5668
5669   if (N0.getOpcode() == ISD::SETCC) {
5670     // For vectors:
5671     // aext(setcc) -> vsetcc
5672     // aext(setcc) -> truncate(vsetcc)
5673     // aext(setcc) -> aext(vsetcc)
5674     // Only do this before legalize for now.
5675     if (VT.isVector() && !LegalOperations) {
5676       EVT N0VT = N0.getOperand(0).getValueType();
5677         // We know that the # elements of the results is the same as the
5678         // # elements of the compare (and the # elements of the compare result
5679         // for that matter).  Check to see that they are the same size.  If so,
5680         // we know that the element size of the sext'd result matches the
5681         // element size of the compare operands.
5682       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5683         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5684                              N0.getOperand(1),
5685                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5686       // If the desired elements are smaller or larger than the source
5687       // elements we can use a matching integer vector type and then
5688       // truncate/any extend
5689       else {
5690         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5691         SDValue VsetCC =
5692           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5693                         N0.getOperand(1),
5694                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5695         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5696       }
5697     }
5698
5699     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5700     SDValue SCC =
5701       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5702                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5703                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5704     if (SCC.getNode())
5705       return SCC;
5706   }
5707
5708   return SDValue();
5709 }
5710
5711 /// See if the specified operand can be simplified with the knowledge that only
5712 /// the bits specified by Mask are used.  If so, return the simpler operand,
5713 /// otherwise return a null SDValue.
5714 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5715   switch (V.getOpcode()) {
5716   default: break;
5717   case ISD::Constant: {
5718     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5719     assert(CV && "Const value should be ConstSDNode.");
5720     const APInt &CVal = CV->getAPIntValue();
5721     APInt NewVal = CVal & Mask;
5722     if (NewVal != CVal)
5723       return DAG.getConstant(NewVal, V.getValueType());
5724     break;
5725   }
5726   case ISD::OR:
5727   case ISD::XOR:
5728     // If the LHS or RHS don't contribute bits to the or, drop them.
5729     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5730       return V.getOperand(1);
5731     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5732       return V.getOperand(0);
5733     break;
5734   case ISD::SRL:
5735     // Only look at single-use SRLs.
5736     if (!V.getNode()->hasOneUse())
5737       break;
5738     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5739       // See if we can recursively simplify the LHS.
5740       unsigned Amt = RHSC->getZExtValue();
5741
5742       // Watch out for shift count overflow though.
5743       if (Amt >= Mask.getBitWidth()) break;
5744       APInt NewMask = Mask << Amt;
5745       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5746       if (SimplifyLHS.getNode())
5747         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5748                            SimplifyLHS, V.getOperand(1));
5749     }
5750   }
5751   return SDValue();
5752 }
5753
5754 /// If the result of a wider load is shifted to right of N  bits and then
5755 /// truncated to a narrower type and where N is a multiple of number of bits of
5756 /// the narrower type, transform it to a narrower load from address + N / num of
5757 /// bits of new type. If the result is to be extended, also fold the extension
5758 /// to form a extending load.
5759 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5760   unsigned Opc = N->getOpcode();
5761
5762   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5763   SDValue N0 = N->getOperand(0);
5764   EVT VT = N->getValueType(0);
5765   EVT ExtVT = VT;
5766
5767   // This transformation isn't valid for vector loads.
5768   if (VT.isVector())
5769     return SDValue();
5770
5771   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5772   // extended to VT.
5773   if (Opc == ISD::SIGN_EXTEND_INREG) {
5774     ExtType = ISD::SEXTLOAD;
5775     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5776   } else if (Opc == ISD::SRL) {
5777     // Another special-case: SRL is basically zero-extending a narrower value.
5778     ExtType = ISD::ZEXTLOAD;
5779     N0 = SDValue(N, 0);
5780     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5781     if (!N01) return SDValue();
5782     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5783                               VT.getSizeInBits() - N01->getZExtValue());
5784   }
5785   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5786     return SDValue();
5787
5788   unsigned EVTBits = ExtVT.getSizeInBits();
5789
5790   // Do not generate loads of non-round integer types since these can
5791   // be expensive (and would be wrong if the type is not byte sized).
5792   if (!ExtVT.isRound())
5793     return SDValue();
5794
5795   unsigned ShAmt = 0;
5796   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5797     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5798       ShAmt = N01->getZExtValue();
5799       // Is the shift amount a multiple of size of VT?
5800       if ((ShAmt & (EVTBits-1)) == 0) {
5801         N0 = N0.getOperand(0);
5802         // Is the load width a multiple of size of VT?
5803         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5804           return SDValue();
5805       }
5806
5807       // At this point, we must have a load or else we can't do the transform.
5808       if (!isa<LoadSDNode>(N0)) return SDValue();
5809
5810       // Because a SRL must be assumed to *need* to zero-extend the high bits
5811       // (as opposed to anyext the high bits), we can't combine the zextload
5812       // lowering of SRL and an sextload.
5813       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5814         return SDValue();
5815
5816       // If the shift amount is larger than the input type then we're not
5817       // accessing any of the loaded bytes.  If the load was a zextload/extload
5818       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5819       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5820         return SDValue();
5821     }
5822   }
5823
5824   // If the load is shifted left (and the result isn't shifted back right),
5825   // we can fold the truncate through the shift.
5826   unsigned ShLeftAmt = 0;
5827   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5828       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5829     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5830       ShLeftAmt = N01->getZExtValue();
5831       N0 = N0.getOperand(0);
5832     }
5833   }
5834
5835   // If we haven't found a load, we can't narrow it.  Don't transform one with
5836   // multiple uses, this would require adding a new load.
5837   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5838     return SDValue();
5839
5840   // Don't change the width of a volatile load.
5841   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5842   if (LN0->isVolatile())
5843     return SDValue();
5844
5845   // Verify that we are actually reducing a load width here.
5846   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5847     return SDValue();
5848
5849   // For the transform to be legal, the load must produce only two values
5850   // (the value loaded and the chain).  Don't transform a pre-increment
5851   // load, for example, which produces an extra value.  Otherwise the
5852   // transformation is not equivalent, and the downstream logic to replace
5853   // uses gets things wrong.
5854   if (LN0->getNumValues() > 2)
5855     return SDValue();
5856
5857   // If the load that we're shrinking is an extload and we're not just
5858   // discarding the extension we can't simply shrink the load. Bail.
5859   // TODO: It would be possible to merge the extensions in some cases.
5860   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5861       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5862     return SDValue();
5863
5864   EVT PtrType = N0.getOperand(1).getValueType();
5865
5866   if (PtrType == MVT::Untyped || PtrType.isExtended())
5867     // It's not possible to generate a constant of extended or untyped type.
5868     return SDValue();
5869
5870   // For big endian targets, we need to adjust the offset to the pointer to
5871   // load the correct bytes.
5872   if (TLI.isBigEndian()) {
5873     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5874     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5875     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5876   }
5877
5878   uint64_t PtrOff = ShAmt / 8;
5879   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5880   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5881                                PtrType, LN0->getBasePtr(),
5882                                DAG.getConstant(PtrOff, PtrType));
5883   AddToWorklist(NewPtr.getNode());
5884
5885   SDValue Load;
5886   if (ExtType == ISD::NON_EXTLOAD)
5887     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5888                         LN0->getPointerInfo().getWithOffset(PtrOff),
5889                         LN0->isVolatile(), LN0->isNonTemporal(),
5890                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5891   else
5892     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5893                           LN0->getPointerInfo().getWithOffset(PtrOff),
5894                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5895                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5896
5897   // Replace the old load's chain with the new load's chain.
5898   WorklistRemover DeadNodes(*this);
5899   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5900
5901   // Shift the result left, if we've swallowed a left shift.
5902   SDValue Result = Load;
5903   if (ShLeftAmt != 0) {
5904     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5905     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5906       ShImmTy = VT;
5907     // If the shift amount is as large as the result size (but, presumably,
5908     // no larger than the source) then the useful bits of the result are
5909     // zero; we can't simply return the shortened shift, because the result
5910     // of that operation is undefined.
5911     if (ShLeftAmt >= VT.getSizeInBits())
5912       Result = DAG.getConstant(0, VT);
5913     else
5914       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5915                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5916   }
5917
5918   // Return the new loaded value.
5919   return Result;
5920 }
5921
5922 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5923   SDValue N0 = N->getOperand(0);
5924   SDValue N1 = N->getOperand(1);
5925   EVT VT = N->getValueType(0);
5926   EVT EVT = cast<VTSDNode>(N1)->getVT();
5927   unsigned VTBits = VT.getScalarType().getSizeInBits();
5928   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5929
5930   // fold (sext_in_reg c1) -> c1
5931   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5932     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5933
5934   // If the input is already sign extended, just drop the extension.
5935   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5936     return N0;
5937
5938   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5939   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5940       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5941     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5942                        N0.getOperand(0), N1);
5943
5944   // fold (sext_in_reg (sext x)) -> (sext x)
5945   // fold (sext_in_reg (aext x)) -> (sext x)
5946   // if x is small enough.
5947   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5948     SDValue N00 = N0.getOperand(0);
5949     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5950         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5951       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5952   }
5953
5954   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5955   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5956     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5957
5958   // fold operands of sext_in_reg based on knowledge that the top bits are not
5959   // demanded.
5960   if (SimplifyDemandedBits(SDValue(N, 0)))
5961     return SDValue(N, 0);
5962
5963   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5964   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5965   SDValue NarrowLoad = ReduceLoadWidth(N);
5966   if (NarrowLoad.getNode())
5967     return NarrowLoad;
5968
5969   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5970   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5971   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5972   if (N0.getOpcode() == ISD::SRL) {
5973     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5974       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5975         // We can turn this into an SRA iff the input to the SRL is already sign
5976         // extended enough.
5977         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5978         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5979           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5980                              N0.getOperand(0), N0.getOperand(1));
5981       }
5982   }
5983
5984   // fold (sext_inreg (extload x)) -> (sextload x)
5985   if (ISD::isEXTLoad(N0.getNode()) &&
5986       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5987       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5988       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5989        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5990     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5991     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5992                                      LN0->getChain(),
5993                                      LN0->getBasePtr(), EVT,
5994                                      LN0->getMemOperand());
5995     CombineTo(N, ExtLoad);
5996     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5997     AddToWorklist(ExtLoad.getNode());
5998     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5999   }
6000   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6001   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6002       N0.hasOneUse() &&
6003       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6004       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6005        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6006     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6007     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6008                                      LN0->getChain(),
6009                                      LN0->getBasePtr(), EVT,
6010                                      LN0->getMemOperand());
6011     CombineTo(N, ExtLoad);
6012     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6013     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6014   }
6015
6016   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6017   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6018     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6019                                        N0.getOperand(1), false);
6020     if (BSwap.getNode())
6021       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6022                          BSwap, N1);
6023   }
6024
6025   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6026   // into a build_vector.
6027   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6028     SmallVector<SDValue, 8> Elts;
6029     unsigned NumElts = N0->getNumOperands();
6030     unsigned ShAmt = VTBits - EVTBits;
6031
6032     for (unsigned i = 0; i != NumElts; ++i) {
6033       SDValue Op = N0->getOperand(i);
6034       if (Op->getOpcode() == ISD::UNDEF) {
6035         Elts.push_back(Op);
6036         continue;
6037       }
6038
6039       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6040       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6041       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6042                                      Op.getValueType()));
6043     }
6044
6045     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6046   }
6047
6048   return SDValue();
6049 }
6050
6051 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6052   SDValue N0 = N->getOperand(0);
6053   EVT VT = N->getValueType(0);
6054   bool isLE = TLI.isLittleEndian();
6055
6056   // noop truncate
6057   if (N0.getValueType() == N->getValueType(0))
6058     return N0;
6059   // fold (truncate c1) -> c1
6060   if (isa<ConstantSDNode>(N0))
6061     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6062   // fold (truncate (truncate x)) -> (truncate x)
6063   if (N0.getOpcode() == ISD::TRUNCATE)
6064     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6065   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6066   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6067       N0.getOpcode() == ISD::SIGN_EXTEND ||
6068       N0.getOpcode() == ISD::ANY_EXTEND) {
6069     if (N0.getOperand(0).getValueType().bitsLT(VT))
6070       // if the source is smaller than the dest, we still need an extend
6071       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6072                          N0.getOperand(0));
6073     if (N0.getOperand(0).getValueType().bitsGT(VT))
6074       // if the source is larger than the dest, than we just need the truncate
6075       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6076     // if the source and dest are the same type, we can drop both the extend
6077     // and the truncate.
6078     return N0.getOperand(0);
6079   }
6080
6081   // Fold extract-and-trunc into a narrow extract. For example:
6082   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6083   //   i32 y = TRUNCATE(i64 x)
6084   //        -- becomes --
6085   //   v16i8 b = BITCAST (v2i64 val)
6086   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6087   //
6088   // Note: We only run this optimization after type legalization (which often
6089   // creates this pattern) and before operation legalization after which
6090   // we need to be more careful about the vector instructions that we generate.
6091   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6092       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6093
6094     EVT VecTy = N0.getOperand(0).getValueType();
6095     EVT ExTy = N0.getValueType();
6096     EVT TrTy = N->getValueType(0);
6097
6098     unsigned NumElem = VecTy.getVectorNumElements();
6099     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6100
6101     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6102     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6103
6104     SDValue EltNo = N0->getOperand(1);
6105     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6106       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6107       EVT IndexTy = TLI.getVectorIdxTy();
6108       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6109
6110       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6111                               NVT, N0.getOperand(0));
6112
6113       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6114                          SDLoc(N), TrTy, V,
6115                          DAG.getConstant(Index, IndexTy));
6116     }
6117   }
6118
6119   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6120   if (N0.getOpcode() == ISD::SELECT) {
6121     EVT SrcVT = N0.getValueType();
6122     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6123         TLI.isTruncateFree(SrcVT, VT)) {
6124       SDLoc SL(N0);
6125       SDValue Cond = N0.getOperand(0);
6126       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6127       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6128       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6129     }
6130   }
6131
6132   // Fold a series of buildvector, bitcast, and truncate if possible.
6133   // For example fold
6134   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6135   //   (2xi32 (buildvector x, y)).
6136   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6137       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6138       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6139       N0.getOperand(0).hasOneUse()) {
6140
6141     SDValue BuildVect = N0.getOperand(0);
6142     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6143     EVT TruncVecEltTy = VT.getVectorElementType();
6144
6145     // Check that the element types match.
6146     if (BuildVectEltTy == TruncVecEltTy) {
6147       // Now we only need to compute the offset of the truncated elements.
6148       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6149       unsigned TruncVecNumElts = VT.getVectorNumElements();
6150       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6151
6152       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6153              "Invalid number of elements");
6154
6155       SmallVector<SDValue, 8> Opnds;
6156       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6157         Opnds.push_back(BuildVect.getOperand(i));
6158
6159       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6160     }
6161   }
6162
6163   // See if we can simplify the input to this truncate through knowledge that
6164   // only the low bits are being used.
6165   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6166   // Currently we only perform this optimization on scalars because vectors
6167   // may have different active low bits.
6168   if (!VT.isVector()) {
6169     SDValue Shorter =
6170       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6171                                                VT.getSizeInBits()));
6172     if (Shorter.getNode())
6173       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6174   }
6175   // fold (truncate (load x)) -> (smaller load x)
6176   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6177   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6178     SDValue Reduced = ReduceLoadWidth(N);
6179     if (Reduced.getNode())
6180       return Reduced;
6181     // Handle the case where the load remains an extending load even
6182     // after truncation.
6183     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6184       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6185       if (!LN0->isVolatile() &&
6186           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6187         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6188                                          VT, LN0->getChain(), LN0->getBasePtr(),
6189                                          LN0->getMemoryVT(),
6190                                          LN0->getMemOperand());
6191         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6192         return NewLoad;
6193       }
6194     }
6195   }
6196   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6197   // where ... are all 'undef'.
6198   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6199     SmallVector<EVT, 8> VTs;
6200     SDValue V;
6201     unsigned Idx = 0;
6202     unsigned NumDefs = 0;
6203
6204     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6205       SDValue X = N0.getOperand(i);
6206       if (X.getOpcode() != ISD::UNDEF) {
6207         V = X;
6208         Idx = i;
6209         NumDefs++;
6210       }
6211       // Stop if more than one members are non-undef.
6212       if (NumDefs > 1)
6213         break;
6214       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6215                                      VT.getVectorElementType(),
6216                                      X.getValueType().getVectorNumElements()));
6217     }
6218
6219     if (NumDefs == 0)
6220       return DAG.getUNDEF(VT);
6221
6222     if (NumDefs == 1) {
6223       assert(V.getNode() && "The single defined operand is empty!");
6224       SmallVector<SDValue, 8> Opnds;
6225       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6226         if (i != Idx) {
6227           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6228           continue;
6229         }
6230         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6231         AddToWorklist(NV.getNode());
6232         Opnds.push_back(NV);
6233       }
6234       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6235     }
6236   }
6237
6238   // Simplify the operands using demanded-bits information.
6239   if (!VT.isVector() &&
6240       SimplifyDemandedBits(SDValue(N, 0)))
6241     return SDValue(N, 0);
6242
6243   return SDValue();
6244 }
6245
6246 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6247   SDValue Elt = N->getOperand(i);
6248   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6249     return Elt.getNode();
6250   return Elt.getOperand(Elt.getResNo()).getNode();
6251 }
6252
6253 /// build_pair (load, load) -> load
6254 /// if load locations are consecutive.
6255 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6256   assert(N->getOpcode() == ISD::BUILD_PAIR);
6257
6258   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6259   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6260   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6261       LD1->getAddressSpace() != LD2->getAddressSpace())
6262     return SDValue();
6263   EVT LD1VT = LD1->getValueType(0);
6264
6265   if (ISD::isNON_EXTLoad(LD2) &&
6266       LD2->hasOneUse() &&
6267       // If both are volatile this would reduce the number of volatile loads.
6268       // If one is volatile it might be ok, but play conservative and bail out.
6269       !LD1->isVolatile() &&
6270       !LD2->isVolatile() &&
6271       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6272     unsigned Align = LD1->getAlignment();
6273     unsigned NewAlign = TLI.getDataLayout()->
6274       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6275
6276     if (NewAlign <= Align &&
6277         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6278       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6279                          LD1->getBasePtr(), LD1->getPointerInfo(),
6280                          false, false, false, Align);
6281   }
6282
6283   return SDValue();
6284 }
6285
6286 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6287   SDValue N0 = N->getOperand(0);
6288   EVT VT = N->getValueType(0);
6289
6290   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6291   // Only do this before legalize, since afterward the target may be depending
6292   // on the bitconvert.
6293   // First check to see if this is all constant.
6294   if (!LegalTypes &&
6295       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6296       VT.isVector()) {
6297     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6298
6299     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6300     assert(!DestEltVT.isVector() &&
6301            "Element type of vector ValueType must not be vector!");
6302     if (isSimple)
6303       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6304   }
6305
6306   // If the input is a constant, let getNode fold it.
6307   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6308     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6309     if (Res.getNode() != N) {
6310       if (!LegalOperations ||
6311           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6312         return Res;
6313
6314       // Folding it resulted in an illegal node, and it's too late to
6315       // do that. Clean up the old node and forego the transformation.
6316       // Ideally this won't happen very often, because instcombine
6317       // and the earlier dagcombine runs (where illegal nodes are
6318       // permitted) should have folded most of them already.
6319       deleteAndRecombine(Res.getNode());
6320     }
6321   }
6322
6323   // (conv (conv x, t1), t2) -> (conv x, t2)
6324   if (N0.getOpcode() == ISD::BITCAST)
6325     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6326                        N0.getOperand(0));
6327
6328   // fold (conv (load x)) -> (load (conv*)x)
6329   // If the resultant load doesn't need a higher alignment than the original!
6330   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6331       // Do not change the width of a volatile load.
6332       !cast<LoadSDNode>(N0)->isVolatile() &&
6333       // Do not remove the cast if the types differ in endian layout.
6334       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6335       TLI.hasBigEndianPartOrdering(VT) &&
6336       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6337       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6338     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6339     unsigned Align = TLI.getDataLayout()->
6340       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6341     unsigned OrigAlign = LN0->getAlignment();
6342
6343     if (Align <= OrigAlign) {
6344       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6345                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6346                                  LN0->isVolatile(), LN0->isNonTemporal(),
6347                                  LN0->isInvariant(), OrigAlign,
6348                                  LN0->getAAInfo());
6349       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6350       return Load;
6351     }
6352   }
6353
6354   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6355   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6356   // This often reduces constant pool loads.
6357   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6358        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6359       N0.getNode()->hasOneUse() && VT.isInteger() &&
6360       !VT.isVector() && !N0.getValueType().isVector()) {
6361     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6362                                   N0.getOperand(0));
6363     AddToWorklist(NewConv.getNode());
6364
6365     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6366     if (N0.getOpcode() == ISD::FNEG)
6367       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6368                          NewConv, DAG.getConstant(SignBit, VT));
6369     assert(N0.getOpcode() == ISD::FABS);
6370     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6371                        NewConv, DAG.getConstant(~SignBit, VT));
6372   }
6373
6374   // fold (bitconvert (fcopysign cst, x)) ->
6375   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6376   // Note that we don't handle (copysign x, cst) because this can always be
6377   // folded to an fneg or fabs.
6378   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6379       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6380       VT.isInteger() && !VT.isVector()) {
6381     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6382     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6383     if (isTypeLegal(IntXVT)) {
6384       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6385                               IntXVT, N0.getOperand(1));
6386       AddToWorklist(X.getNode());
6387
6388       // If X has a different width than the result/lhs, sext it or truncate it.
6389       unsigned VTWidth = VT.getSizeInBits();
6390       if (OrigXWidth < VTWidth) {
6391         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6392         AddToWorklist(X.getNode());
6393       } else if (OrigXWidth > VTWidth) {
6394         // To get the sign bit in the right place, we have to shift it right
6395         // before truncating.
6396         X = DAG.getNode(ISD::SRL, SDLoc(X),
6397                         X.getValueType(), X,
6398                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6399         AddToWorklist(X.getNode());
6400         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6401         AddToWorklist(X.getNode());
6402       }
6403
6404       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6405       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6406                       X, DAG.getConstant(SignBit, VT));
6407       AddToWorklist(X.getNode());
6408
6409       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6410                                 VT, N0.getOperand(0));
6411       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6412                         Cst, DAG.getConstant(~SignBit, VT));
6413       AddToWorklist(Cst.getNode());
6414
6415       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6416     }
6417   }
6418
6419   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6420   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6421     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6422     if (CombineLD.getNode())
6423       return CombineLD;
6424   }
6425
6426   return SDValue();
6427 }
6428
6429 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6430   EVT VT = N->getValueType(0);
6431   return CombineConsecutiveLoads(N, VT);
6432 }
6433
6434 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6435 /// operands. DstEltVT indicates the destination element value type.
6436 SDValue DAGCombiner::
6437 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6438   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6439
6440   // If this is already the right type, we're done.
6441   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6442
6443   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6444   unsigned DstBitSize = DstEltVT.getSizeInBits();
6445
6446   // If this is a conversion of N elements of one type to N elements of another
6447   // type, convert each element.  This handles FP<->INT cases.
6448   if (SrcBitSize == DstBitSize) {
6449     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6450                               BV->getValueType(0).getVectorNumElements());
6451
6452     // Due to the FP element handling below calling this routine recursively,
6453     // we can end up with a scalar-to-vector node here.
6454     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6455       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6456                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6457                                      DstEltVT, BV->getOperand(0)));
6458
6459     SmallVector<SDValue, 8> Ops;
6460     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6461       SDValue Op = BV->getOperand(i);
6462       // If the vector element type is not legal, the BUILD_VECTOR operands
6463       // are promoted and implicitly truncated.  Make that explicit here.
6464       if (Op.getValueType() != SrcEltVT)
6465         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6466       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6467                                 DstEltVT, Op));
6468       AddToWorklist(Ops.back().getNode());
6469     }
6470     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6471   }
6472
6473   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6474   // handle annoying details of growing/shrinking FP values, we convert them to
6475   // int first.
6476   if (SrcEltVT.isFloatingPoint()) {
6477     // Convert the input float vector to a int vector where the elements are the
6478     // same sizes.
6479     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6480     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6481     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6482     SrcEltVT = IntVT;
6483   }
6484
6485   // Now we know the input is an integer vector.  If the output is a FP type,
6486   // convert to integer first, then to FP of the right size.
6487   if (DstEltVT.isFloatingPoint()) {
6488     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6489     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6490     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6491
6492     // Next, convert to FP elements of the same size.
6493     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6494   }
6495
6496   // Okay, we know the src/dst types are both integers of differing types.
6497   // Handling growing first.
6498   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6499   if (SrcBitSize < DstBitSize) {
6500     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6501
6502     SmallVector<SDValue, 8> Ops;
6503     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6504          i += NumInputsPerOutput) {
6505       bool isLE = TLI.isLittleEndian();
6506       APInt NewBits = APInt(DstBitSize, 0);
6507       bool EltIsUndef = true;
6508       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6509         // Shift the previously computed bits over.
6510         NewBits <<= SrcBitSize;
6511         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6512         if (Op.getOpcode() == ISD::UNDEF) continue;
6513         EltIsUndef = false;
6514
6515         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6516                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6517       }
6518
6519       if (EltIsUndef)
6520         Ops.push_back(DAG.getUNDEF(DstEltVT));
6521       else
6522         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6523     }
6524
6525     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6526     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6527   }
6528
6529   // Finally, this must be the case where we are shrinking elements: each input
6530   // turns into multiple outputs.
6531   bool isS2V = ISD::isScalarToVector(BV);
6532   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6533   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6534                             NumOutputsPerInput*BV->getNumOperands());
6535   SmallVector<SDValue, 8> Ops;
6536
6537   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6538     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6539       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6540         Ops.push_back(DAG.getUNDEF(DstEltVT));
6541       continue;
6542     }
6543
6544     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6545                   getAPIntValue().zextOrTrunc(SrcBitSize);
6546
6547     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6548       APInt ThisVal = OpVal.trunc(DstBitSize);
6549       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6550       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6551         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6552         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6553                            Ops[0]);
6554       OpVal = OpVal.lshr(DstBitSize);
6555     }
6556
6557     // For big endian targets, swap the order of the pieces of each element.
6558     if (TLI.isBigEndian())
6559       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6560   }
6561
6562   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6563 }
6564
6565 SDValue DAGCombiner::visitFADD(SDNode *N) {
6566   SDValue N0 = N->getOperand(0);
6567   SDValue N1 = N->getOperand(1);
6568   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6569   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6570   EVT VT = N->getValueType(0);
6571   const TargetOptions &Options = DAG.getTarget().Options;
6572   
6573   // fold vector ops
6574   if (VT.isVector()) {
6575     SDValue FoldedVOp = SimplifyVBinOp(N);
6576     if (FoldedVOp.getNode()) return FoldedVOp;
6577   }
6578
6579   // fold (fadd c1, c2) -> c1 + c2
6580   if (N0CFP && N1CFP)
6581     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6582
6583   // canonicalize constant to RHS
6584   if (N0CFP && !N1CFP)
6585     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6586
6587   // fold (fadd A, (fneg B)) -> (fsub A, B)
6588   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6589       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6590     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6591                        GetNegatedExpression(N1, DAG, LegalOperations));
6592   
6593   // fold (fadd (fneg A), B) -> (fsub B, A)
6594   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6595       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6596     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6597                        GetNegatedExpression(N0, DAG, LegalOperations));
6598
6599   // If 'unsafe math' is enabled, fold lots of things.
6600   if (Options.UnsafeFPMath) {
6601     // No FP constant should be created after legalization as Instruction
6602     // Selection pass has a hard time dealing with FP constants.
6603     bool AllowNewConst = (Level < AfterLegalizeDAG);
6604     
6605     // fold (fadd A, 0) -> A
6606     if (N1CFP && N1CFP->getValueAPF().isZero())
6607       return N0;
6608
6609     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6610     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6611         isa<ConstantFPSDNode>(N0.getOperand(1)))
6612       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6613                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6614                                      N0.getOperand(1), N1));
6615     
6616     // If allowed, fold (fadd (fneg x), x) -> 0.0
6617     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6618       return DAG.getConstantFP(0.0, VT);
6619     
6620     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6621     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6622       return DAG.getConstantFP(0.0, VT);
6623     
6624     // We can fold chains of FADD's of the same value into multiplications.
6625     // This transform is not safe in general because we are reducing the number
6626     // of rounding steps.
6627     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6628       if (N0.getOpcode() == ISD::FMUL) {
6629         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6630         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6631         
6632         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6633         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6634           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6635                                        SDValue(CFP01, 0),
6636                                        DAG.getConstantFP(1.0, VT));
6637           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6638         }
6639         
6640         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6641         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6642             N1.getOperand(0) == N1.getOperand(1) &&
6643             N0.getOperand(0) == N1.getOperand(0)) {
6644           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645                                        SDValue(CFP01, 0),
6646                                        DAG.getConstantFP(2.0, VT));
6647           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6648                              N0.getOperand(0), NewCFP);
6649         }
6650       }
6651       
6652       if (N1.getOpcode() == ISD::FMUL) {
6653         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6654         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6655         
6656         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6657         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6658           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6659                                        SDValue(CFP11, 0),
6660                                        DAG.getConstantFP(1.0, VT));
6661           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6662         }
6663
6664         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6665         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6666             N0.getOperand(0) == N0.getOperand(1) &&
6667             N1.getOperand(0) == N0.getOperand(0)) {
6668           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6669                                        SDValue(CFP11, 0),
6670                                        DAG.getConstantFP(2.0, VT));
6671           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6672         }
6673       }
6674
6675       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6676         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6677         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6678         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6679             (N0.getOperand(0) == N1))
6680           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6681                              N1, DAG.getConstantFP(3.0, VT));
6682       }
6683       
6684       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6685         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6686         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6687         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6688             N1.getOperand(0) == N0)
6689           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6690                              N0, DAG.getConstantFP(3.0, VT));
6691       }
6692       
6693       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6694       if (AllowNewConst &&
6695           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6696           N0.getOperand(0) == N0.getOperand(1) &&
6697           N1.getOperand(0) == N1.getOperand(1) &&
6698           N0.getOperand(0) == N1.getOperand(0))
6699         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6700                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6701     }
6702   } // enable-unsafe-fp-math
6703   
6704   // FADD -> FMA combines:
6705   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6706       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6707       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6708
6709     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6710     if (N0.getOpcode() == ISD::FMUL &&
6711         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6712       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6713                          N0.getOperand(0), N0.getOperand(1), N1);
6714
6715     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6716     // Note: Commutes FADD operands.
6717     if (N1.getOpcode() == ISD::FMUL &&
6718         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6719       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6720                          N1.getOperand(0), N1.getOperand(1), N0);
6721   }
6722
6723   return SDValue();
6724 }
6725
6726 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6727   SDValue N0 = N->getOperand(0);
6728   SDValue N1 = N->getOperand(1);
6729   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6730   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6731   EVT VT = N->getValueType(0);
6732   SDLoc dl(N);
6733   const TargetOptions &Options = DAG.getTarget().Options;
6734
6735   // fold vector ops
6736   if (VT.isVector()) {
6737     SDValue FoldedVOp = SimplifyVBinOp(N);
6738     if (FoldedVOp.getNode()) return FoldedVOp;
6739   }
6740
6741   // fold (fsub c1, c2) -> c1-c2
6742   if (N0CFP && N1CFP)
6743     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6744
6745   // fold (fsub A, (fneg B)) -> (fadd A, B)
6746   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6747     return DAG.getNode(ISD::FADD, dl, VT, N0,
6748                        GetNegatedExpression(N1, DAG, LegalOperations));
6749
6750   // If 'unsafe math' is enabled, fold lots of things.
6751   if (Options.UnsafeFPMath) {
6752     // (fsub A, 0) -> A
6753     if (N1CFP && N1CFP->getValueAPF().isZero())
6754       return N0;
6755
6756     // (fsub 0, B) -> -B
6757     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6758       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6759         return GetNegatedExpression(N1, DAG, LegalOperations);
6760       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6761         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6762     }
6763
6764     // (fsub x, x) -> 0.0
6765     if (N0 == N1)
6766       return DAG.getConstantFP(0.0f, VT);
6767
6768     // (fsub x, (fadd x, y)) -> (fneg y)
6769     // (fsub x, (fadd y, x)) -> (fneg y)
6770     if (N1.getOpcode() == ISD::FADD) {
6771       SDValue N10 = N1->getOperand(0);
6772       SDValue N11 = N1->getOperand(1);
6773
6774       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6775         return GetNegatedExpression(N11, DAG, LegalOperations);
6776
6777       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6778         return GetNegatedExpression(N10, DAG, LegalOperations);
6779     }
6780   }
6781
6782   // FSUB -> FMA combines:
6783   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6784       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6785       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6786
6787     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6788     if (N0.getOpcode() == ISD::FMUL &&
6789         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6790       return DAG.getNode(ISD::FMA, dl, VT,
6791                          N0.getOperand(0), N0.getOperand(1),
6792                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6793
6794     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6795     // Note: Commutes FSUB operands.
6796     if (N1.getOpcode() == ISD::FMUL &&
6797         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6798       return DAG.getNode(ISD::FMA, dl, VT,
6799                          DAG.getNode(ISD::FNEG, dl, VT,
6800                          N1.getOperand(0)),
6801                          N1.getOperand(1), N0);
6802
6803     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6804     if (N0.getOpcode() == ISD::FNEG &&
6805         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6806         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6807             TLI.enableAggressiveFMAFusion(VT))) {
6808       SDValue N00 = N0.getOperand(0).getOperand(0);
6809       SDValue N01 = N0.getOperand(0).getOperand(1);
6810       return DAG.getNode(ISD::FMA, dl, VT,
6811                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6812                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6813     }
6814   }
6815
6816   return SDValue();
6817 }
6818
6819 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6820   SDValue N0 = N->getOperand(0);
6821   SDValue N1 = N->getOperand(1);
6822   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6823   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6824   EVT VT = N->getValueType(0);
6825   const TargetOptions &Options = DAG.getTarget().Options;
6826
6827   // fold vector ops
6828   if (VT.isVector()) {
6829     // This just handles C1 * C2 for vectors. Other vector folds are below.
6830     SDValue FoldedVOp = SimplifyVBinOp(N);
6831     if (FoldedVOp.getNode())
6832       return FoldedVOp;
6833     // Canonicalize vector constant to RHS.
6834     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6835         N1.getOpcode() != ISD::BUILD_VECTOR)
6836       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6837         if (BV0->isConstant())
6838           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6839   }
6840
6841   // fold (fmul c1, c2) -> c1*c2
6842   if (N0CFP && N1CFP)
6843     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6844
6845   // canonicalize constant to RHS
6846   if (N0CFP && !N1CFP)
6847     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6848
6849   // fold (fmul A, 1.0) -> A
6850   if (N1CFP && N1CFP->isExactlyValue(1.0))
6851     return N0;
6852
6853   if (Options.UnsafeFPMath) {
6854     // fold (fmul A, 0) -> 0
6855     if (N1CFP && N1CFP->getValueAPF().isZero())
6856       return N1;
6857
6858     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6859     if (N0.getOpcode() == ISD::FMUL) {
6860       // Fold scalars or any vector constants (not just splats).
6861       // This fold is done in general by InstCombine, but extra fmul insts
6862       // may have been generated during lowering.
6863       SDValue N01 = N0.getOperand(1);
6864       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6865       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6866       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6867           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6868         SDLoc SL(N);
6869         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6870         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6871       }
6872     }
6873
6874     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6875     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6876     // during an early run of DAGCombiner can prevent folding with fmuls
6877     // inserted during lowering.
6878     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6879       SDLoc SL(N);
6880       const SDValue Two = DAG.getConstantFP(2.0, VT);
6881       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6882       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6883     }
6884   }
6885
6886   // fold (fmul X, 2.0) -> (fadd X, X)
6887   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6888     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6889
6890   // fold (fmul X, -1.0) -> (fneg X)
6891   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6892     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6893       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6894
6895   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6896   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6897     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6898       // Both can be negated for free, check to see if at least one is cheaper
6899       // negated.
6900       if (LHSNeg == 2 || RHSNeg == 2)
6901         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6902                            GetNegatedExpression(N0, DAG, LegalOperations),
6903                            GetNegatedExpression(N1, DAG, LegalOperations));
6904     }
6905   }
6906
6907   return SDValue();
6908 }
6909
6910 SDValue DAGCombiner::visitFMA(SDNode *N) {
6911   SDValue N0 = N->getOperand(0);
6912   SDValue N1 = N->getOperand(1);
6913   SDValue N2 = N->getOperand(2);
6914   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6915   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6916   EVT VT = N->getValueType(0);
6917   SDLoc dl(N);
6918   const TargetOptions &Options = DAG.getTarget().Options;
6919
6920   // Constant fold FMA.
6921   if (isa<ConstantFPSDNode>(N0) &&
6922       isa<ConstantFPSDNode>(N1) &&
6923       isa<ConstantFPSDNode>(N2)) {
6924     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6925   }
6926
6927   if (Options.UnsafeFPMath) {
6928     if (N0CFP && N0CFP->isZero())
6929       return N2;
6930     if (N1CFP && N1CFP->isZero())
6931       return N2;
6932   }
6933   if (N0CFP && N0CFP->isExactlyValue(1.0))
6934     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6935   if (N1CFP && N1CFP->isExactlyValue(1.0))
6936     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6937
6938   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6939   if (N0CFP && !N1CFP)
6940     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6941
6942   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6943   if (Options.UnsafeFPMath && N1CFP &&
6944       N2.getOpcode() == ISD::FMUL &&
6945       N0 == N2.getOperand(0) &&
6946       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6947     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6948                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6949   }
6950
6951
6952   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6953   if (Options.UnsafeFPMath &&
6954       N0.getOpcode() == ISD::FMUL && N1CFP &&
6955       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6956     return DAG.getNode(ISD::FMA, dl, VT,
6957                        N0.getOperand(0),
6958                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6959                        N2);
6960   }
6961
6962   // (fma x, 1, y) -> (fadd x, y)
6963   // (fma x, -1, y) -> (fadd (fneg x), y)
6964   if (N1CFP) {
6965     if (N1CFP->isExactlyValue(1.0))
6966       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6967
6968     if (N1CFP->isExactlyValue(-1.0) &&
6969         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6970       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6971       AddToWorklist(RHSNeg.getNode());
6972       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6973     }
6974   }
6975
6976   // (fma x, c, x) -> (fmul x, (c+1))
6977   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6978     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6979                        DAG.getNode(ISD::FADD, dl, VT,
6980                                    N1, DAG.getConstantFP(1.0, VT)));
6981
6982   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6983   if (Options.UnsafeFPMath && N1CFP &&
6984       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6985     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6986                        DAG.getNode(ISD::FADD, dl, VT,
6987                                    N1, DAG.getConstantFP(-1.0, VT)));
6988
6989
6990   return SDValue();
6991 }
6992
6993 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6994   SDValue N0 = N->getOperand(0);
6995   SDValue N1 = N->getOperand(1);
6996   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6997   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6998   EVT VT = N->getValueType(0);
6999   SDLoc DL(N);
7000   const TargetOptions &Options = DAG.getTarget().Options;
7001
7002   // fold vector ops
7003   if (VT.isVector()) {
7004     SDValue FoldedVOp = SimplifyVBinOp(N);
7005     if (FoldedVOp.getNode()) return FoldedVOp;
7006   }
7007
7008   // fold (fdiv c1, c2) -> c1/c2
7009   if (N0CFP && N1CFP)
7010     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7011
7012   if (Options.UnsafeFPMath) {
7013     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7014     if (N1CFP) {
7015       // Compute the reciprocal 1.0 / c2.
7016       APFloat N1APF = N1CFP->getValueAPF();
7017       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7018       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7019       // Only do the transform if the reciprocal is a legal fp immediate that
7020       // isn't too nasty (eg NaN, denormal, ...).
7021       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7022           (!LegalOperations ||
7023            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7024            // backend)... we should handle this gracefully after Legalize.
7025            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7026            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7027            TLI.isFPImmLegal(Recip, VT)))
7028         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7029                            DAG.getConstantFP(Recip, VT));
7030     }
7031     
7032     // If this FDIV is part of a reciprocal square root, it may be folded
7033     // into a target-specific square root estimate instruction.
7034     if (N1.getOpcode() == ISD::FSQRT) {
7035       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7036         AddToWorklist(RV.getNode());
7037         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7038       }
7039     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7040                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7041       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7042         AddToWorklist(RV.getNode());
7043         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7044         AddToWorklist(RV.getNode());
7045         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7046       }
7047     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7048                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7049       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7050         AddToWorklist(RV.getNode());
7051         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7052         AddToWorklist(RV.getNode());
7053         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7054       }
7055     } else if (N1.getOpcode() == ISD::FMUL) {
7056       // Look through an FMUL. Even though this won't remove the FDIV directly,
7057       // it's still worthwhile to get rid of the FSQRT if possible.
7058       SDValue SqrtOp;
7059       SDValue OtherOp;
7060       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7061         SqrtOp = N1.getOperand(0);
7062         OtherOp = N1.getOperand(1);
7063       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7064         SqrtOp = N1.getOperand(1);
7065         OtherOp = N1.getOperand(0);
7066       }
7067       if (SqrtOp.getNode()) {
7068         // We found a FSQRT, so try to make this fold:
7069         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7070         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7071           AddToWorklist(RV.getNode());
7072           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7073           AddToWorklist(RV.getNode());
7074           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7075         }
7076       }
7077     }
7078     
7079     // Fold into a reciprocal estimate and multiply instead of a real divide.
7080     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7081       AddToWorklist(RV.getNode());
7082       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7083     }
7084   }
7085
7086   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7087   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7088     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7089       // Both can be negated for free, check to see if at least one is cheaper
7090       // negated.
7091       if (LHSNeg == 2 || RHSNeg == 2)
7092         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7093                            GetNegatedExpression(N0, DAG, LegalOperations),
7094                            GetNegatedExpression(N1, DAG, LegalOperations));
7095     }
7096   }
7097
7098   return SDValue();
7099 }
7100
7101 SDValue DAGCombiner::visitFREM(SDNode *N) {
7102   SDValue N0 = N->getOperand(0);
7103   SDValue N1 = N->getOperand(1);
7104   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7105   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7106   EVT VT = N->getValueType(0);
7107
7108   // fold (frem c1, c2) -> fmod(c1,c2)
7109   if (N0CFP && N1CFP)
7110     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7111
7112   return SDValue();
7113 }
7114
7115 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7116   if (DAG.getTarget().Options.UnsafeFPMath) {
7117     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7118     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7119       AddToWorklist(RV.getNode());
7120       EVT VT = RV.getValueType();
7121       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7122       AddToWorklist(RV.getNode());
7123
7124       // Unfortunately, RV is now NaN if the input was exactly 0.
7125       // Select out this case and force the answer to 0.
7126       SDValue Zero = DAG.getConstantFP(0.0, VT);
7127       SDValue ZeroCmp =
7128         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7129                      N->getOperand(0), Zero, ISD::SETEQ);
7130       AddToWorklist(ZeroCmp.getNode());
7131       AddToWorklist(RV.getNode());
7132
7133       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7134                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7135       return RV;
7136     }
7137   }
7138   return SDValue();
7139 }
7140
7141 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7142   SDValue N0 = N->getOperand(0);
7143   SDValue N1 = N->getOperand(1);
7144   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7145   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7146   EVT VT = N->getValueType(0);
7147
7148   if (N0CFP && N1CFP)  // Constant fold
7149     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7150
7151   if (N1CFP) {
7152     const APFloat& V = N1CFP->getValueAPF();
7153     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7154     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7155     if (!V.isNegative()) {
7156       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7157         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7158     } else {
7159       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7160         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7161                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7162     }
7163   }
7164
7165   // copysign(fabs(x), y) -> copysign(x, y)
7166   // copysign(fneg(x), y) -> copysign(x, y)
7167   // copysign(copysign(x,z), y) -> copysign(x, y)
7168   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7169       N0.getOpcode() == ISD::FCOPYSIGN)
7170     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7171                        N0.getOperand(0), N1);
7172
7173   // copysign(x, abs(y)) -> abs(x)
7174   if (N1.getOpcode() == ISD::FABS)
7175     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7176
7177   // copysign(x, copysign(y,z)) -> copysign(x, z)
7178   if (N1.getOpcode() == ISD::FCOPYSIGN)
7179     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7180                        N0, N1.getOperand(1));
7181
7182   // copysign(x, fp_extend(y)) -> copysign(x, y)
7183   // copysign(x, fp_round(y)) -> copysign(x, y)
7184   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7185     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7186                        N0, N1.getOperand(0));
7187
7188   return SDValue();
7189 }
7190
7191 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7192   SDValue N0 = N->getOperand(0);
7193   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7194   EVT VT = N->getValueType(0);
7195   EVT OpVT = N0.getValueType();
7196
7197   // fold (sint_to_fp c1) -> c1fp
7198   if (N0C &&
7199       // ...but only if the target supports immediate floating-point values
7200       (!LegalOperations ||
7201        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7202     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7203
7204   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7205   // but UINT_TO_FP is legal on this target, try to convert.
7206   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7207       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7208     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7209     if (DAG.SignBitIsZero(N0))
7210       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7211   }
7212
7213   // The next optimizations are desirable only if SELECT_CC can be lowered.
7214   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7215     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7216     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7217         !VT.isVector() &&
7218         (!LegalOperations ||
7219          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7220       SDValue Ops[] =
7221         { N0.getOperand(0), N0.getOperand(1),
7222           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7223           N0.getOperand(2) };
7224       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7225     }
7226
7227     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7228     //      (select_cc x, y, 1.0, 0.0,, cc)
7229     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7230         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7231         (!LegalOperations ||
7232          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7233       SDValue Ops[] =
7234         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7235           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7236           N0.getOperand(0).getOperand(2) };
7237       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7238     }
7239   }
7240
7241   return SDValue();
7242 }
7243
7244 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7245   SDValue N0 = N->getOperand(0);
7246   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7247   EVT VT = N->getValueType(0);
7248   EVT OpVT = N0.getValueType();
7249
7250   // fold (uint_to_fp c1) -> c1fp
7251   if (N0C &&
7252       // ...but only if the target supports immediate floating-point values
7253       (!LegalOperations ||
7254        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7255     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7256
7257   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7258   // but SINT_TO_FP is legal on this target, try to convert.
7259   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7260       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7261     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7262     if (DAG.SignBitIsZero(N0))
7263       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7264   }
7265
7266   // The next optimizations are desirable only if SELECT_CC can be lowered.
7267   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7268     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7269
7270     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7271         (!LegalOperations ||
7272          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7273       SDValue Ops[] =
7274         { N0.getOperand(0), N0.getOperand(1),
7275           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7276           N0.getOperand(2) };
7277       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7278     }
7279   }
7280
7281   return SDValue();
7282 }
7283
7284 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7285   SDValue N0 = N->getOperand(0);
7286   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7287   EVT VT = N->getValueType(0);
7288
7289   // fold (fp_to_sint c1fp) -> c1
7290   if (N0CFP)
7291     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7292
7293   return SDValue();
7294 }
7295
7296 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7297   SDValue N0 = N->getOperand(0);
7298   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7299   EVT VT = N->getValueType(0);
7300
7301   // fold (fp_to_uint c1fp) -> c1
7302   if (N0CFP)
7303     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7304
7305   return SDValue();
7306 }
7307
7308 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7309   SDValue N0 = N->getOperand(0);
7310   SDValue N1 = N->getOperand(1);
7311   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7312   EVT VT = N->getValueType(0);
7313
7314   // fold (fp_round c1fp) -> c1fp
7315   if (N0CFP)
7316     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7317
7318   // fold (fp_round (fp_extend x)) -> x
7319   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7320     return N0.getOperand(0);
7321
7322   // fold (fp_round (fp_round x)) -> (fp_round x)
7323   if (N0.getOpcode() == ISD::FP_ROUND) {
7324     // This is a value preserving truncation if both round's are.
7325     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7326                    N0.getNode()->getConstantOperandVal(1) == 1;
7327     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7328                        DAG.getIntPtrConstant(IsTrunc));
7329   }
7330
7331   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7332   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7333     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7334                               N0.getOperand(0), N1);
7335     AddToWorklist(Tmp.getNode());
7336     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7337                        Tmp, N0.getOperand(1));
7338   }
7339
7340   return SDValue();
7341 }
7342
7343 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7344   SDValue N0 = N->getOperand(0);
7345   EVT VT = N->getValueType(0);
7346   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7347   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7348
7349   // fold (fp_round_inreg c1fp) -> c1fp
7350   if (N0CFP && isTypeLegal(EVT)) {
7351     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7352     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7353   }
7354
7355   return SDValue();
7356 }
7357
7358 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7359   SDValue N0 = N->getOperand(0);
7360   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7361   EVT VT = N->getValueType(0);
7362
7363   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7364   if (N->hasOneUse() &&
7365       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7366     return SDValue();
7367
7368   // fold (fp_extend c1fp) -> c1fp
7369   if (N0CFP)
7370     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7371
7372   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7373   // value of X.
7374   if (N0.getOpcode() == ISD::FP_ROUND
7375       && N0.getNode()->getConstantOperandVal(1) == 1) {
7376     SDValue In = N0.getOperand(0);
7377     if (In.getValueType() == VT) return In;
7378     if (VT.bitsLT(In.getValueType()))
7379       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7380                          In, N0.getOperand(1));
7381     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7382   }
7383
7384   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7385   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7386        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7387     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7388     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7389                                      LN0->getChain(),
7390                                      LN0->getBasePtr(), N0.getValueType(),
7391                                      LN0->getMemOperand());
7392     CombineTo(N, ExtLoad);
7393     CombineTo(N0.getNode(),
7394               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7395                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7396               ExtLoad.getValue(1));
7397     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7398   }
7399
7400   return SDValue();
7401 }
7402
7403 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7404   SDValue N0 = N->getOperand(0);
7405   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7406   EVT VT = N->getValueType(0);
7407
7408   // fold (fceil c1) -> fceil(c1)
7409   if (N0CFP)
7410     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7411
7412   return SDValue();
7413 }
7414
7415 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7416   SDValue N0 = N->getOperand(0);
7417   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7418   EVT VT = N->getValueType(0);
7419
7420   // fold (ftrunc c1) -> ftrunc(c1)
7421   if (N0CFP)
7422     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7423
7424   return SDValue();
7425 }
7426
7427 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7428   SDValue N0 = N->getOperand(0);
7429   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7430   EVT VT = N->getValueType(0);
7431
7432   // fold (ffloor c1) -> ffloor(c1)
7433   if (N0CFP)
7434     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7435
7436   return SDValue();
7437 }
7438
7439 // FIXME: FNEG and FABS have a lot in common; refactor.
7440 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7441   SDValue N0 = N->getOperand(0);
7442   EVT VT = N->getValueType(0);
7443
7444   if (VT.isVector()) {
7445     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7446     if (FoldedVOp.getNode()) return FoldedVOp;
7447   }
7448
7449   // Constant fold FNEG.
7450   if (isa<ConstantFPSDNode>(N0))
7451     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7452
7453   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7454                          &DAG.getTarget().Options))
7455     return GetNegatedExpression(N0, DAG, LegalOperations);
7456
7457   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7458   // constant pool values.
7459   if (!TLI.isFNegFree(VT) &&
7460       N0.getOpcode() == ISD::BITCAST &&
7461       N0.getNode()->hasOneUse()) {
7462     SDValue Int = N0.getOperand(0);
7463     EVT IntVT = Int.getValueType();
7464     if (IntVT.isInteger() && !IntVT.isVector()) {
7465       APInt SignMask;
7466       if (N0.getValueType().isVector()) {
7467         // For a vector, get a mask such as 0x80... per scalar element
7468         // and splat it.
7469         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7470         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7471       } else {
7472         // For a scalar, just generate 0x80...
7473         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7474       }
7475       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7476                         DAG.getConstant(SignMask, IntVT));
7477       AddToWorklist(Int.getNode());
7478       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7479     }
7480   }
7481
7482   // (fneg (fmul c, x)) -> (fmul -c, x)
7483   if (N0.getOpcode() == ISD::FMUL) {
7484     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7485     if (CFP1) {
7486       APFloat CVal = CFP1->getValueAPF();
7487       CVal.changeSign();
7488       if (Level >= AfterLegalizeDAG &&
7489           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7490            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7491         return DAG.getNode(
7492             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7493             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7494     }
7495   }
7496
7497   return SDValue();
7498 }
7499
7500 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7501   SDValue N0 = N->getOperand(0);
7502   SDValue N1 = N->getOperand(1);
7503   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7504   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7505
7506   if (N0CFP && N1CFP) {
7507     const APFloat &C0 = N0CFP->getValueAPF();
7508     const APFloat &C1 = N1CFP->getValueAPF();
7509     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7510   }
7511
7512   if (N0CFP) {
7513     EVT VT = N->getValueType(0);
7514     // Canonicalize to constant on RHS.
7515     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7516   }
7517
7518   return SDValue();
7519 }
7520
7521 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7522   SDValue N0 = N->getOperand(0);
7523   SDValue N1 = N->getOperand(1);
7524   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7525   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7526
7527   if (N0CFP && N1CFP) {
7528     const APFloat &C0 = N0CFP->getValueAPF();
7529     const APFloat &C1 = N1CFP->getValueAPF();
7530     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7531   }
7532
7533   if (N0CFP) {
7534     EVT VT = N->getValueType(0);
7535     // Canonicalize to constant on RHS.
7536     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7537   }
7538
7539   return SDValue();
7540 }
7541
7542 SDValue DAGCombiner::visitFABS(SDNode *N) {
7543   SDValue N0 = N->getOperand(0);
7544   EVT VT = N->getValueType(0);
7545
7546   if (VT.isVector()) {
7547     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7548     if (FoldedVOp.getNode()) return FoldedVOp;
7549   }
7550
7551   // fold (fabs c1) -> fabs(c1)
7552   if (isa<ConstantFPSDNode>(N0))
7553     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7554   
7555   // fold (fabs (fabs x)) -> (fabs x)
7556   if (N0.getOpcode() == ISD::FABS)
7557     return N->getOperand(0);
7558
7559   // fold (fabs (fneg x)) -> (fabs x)
7560   // fold (fabs (fcopysign x, y)) -> (fabs x)
7561   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7562     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7563
7564   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7565   // constant pool values.
7566   if (!TLI.isFAbsFree(VT) &&
7567       N0.getOpcode() == ISD::BITCAST &&
7568       N0.getNode()->hasOneUse()) {
7569     SDValue Int = N0.getOperand(0);
7570     EVT IntVT = Int.getValueType();
7571     if (IntVT.isInteger() && !IntVT.isVector()) {
7572       APInt SignMask;
7573       if (N0.getValueType().isVector()) {
7574         // For a vector, get a mask such as 0x7f... per scalar element
7575         // and splat it.
7576         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7577         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7578       } else {
7579         // For a scalar, just generate 0x7f...
7580         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7581       }
7582       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7583                         DAG.getConstant(SignMask, IntVT));
7584       AddToWorklist(Int.getNode());
7585       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7586     }
7587   }
7588
7589   return SDValue();
7590 }
7591
7592 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7593   SDValue Chain = N->getOperand(0);
7594   SDValue N1 = N->getOperand(1);
7595   SDValue N2 = N->getOperand(2);
7596
7597   // If N is a constant we could fold this into a fallthrough or unconditional
7598   // branch. However that doesn't happen very often in normal code, because
7599   // Instcombine/SimplifyCFG should have handled the available opportunities.
7600   // If we did this folding here, it would be necessary to update the
7601   // MachineBasicBlock CFG, which is awkward.
7602
7603   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7604   // on the target.
7605   if (N1.getOpcode() == ISD::SETCC &&
7606       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7607                                    N1.getOperand(0).getValueType())) {
7608     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7609                        Chain, N1.getOperand(2),
7610                        N1.getOperand(0), N1.getOperand(1), N2);
7611   }
7612
7613   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7614       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7615        (N1.getOperand(0).hasOneUse() &&
7616         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7617     SDNode *Trunc = nullptr;
7618     if (N1.getOpcode() == ISD::TRUNCATE) {
7619       // Look pass the truncate.
7620       Trunc = N1.getNode();
7621       N1 = N1.getOperand(0);
7622     }
7623
7624     // Match this pattern so that we can generate simpler code:
7625     //
7626     //   %a = ...
7627     //   %b = and i32 %a, 2
7628     //   %c = srl i32 %b, 1
7629     //   brcond i32 %c ...
7630     //
7631     // into
7632     //
7633     //   %a = ...
7634     //   %b = and i32 %a, 2
7635     //   %c = setcc eq %b, 0
7636     //   brcond %c ...
7637     //
7638     // This applies only when the AND constant value has one bit set and the
7639     // SRL constant is equal to the log2 of the AND constant. The back-end is
7640     // smart enough to convert the result into a TEST/JMP sequence.
7641     SDValue Op0 = N1.getOperand(0);
7642     SDValue Op1 = N1.getOperand(1);
7643
7644     if (Op0.getOpcode() == ISD::AND &&
7645         Op1.getOpcode() == ISD::Constant) {
7646       SDValue AndOp1 = Op0.getOperand(1);
7647
7648       if (AndOp1.getOpcode() == ISD::Constant) {
7649         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7650
7651         if (AndConst.isPowerOf2() &&
7652             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7653           SDValue SetCC =
7654             DAG.getSetCC(SDLoc(N),
7655                          getSetCCResultType(Op0.getValueType()),
7656                          Op0, DAG.getConstant(0, Op0.getValueType()),
7657                          ISD::SETNE);
7658
7659           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7660                                           MVT::Other, Chain, SetCC, N2);
7661           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7662           // will convert it back to (X & C1) >> C2.
7663           CombineTo(N, NewBRCond, false);
7664           // Truncate is dead.
7665           if (Trunc)
7666             deleteAndRecombine(Trunc);
7667           // Replace the uses of SRL with SETCC
7668           WorklistRemover DeadNodes(*this);
7669           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7670           deleteAndRecombine(N1.getNode());
7671           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7672         }
7673       }
7674     }
7675
7676     if (Trunc)
7677       // Restore N1 if the above transformation doesn't match.
7678       N1 = N->getOperand(1);
7679   }
7680
7681   // Transform br(xor(x, y)) -> br(x != y)
7682   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7683   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7684     SDNode *TheXor = N1.getNode();
7685     SDValue Op0 = TheXor->getOperand(0);
7686     SDValue Op1 = TheXor->getOperand(1);
7687     if (Op0.getOpcode() == Op1.getOpcode()) {
7688       // Avoid missing important xor optimizations.
7689       SDValue Tmp = visitXOR(TheXor);
7690       if (Tmp.getNode()) {
7691         if (Tmp.getNode() != TheXor) {
7692           DEBUG(dbgs() << "\nReplacing.8 ";
7693                 TheXor->dump(&DAG);
7694                 dbgs() << "\nWith: ";
7695                 Tmp.getNode()->dump(&DAG);
7696                 dbgs() << '\n');
7697           WorklistRemover DeadNodes(*this);
7698           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7699           deleteAndRecombine(TheXor);
7700           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7701                              MVT::Other, Chain, Tmp, N2);
7702         }
7703
7704         // visitXOR has changed XOR's operands or replaced the XOR completely,
7705         // bail out.
7706         return SDValue(N, 0);
7707       }
7708     }
7709
7710     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7711       bool Equal = false;
7712       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7713         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7714             Op0.getOpcode() == ISD::XOR) {
7715           TheXor = Op0.getNode();
7716           Equal = true;
7717         }
7718
7719       EVT SetCCVT = N1.getValueType();
7720       if (LegalTypes)
7721         SetCCVT = getSetCCResultType(SetCCVT);
7722       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7723                                    SetCCVT,
7724                                    Op0, Op1,
7725                                    Equal ? ISD::SETEQ : ISD::SETNE);
7726       // Replace the uses of XOR with SETCC
7727       WorklistRemover DeadNodes(*this);
7728       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7729       deleteAndRecombine(N1.getNode());
7730       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7731                          MVT::Other, Chain, SetCC, N2);
7732     }
7733   }
7734
7735   return SDValue();
7736 }
7737
7738 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7739 //
7740 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7741   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7742   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7743
7744   // If N is a constant we could fold this into a fallthrough or unconditional
7745   // branch. However that doesn't happen very often in normal code, because
7746   // Instcombine/SimplifyCFG should have handled the available opportunities.
7747   // If we did this folding here, it would be necessary to update the
7748   // MachineBasicBlock CFG, which is awkward.
7749
7750   // Use SimplifySetCC to simplify SETCC's.
7751   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7752                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7753                                false);
7754   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7755
7756   // fold to a simpler setcc
7757   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7758     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7759                        N->getOperand(0), Simp.getOperand(2),
7760                        Simp.getOperand(0), Simp.getOperand(1),
7761                        N->getOperand(4));
7762
7763   return SDValue();
7764 }
7765
7766 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7767 /// and that N may be folded in the load / store addressing mode.
7768 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7769                                     SelectionDAG &DAG,
7770                                     const TargetLowering &TLI) {
7771   EVT VT;
7772   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7773     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7774       return false;
7775     VT = Use->getValueType(0);
7776   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7777     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7778       return false;
7779     VT = ST->getValue().getValueType();
7780   } else
7781     return false;
7782
7783   TargetLowering::AddrMode AM;
7784   if (N->getOpcode() == ISD::ADD) {
7785     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7786     if (Offset)
7787       // [reg +/- imm]
7788       AM.BaseOffs = Offset->getSExtValue();
7789     else
7790       // [reg +/- reg]
7791       AM.Scale = 1;
7792   } else if (N->getOpcode() == ISD::SUB) {
7793     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7794     if (Offset)
7795       // [reg +/- imm]
7796       AM.BaseOffs = -Offset->getSExtValue();
7797     else
7798       // [reg +/- reg]
7799       AM.Scale = 1;
7800   } else
7801     return false;
7802
7803   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7804 }
7805
7806 /// Try turning a load/store into a pre-indexed load/store when the base
7807 /// pointer is an add or subtract and it has other uses besides the load/store.
7808 /// After the transformation, the new indexed load/store has effectively folded
7809 /// the add/subtract in and all of its other uses are redirected to the
7810 /// new load/store.
7811 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7812   if (Level < AfterLegalizeDAG)
7813     return false;
7814
7815   bool isLoad = true;
7816   SDValue Ptr;
7817   EVT VT;
7818   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7819     if (LD->isIndexed())
7820       return false;
7821     VT = LD->getMemoryVT();
7822     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7823         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7824       return false;
7825     Ptr = LD->getBasePtr();
7826   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7827     if (ST->isIndexed())
7828       return false;
7829     VT = ST->getMemoryVT();
7830     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7831         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7832       return false;
7833     Ptr = ST->getBasePtr();
7834     isLoad = false;
7835   } else {
7836     return false;
7837   }
7838
7839   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7840   // out.  There is no reason to make this a preinc/predec.
7841   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7842       Ptr.getNode()->hasOneUse())
7843     return false;
7844
7845   // Ask the target to do addressing mode selection.
7846   SDValue BasePtr;
7847   SDValue Offset;
7848   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7849   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7850     return false;
7851
7852   // Backends without true r+i pre-indexed forms may need to pass a
7853   // constant base with a variable offset so that constant coercion
7854   // will work with the patterns in canonical form.
7855   bool Swapped = false;
7856   if (isa<ConstantSDNode>(BasePtr)) {
7857     std::swap(BasePtr, Offset);
7858     Swapped = true;
7859   }
7860
7861   // Don't create a indexed load / store with zero offset.
7862   if (isa<ConstantSDNode>(Offset) &&
7863       cast<ConstantSDNode>(Offset)->isNullValue())
7864     return false;
7865
7866   // Try turning it into a pre-indexed load / store except when:
7867   // 1) The new base ptr is a frame index.
7868   // 2) If N is a store and the new base ptr is either the same as or is a
7869   //    predecessor of the value being stored.
7870   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7871   //    that would create a cycle.
7872   // 4) All uses are load / store ops that use it as old base ptr.
7873
7874   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7875   // (plus the implicit offset) to a register to preinc anyway.
7876   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7877     return false;
7878
7879   // Check #2.
7880   if (!isLoad) {
7881     SDValue Val = cast<StoreSDNode>(N)->getValue();
7882     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7883       return false;
7884   }
7885
7886   // If the offset is a constant, there may be other adds of constants that
7887   // can be folded with this one. We should do this to avoid having to keep
7888   // a copy of the original base pointer.
7889   SmallVector<SDNode *, 16> OtherUses;
7890   if (isa<ConstantSDNode>(Offset))
7891     for (SDNode *Use : BasePtr.getNode()->uses()) {
7892       if (Use == Ptr.getNode())
7893         continue;
7894
7895       if (Use->isPredecessorOf(N))
7896         continue;
7897
7898       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7899         OtherUses.clear();
7900         break;
7901       }
7902
7903       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7904       if (Op1.getNode() == BasePtr.getNode())
7905         std::swap(Op0, Op1);
7906       assert(Op0.getNode() == BasePtr.getNode() &&
7907              "Use of ADD/SUB but not an operand");
7908
7909       if (!isa<ConstantSDNode>(Op1)) {
7910         OtherUses.clear();
7911         break;
7912       }
7913
7914       // FIXME: In some cases, we can be smarter about this.
7915       if (Op1.getValueType() != Offset.getValueType()) {
7916         OtherUses.clear();
7917         break;
7918       }
7919
7920       OtherUses.push_back(Use);
7921     }
7922
7923   if (Swapped)
7924     std::swap(BasePtr, Offset);
7925
7926   // Now check for #3 and #4.
7927   bool RealUse = false;
7928
7929   // Caches for hasPredecessorHelper
7930   SmallPtrSet<const SDNode *, 32> Visited;
7931   SmallVector<const SDNode *, 16> Worklist;
7932
7933   for (SDNode *Use : Ptr.getNode()->uses()) {
7934     if (Use == N)
7935       continue;
7936     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7937       return false;
7938
7939     // If Ptr may be folded in addressing mode of other use, then it's
7940     // not profitable to do this transformation.
7941     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7942       RealUse = true;
7943   }
7944
7945   if (!RealUse)
7946     return false;
7947
7948   SDValue Result;
7949   if (isLoad)
7950     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7951                                 BasePtr, Offset, AM);
7952   else
7953     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7954                                  BasePtr, Offset, AM);
7955   ++PreIndexedNodes;
7956   ++NodesCombined;
7957   DEBUG(dbgs() << "\nReplacing.4 ";
7958         N->dump(&DAG);
7959         dbgs() << "\nWith: ";
7960         Result.getNode()->dump(&DAG);
7961         dbgs() << '\n');
7962   WorklistRemover DeadNodes(*this);
7963   if (isLoad) {
7964     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7965     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7966   } else {
7967     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7968   }
7969
7970   // Finally, since the node is now dead, remove it from the graph.
7971   deleteAndRecombine(N);
7972
7973   if (Swapped)
7974     std::swap(BasePtr, Offset);
7975
7976   // Replace other uses of BasePtr that can be updated to use Ptr
7977   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7978     unsigned OffsetIdx = 1;
7979     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7980       OffsetIdx = 0;
7981     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7982            BasePtr.getNode() && "Expected BasePtr operand");
7983
7984     // We need to replace ptr0 in the following expression:
7985     //   x0 * offset0 + y0 * ptr0 = t0
7986     // knowing that
7987     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7988     //
7989     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7990     // indexed load/store and the expresion that needs to be re-written.
7991     //
7992     // Therefore, we have:
7993     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7994
7995     ConstantSDNode *CN =
7996       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7997     int X0, X1, Y0, Y1;
7998     APInt Offset0 = CN->getAPIntValue();
7999     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8000
8001     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8002     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8003     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8004     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8005
8006     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8007
8008     APInt CNV = Offset0;
8009     if (X0 < 0) CNV = -CNV;
8010     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8011     else CNV = CNV - Offset1;
8012
8013     // We can now generate the new expression.
8014     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8015     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8016
8017     SDValue NewUse = DAG.getNode(Opcode,
8018                                  SDLoc(OtherUses[i]),
8019                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8020     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8021     deleteAndRecombine(OtherUses[i]);
8022   }
8023
8024   // Replace the uses of Ptr with uses of the updated base value.
8025   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8026   deleteAndRecombine(Ptr.getNode());
8027
8028   return true;
8029 }
8030
8031 /// Try to combine a load/store with a add/sub of the base pointer node into a
8032 /// post-indexed load/store. The transformation folded the add/subtract into the
8033 /// new indexed load/store effectively and all of its uses are redirected to the
8034 /// new load/store.
8035 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8036   if (Level < AfterLegalizeDAG)
8037     return false;
8038
8039   bool isLoad = true;
8040   SDValue Ptr;
8041   EVT VT;
8042   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8043     if (LD->isIndexed())
8044       return false;
8045     VT = LD->getMemoryVT();
8046     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8047         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8048       return false;
8049     Ptr = LD->getBasePtr();
8050   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8051     if (ST->isIndexed())
8052       return false;
8053     VT = ST->getMemoryVT();
8054     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8055         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8056       return false;
8057     Ptr = ST->getBasePtr();
8058     isLoad = false;
8059   } else {
8060     return false;
8061   }
8062
8063   if (Ptr.getNode()->hasOneUse())
8064     return false;
8065
8066   for (SDNode *Op : Ptr.getNode()->uses()) {
8067     if (Op == N ||
8068         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8069       continue;
8070
8071     SDValue BasePtr;
8072     SDValue Offset;
8073     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8074     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8075       // Don't create a indexed load / store with zero offset.
8076       if (isa<ConstantSDNode>(Offset) &&
8077           cast<ConstantSDNode>(Offset)->isNullValue())
8078         continue;
8079
8080       // Try turning it into a post-indexed load / store except when
8081       // 1) All uses are load / store ops that use it as base ptr (and
8082       //    it may be folded as addressing mmode).
8083       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8084       //    nor a successor of N. Otherwise, if Op is folded that would
8085       //    create a cycle.
8086
8087       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8088         continue;
8089
8090       // Check for #1.
8091       bool TryNext = false;
8092       for (SDNode *Use : BasePtr.getNode()->uses()) {
8093         if (Use == Ptr.getNode())
8094           continue;
8095
8096         // If all the uses are load / store addresses, then don't do the
8097         // transformation.
8098         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8099           bool RealUse = false;
8100           for (SDNode *UseUse : Use->uses()) {
8101             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8102               RealUse = true;
8103           }
8104
8105           if (!RealUse) {
8106             TryNext = true;
8107             break;
8108           }
8109         }
8110       }
8111
8112       if (TryNext)
8113         continue;
8114
8115       // Check for #2
8116       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8117         SDValue Result = isLoad
8118           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8119                                BasePtr, Offset, AM)
8120           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8121                                 BasePtr, Offset, AM);
8122         ++PostIndexedNodes;
8123         ++NodesCombined;
8124         DEBUG(dbgs() << "\nReplacing.5 ";
8125               N->dump(&DAG);
8126               dbgs() << "\nWith: ";
8127               Result.getNode()->dump(&DAG);
8128               dbgs() << '\n');
8129         WorklistRemover DeadNodes(*this);
8130         if (isLoad) {
8131           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8132           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8133         } else {
8134           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8135         }
8136
8137         // Finally, since the node is now dead, remove it from the graph.
8138         deleteAndRecombine(N);
8139
8140         // Replace the uses of Use with uses of the updated base value.
8141         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8142                                       Result.getValue(isLoad ? 1 : 0));
8143         deleteAndRecombine(Op);
8144         return true;
8145       }
8146     }
8147   }
8148
8149   return false;
8150 }
8151
8152 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8153 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8154   ISD::MemIndexedMode AM = LD->getAddressingMode();
8155   assert(AM != ISD::UNINDEXED);
8156   SDValue BP = LD->getOperand(1);
8157   SDValue Inc = LD->getOperand(2);
8158
8159   // Some backends use TargetConstants for load offsets, but don't expect
8160   // TargetConstants in general ADD nodes. We can convert these constants into
8161   // regular Constants (if the constant is not opaque).
8162   assert((Inc.getOpcode() != ISD::TargetConstant ||
8163           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8164          "Cannot split out indexing using opaque target constants");
8165   if (Inc.getOpcode() == ISD::TargetConstant) {
8166     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8167     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8168                           ConstInc->getValueType(0));
8169   }
8170
8171   unsigned Opc =
8172       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8173   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8174 }
8175
8176 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8177   LoadSDNode *LD  = cast<LoadSDNode>(N);
8178   SDValue Chain = LD->getChain();
8179   SDValue Ptr   = LD->getBasePtr();
8180
8181   // If load is not volatile and there are no uses of the loaded value (and
8182   // the updated indexed value in case of indexed loads), change uses of the
8183   // chain value into uses of the chain input (i.e. delete the dead load).
8184   if (!LD->isVolatile()) {
8185     if (N->getValueType(1) == MVT::Other) {
8186       // Unindexed loads.
8187       if (!N->hasAnyUseOfValue(0)) {
8188         // It's not safe to use the two value CombineTo variant here. e.g.
8189         // v1, chain2 = load chain1, loc
8190         // v2, chain3 = load chain2, loc
8191         // v3         = add v2, c
8192         // Now we replace use of chain2 with chain1.  This makes the second load
8193         // isomorphic to the one we are deleting, and thus makes this load live.
8194         DEBUG(dbgs() << "\nReplacing.6 ";
8195               N->dump(&DAG);
8196               dbgs() << "\nWith chain: ";
8197               Chain.getNode()->dump(&DAG);
8198               dbgs() << "\n");
8199         WorklistRemover DeadNodes(*this);
8200         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8201
8202         if (N->use_empty())
8203           deleteAndRecombine(N);
8204
8205         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8206       }
8207     } else {
8208       // Indexed loads.
8209       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8210
8211       // If this load has an opaque TargetConstant offset, then we cannot split
8212       // the indexing into an add/sub directly (that TargetConstant may not be
8213       // valid for a different type of node, and we cannot convert an opaque
8214       // target constant into a regular constant).
8215       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8216                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8217
8218       if (!N->hasAnyUseOfValue(0) &&
8219           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8220         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8221         SDValue Index;
8222         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8223           Index = SplitIndexingFromLoad(LD);
8224           // Try to fold the base pointer arithmetic into subsequent loads and
8225           // stores.
8226           AddUsersToWorklist(N);
8227         } else
8228           Index = DAG.getUNDEF(N->getValueType(1));
8229         DEBUG(dbgs() << "\nReplacing.7 ";
8230               N->dump(&DAG);
8231               dbgs() << "\nWith: ";
8232               Undef.getNode()->dump(&DAG);
8233               dbgs() << " and 2 other values\n");
8234         WorklistRemover DeadNodes(*this);
8235         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8236         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8237         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8238         deleteAndRecombine(N);
8239         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8240       }
8241     }
8242   }
8243
8244   // If this load is directly stored, replace the load value with the stored
8245   // value.
8246   // TODO: Handle store large -> read small portion.
8247   // TODO: Handle TRUNCSTORE/LOADEXT
8248   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8249     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8250       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8251       if (PrevST->getBasePtr() == Ptr &&
8252           PrevST->getValue().getValueType() == N->getValueType(0))
8253       return CombineTo(N, Chain.getOperand(1), Chain);
8254     }
8255   }
8256
8257   // Try to infer better alignment information than the load already has.
8258   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8259     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8260       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8261         SDValue NewLoad =
8262                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8263                               LD->getValueType(0),
8264                               Chain, Ptr, LD->getPointerInfo(),
8265                               LD->getMemoryVT(),
8266                               LD->isVolatile(), LD->isNonTemporal(),
8267                               LD->isInvariant(), Align, LD->getAAInfo());
8268         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8269       }
8270     }
8271   }
8272
8273   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8274                                                   : DAG.getSubtarget().useAA();
8275 #ifndef NDEBUG
8276   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8277       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8278     UseAA = false;
8279 #endif
8280   if (UseAA && LD->isUnindexed()) {
8281     // Walk up chain skipping non-aliasing memory nodes.
8282     SDValue BetterChain = FindBetterChain(N, Chain);
8283
8284     // If there is a better chain.
8285     if (Chain != BetterChain) {
8286       SDValue ReplLoad;
8287
8288       // Replace the chain to void dependency.
8289       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8290         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8291                                BetterChain, Ptr, LD->getMemOperand());
8292       } else {
8293         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8294                                   LD->getValueType(0),
8295                                   BetterChain, Ptr, LD->getMemoryVT(),
8296                                   LD->getMemOperand());
8297       }
8298
8299       // Create token factor to keep old chain connected.
8300       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8301                                   MVT::Other, Chain, ReplLoad.getValue(1));
8302
8303       // Make sure the new and old chains are cleaned up.
8304       AddToWorklist(Token.getNode());
8305
8306       // Replace uses with load result and token factor. Don't add users
8307       // to work list.
8308       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8309     }
8310   }
8311
8312   // Try transforming N to an indexed load.
8313   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8314     return SDValue(N, 0);
8315
8316   // Try to slice up N to more direct loads if the slices are mapped to
8317   // different register banks or pairing can take place.
8318   if (SliceUpLoad(N))
8319     return SDValue(N, 0);
8320
8321   return SDValue();
8322 }
8323
8324 namespace {
8325 /// \brief Helper structure used to slice a load in smaller loads.
8326 /// Basically a slice is obtained from the following sequence:
8327 /// Origin = load Ty1, Base
8328 /// Shift = srl Ty1 Origin, CstTy Amount
8329 /// Inst = trunc Shift to Ty2
8330 ///
8331 /// Then, it will be rewriten into:
8332 /// Slice = load SliceTy, Base + SliceOffset
8333 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8334 ///
8335 /// SliceTy is deduced from the number of bits that are actually used to
8336 /// build Inst.
8337 struct LoadedSlice {
8338   /// \brief Helper structure used to compute the cost of a slice.
8339   struct Cost {
8340     /// Are we optimizing for code size.
8341     bool ForCodeSize;
8342     /// Various cost.
8343     unsigned Loads;
8344     unsigned Truncates;
8345     unsigned CrossRegisterBanksCopies;
8346     unsigned ZExts;
8347     unsigned Shift;
8348
8349     Cost(bool ForCodeSize = false)
8350         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8351           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8352
8353     /// \brief Get the cost of one isolated slice.
8354     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8355         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8356           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8357       EVT TruncType = LS.Inst->getValueType(0);
8358       EVT LoadedType = LS.getLoadedType();
8359       if (TruncType != LoadedType &&
8360           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8361         ZExts = 1;
8362     }
8363
8364     /// \brief Account for slicing gain in the current cost.
8365     /// Slicing provide a few gains like removing a shift or a
8366     /// truncate. This method allows to grow the cost of the original
8367     /// load with the gain from this slice.
8368     void addSliceGain(const LoadedSlice &LS) {
8369       // Each slice saves a truncate.
8370       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8371       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8372                               LS.Inst->getOperand(0).getValueType()))
8373         ++Truncates;
8374       // If there is a shift amount, this slice gets rid of it.
8375       if (LS.Shift)
8376         ++Shift;
8377       // If this slice can merge a cross register bank copy, account for it.
8378       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8379         ++CrossRegisterBanksCopies;
8380     }
8381
8382     Cost &operator+=(const Cost &RHS) {
8383       Loads += RHS.Loads;
8384       Truncates += RHS.Truncates;
8385       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8386       ZExts += RHS.ZExts;
8387       Shift += RHS.Shift;
8388       return *this;
8389     }
8390
8391     bool operator==(const Cost &RHS) const {
8392       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8393              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8394              ZExts == RHS.ZExts && Shift == RHS.Shift;
8395     }
8396
8397     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8398
8399     bool operator<(const Cost &RHS) const {
8400       // Assume cross register banks copies are as expensive as loads.
8401       // FIXME: Do we want some more target hooks?
8402       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8403       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8404       // Unless we are optimizing for code size, consider the
8405       // expensive operation first.
8406       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8407         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8408       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8409              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8410     }
8411
8412     bool operator>(const Cost &RHS) const { return RHS < *this; }
8413
8414     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8415
8416     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8417   };
8418   // The last instruction that represent the slice. This should be a
8419   // truncate instruction.
8420   SDNode *Inst;
8421   // The original load instruction.
8422   LoadSDNode *Origin;
8423   // The right shift amount in bits from the original load.
8424   unsigned Shift;
8425   // The DAG from which Origin came from.
8426   // This is used to get some contextual information about legal types, etc.
8427   SelectionDAG *DAG;
8428
8429   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8430               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8431       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8432
8433   LoadedSlice(const LoadedSlice &LS)
8434       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8435
8436   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8437   /// \return Result is \p BitWidth and has used bits set to 1 and
8438   ///         not used bits set to 0.
8439   APInt getUsedBits() const {
8440     // Reproduce the trunc(lshr) sequence:
8441     // - Start from the truncated value.
8442     // - Zero extend to the desired bit width.
8443     // - Shift left.
8444     assert(Origin && "No original load to compare against.");
8445     unsigned BitWidth = Origin->getValueSizeInBits(0);
8446     assert(Inst && "This slice is not bound to an instruction");
8447     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8448            "Extracted slice is bigger than the whole type!");
8449     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8450     UsedBits.setAllBits();
8451     UsedBits = UsedBits.zext(BitWidth);
8452     UsedBits <<= Shift;
8453     return UsedBits;
8454   }
8455
8456   /// \brief Get the size of the slice to be loaded in bytes.
8457   unsigned getLoadedSize() const {
8458     unsigned SliceSize = getUsedBits().countPopulation();
8459     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8460     return SliceSize / 8;
8461   }
8462
8463   /// \brief Get the type that will be loaded for this slice.
8464   /// Note: This may not be the final type for the slice.
8465   EVT getLoadedType() const {
8466     assert(DAG && "Missing context");
8467     LLVMContext &Ctxt = *DAG->getContext();
8468     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8469   }
8470
8471   /// \brief Get the alignment of the load used for this slice.
8472   unsigned getAlignment() const {
8473     unsigned Alignment = Origin->getAlignment();
8474     unsigned Offset = getOffsetFromBase();
8475     if (Offset != 0)
8476       Alignment = MinAlign(Alignment, Alignment + Offset);
8477     return Alignment;
8478   }
8479
8480   /// \brief Check if this slice can be rewritten with legal operations.
8481   bool isLegal() const {
8482     // An invalid slice is not legal.
8483     if (!Origin || !Inst || !DAG)
8484       return false;
8485
8486     // Offsets are for indexed load only, we do not handle that.
8487     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8488       return false;
8489
8490     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8491
8492     // Check that the type is legal.
8493     EVT SliceType = getLoadedType();
8494     if (!TLI.isTypeLegal(SliceType))
8495       return false;
8496
8497     // Check that the load is legal for this type.
8498     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8499       return false;
8500
8501     // Check that the offset can be computed.
8502     // 1. Check its type.
8503     EVT PtrType = Origin->getBasePtr().getValueType();
8504     if (PtrType == MVT::Untyped || PtrType.isExtended())
8505       return false;
8506
8507     // 2. Check that it fits in the immediate.
8508     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8509       return false;
8510
8511     // 3. Check that the computation is legal.
8512     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8513       return false;
8514
8515     // Check that the zext is legal if it needs one.
8516     EVT TruncateType = Inst->getValueType(0);
8517     if (TruncateType != SliceType &&
8518         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8519       return false;
8520
8521     return true;
8522   }
8523
8524   /// \brief Get the offset in bytes of this slice in the original chunk of
8525   /// bits.
8526   /// \pre DAG != nullptr.
8527   uint64_t getOffsetFromBase() const {
8528     assert(DAG && "Missing context.");
8529     bool IsBigEndian =
8530         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8531     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8532     uint64_t Offset = Shift / 8;
8533     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8534     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8535            "The size of the original loaded type is not a multiple of a"
8536            " byte.");
8537     // If Offset is bigger than TySizeInBytes, it means we are loading all
8538     // zeros. This should have been optimized before in the process.
8539     assert(TySizeInBytes > Offset &&
8540            "Invalid shift amount for given loaded size");
8541     if (IsBigEndian)
8542       Offset = TySizeInBytes - Offset - getLoadedSize();
8543     return Offset;
8544   }
8545
8546   /// \brief Generate the sequence of instructions to load the slice
8547   /// represented by this object and redirect the uses of this slice to
8548   /// this new sequence of instructions.
8549   /// \pre this->Inst && this->Origin are valid Instructions and this
8550   /// object passed the legal check: LoadedSlice::isLegal returned true.
8551   /// \return The last instruction of the sequence used to load the slice.
8552   SDValue loadSlice() const {
8553     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8554     const SDValue &OldBaseAddr = Origin->getBasePtr();
8555     SDValue BaseAddr = OldBaseAddr;
8556     // Get the offset in that chunk of bytes w.r.t. the endianess.
8557     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8558     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8559     if (Offset) {
8560       // BaseAddr = BaseAddr + Offset.
8561       EVT ArithType = BaseAddr.getValueType();
8562       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8563                               DAG->getConstant(Offset, ArithType));
8564     }
8565
8566     // Create the type of the loaded slice according to its size.
8567     EVT SliceType = getLoadedType();
8568
8569     // Create the load for the slice.
8570     SDValue LastInst = DAG->getLoad(
8571         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8572         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8573         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8574     // If the final type is not the same as the loaded type, this means that
8575     // we have to pad with zero. Create a zero extend for that.
8576     EVT FinalType = Inst->getValueType(0);
8577     if (SliceType != FinalType)
8578       LastInst =
8579           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8580     return LastInst;
8581   }
8582
8583   /// \brief Check if this slice can be merged with an expensive cross register
8584   /// bank copy. E.g.,
8585   /// i = load i32
8586   /// f = bitcast i32 i to float
8587   bool canMergeExpensiveCrossRegisterBankCopy() const {
8588     if (!Inst || !Inst->hasOneUse())
8589       return false;
8590     SDNode *Use = *Inst->use_begin();
8591     if (Use->getOpcode() != ISD::BITCAST)
8592       return false;
8593     assert(DAG && "Missing context");
8594     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8595     EVT ResVT = Use->getValueType(0);
8596     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8597     const TargetRegisterClass *ArgRC =
8598         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8599     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8600       return false;
8601
8602     // At this point, we know that we perform a cross-register-bank copy.
8603     // Check if it is expensive.
8604     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8605     // Assume bitcasts are cheap, unless both register classes do not
8606     // explicitly share a common sub class.
8607     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8608       return false;
8609
8610     // Check if it will be merged with the load.
8611     // 1. Check the alignment constraint.
8612     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8613         ResVT.getTypeForEVT(*DAG->getContext()));
8614
8615     if (RequiredAlignment > getAlignment())
8616       return false;
8617
8618     // 2. Check that the load is a legal operation for that type.
8619     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8620       return false;
8621
8622     // 3. Check that we do not have a zext in the way.
8623     if (Inst->getValueType(0) != getLoadedType())
8624       return false;
8625
8626     return true;
8627   }
8628 };
8629 }
8630
8631 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8632 /// \p UsedBits looks like 0..0 1..1 0..0.
8633 static bool areUsedBitsDense(const APInt &UsedBits) {
8634   // If all the bits are one, this is dense!
8635   if (UsedBits.isAllOnesValue())
8636     return true;
8637
8638   // Get rid of the unused bits on the right.
8639   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8640   // Get rid of the unused bits on the left.
8641   if (NarrowedUsedBits.countLeadingZeros())
8642     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8643   // Check that the chunk of bits is completely used.
8644   return NarrowedUsedBits.isAllOnesValue();
8645 }
8646
8647 /// \brief Check whether or not \p First and \p Second are next to each other
8648 /// in memory. This means that there is no hole between the bits loaded
8649 /// by \p First and the bits loaded by \p Second.
8650 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8651                                      const LoadedSlice &Second) {
8652   assert(First.Origin == Second.Origin && First.Origin &&
8653          "Unable to match different memory origins.");
8654   APInt UsedBits = First.getUsedBits();
8655   assert((UsedBits & Second.getUsedBits()) == 0 &&
8656          "Slices are not supposed to overlap.");
8657   UsedBits |= Second.getUsedBits();
8658   return areUsedBitsDense(UsedBits);
8659 }
8660
8661 /// \brief Adjust the \p GlobalLSCost according to the target
8662 /// paring capabilities and the layout of the slices.
8663 /// \pre \p GlobalLSCost should account for at least as many loads as
8664 /// there is in the slices in \p LoadedSlices.
8665 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8666                                  LoadedSlice::Cost &GlobalLSCost) {
8667   unsigned NumberOfSlices = LoadedSlices.size();
8668   // If there is less than 2 elements, no pairing is possible.
8669   if (NumberOfSlices < 2)
8670     return;
8671
8672   // Sort the slices so that elements that are likely to be next to each
8673   // other in memory are next to each other in the list.
8674   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8675             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8676     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8677     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8678   });
8679   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8680   // First (resp. Second) is the first (resp. Second) potentially candidate
8681   // to be placed in a paired load.
8682   const LoadedSlice *First = nullptr;
8683   const LoadedSlice *Second = nullptr;
8684   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8685                 // Set the beginning of the pair.
8686                                                            First = Second) {
8687
8688     Second = &LoadedSlices[CurrSlice];
8689
8690     // If First is NULL, it means we start a new pair.
8691     // Get to the next slice.
8692     if (!First)
8693       continue;
8694
8695     EVT LoadedType = First->getLoadedType();
8696
8697     // If the types of the slices are different, we cannot pair them.
8698     if (LoadedType != Second->getLoadedType())
8699       continue;
8700
8701     // Check if the target supplies paired loads for this type.
8702     unsigned RequiredAlignment = 0;
8703     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8704       // move to the next pair, this type is hopeless.
8705       Second = nullptr;
8706       continue;
8707     }
8708     // Check if we meet the alignment requirement.
8709     if (RequiredAlignment > First->getAlignment())
8710       continue;
8711
8712     // Check that both loads are next to each other in memory.
8713     if (!areSlicesNextToEachOther(*First, *Second))
8714       continue;
8715
8716     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8717     --GlobalLSCost.Loads;
8718     // Move to the next pair.
8719     Second = nullptr;
8720   }
8721 }
8722
8723 /// \brief Check the profitability of all involved LoadedSlice.
8724 /// Currently, it is considered profitable if there is exactly two
8725 /// involved slices (1) which are (2) next to each other in memory, and
8726 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8727 ///
8728 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8729 /// the elements themselves.
8730 ///
8731 /// FIXME: When the cost model will be mature enough, we can relax
8732 /// constraints (1) and (2).
8733 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8734                                 const APInt &UsedBits, bool ForCodeSize) {
8735   unsigned NumberOfSlices = LoadedSlices.size();
8736   if (StressLoadSlicing)
8737     return NumberOfSlices > 1;
8738
8739   // Check (1).
8740   if (NumberOfSlices != 2)
8741     return false;
8742
8743   // Check (2).
8744   if (!areUsedBitsDense(UsedBits))
8745     return false;
8746
8747   // Check (3).
8748   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8749   // The original code has one big load.
8750   OrigCost.Loads = 1;
8751   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8752     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8753     // Accumulate the cost of all the slices.
8754     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8755     GlobalSlicingCost += SliceCost;
8756
8757     // Account as cost in the original configuration the gain obtained
8758     // with the current slices.
8759     OrigCost.addSliceGain(LS);
8760   }
8761
8762   // If the target supports paired load, adjust the cost accordingly.
8763   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8764   return OrigCost > GlobalSlicingCost;
8765 }
8766
8767 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8768 /// operations, split it in the various pieces being extracted.
8769 ///
8770 /// This sort of thing is introduced by SROA.
8771 /// This slicing takes care not to insert overlapping loads.
8772 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8773 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8774   if (Level < AfterLegalizeDAG)
8775     return false;
8776
8777   LoadSDNode *LD = cast<LoadSDNode>(N);
8778   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8779       !LD->getValueType(0).isInteger())
8780     return false;
8781
8782   // Keep track of already used bits to detect overlapping values.
8783   // In that case, we will just abort the transformation.
8784   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8785
8786   SmallVector<LoadedSlice, 4> LoadedSlices;
8787
8788   // Check if this load is used as several smaller chunks of bits.
8789   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8790   // of computation for each trunc.
8791   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8792        UI != UIEnd; ++UI) {
8793     // Skip the uses of the chain.
8794     if (UI.getUse().getResNo() != 0)
8795       continue;
8796
8797     SDNode *User = *UI;
8798     unsigned Shift = 0;
8799
8800     // Check if this is a trunc(lshr).
8801     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8802         isa<ConstantSDNode>(User->getOperand(1))) {
8803       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8804       User = *User->use_begin();
8805     }
8806
8807     // At this point, User is a Truncate, iff we encountered, trunc or
8808     // trunc(lshr).
8809     if (User->getOpcode() != ISD::TRUNCATE)
8810       return false;
8811
8812     // The width of the type must be a power of 2 and greater than 8-bits.
8813     // Otherwise the load cannot be represented in LLVM IR.
8814     // Moreover, if we shifted with a non-8-bits multiple, the slice
8815     // will be across several bytes. We do not support that.
8816     unsigned Width = User->getValueSizeInBits(0);
8817     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8818       return 0;
8819
8820     // Build the slice for this chain of computations.
8821     LoadedSlice LS(User, LD, Shift, &DAG);
8822     APInt CurrentUsedBits = LS.getUsedBits();
8823
8824     // Check if this slice overlaps with another.
8825     if ((CurrentUsedBits & UsedBits) != 0)
8826       return false;
8827     // Update the bits used globally.
8828     UsedBits |= CurrentUsedBits;
8829
8830     // Check if the new slice would be legal.
8831     if (!LS.isLegal())
8832       return false;
8833
8834     // Record the slice.
8835     LoadedSlices.push_back(LS);
8836   }
8837
8838   // Abort slicing if it does not seem to be profitable.
8839   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8840     return false;
8841
8842   ++SlicedLoads;
8843
8844   // Rewrite each chain to use an independent load.
8845   // By construction, each chain can be represented by a unique load.
8846
8847   // Prepare the argument for the new token factor for all the slices.
8848   SmallVector<SDValue, 8> ArgChains;
8849   for (SmallVectorImpl<LoadedSlice>::const_iterator
8850            LSIt = LoadedSlices.begin(),
8851            LSItEnd = LoadedSlices.end();
8852        LSIt != LSItEnd; ++LSIt) {
8853     SDValue SliceInst = LSIt->loadSlice();
8854     CombineTo(LSIt->Inst, SliceInst, true);
8855     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8856       SliceInst = SliceInst.getOperand(0);
8857     assert(SliceInst->getOpcode() == ISD::LOAD &&
8858            "It takes more than a zext to get to the loaded slice!!");
8859     ArgChains.push_back(SliceInst.getValue(1));
8860   }
8861
8862   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8863                               ArgChains);
8864   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8865   return true;
8866 }
8867
8868 /// Check to see if V is (and load (ptr), imm), where the load is having
8869 /// specific bytes cleared out.  If so, return the byte size being masked out
8870 /// and the shift amount.
8871 static std::pair<unsigned, unsigned>
8872 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8873   std::pair<unsigned, unsigned> Result(0, 0);
8874
8875   // Check for the structure we're looking for.
8876   if (V->getOpcode() != ISD::AND ||
8877       !isa<ConstantSDNode>(V->getOperand(1)) ||
8878       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8879     return Result;
8880
8881   // Check the chain and pointer.
8882   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8883   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8884
8885   // The store should be chained directly to the load or be an operand of a
8886   // tokenfactor.
8887   if (LD == Chain.getNode())
8888     ; // ok.
8889   else if (Chain->getOpcode() != ISD::TokenFactor)
8890     return Result; // Fail.
8891   else {
8892     bool isOk = false;
8893     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8894       if (Chain->getOperand(i).getNode() == LD) {
8895         isOk = true;
8896         break;
8897       }
8898     if (!isOk) return Result;
8899   }
8900
8901   // This only handles simple types.
8902   if (V.getValueType() != MVT::i16 &&
8903       V.getValueType() != MVT::i32 &&
8904       V.getValueType() != MVT::i64)
8905     return Result;
8906
8907   // Check the constant mask.  Invert it so that the bits being masked out are
8908   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8909   // follow the sign bit for uniformity.
8910   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8911   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8912   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8913   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8914   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8915   if (NotMaskLZ == 64) return Result;  // All zero mask.
8916
8917   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8918   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8919     return Result;
8920
8921   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8922   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8923     NotMaskLZ -= 64-V.getValueSizeInBits();
8924
8925   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8926   switch (MaskedBytes) {
8927   case 1:
8928   case 2:
8929   case 4: break;
8930   default: return Result; // All one mask, or 5-byte mask.
8931   }
8932
8933   // Verify that the first bit starts at a multiple of mask so that the access
8934   // is aligned the same as the access width.
8935   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8936
8937   Result.first = MaskedBytes;
8938   Result.second = NotMaskTZ/8;
8939   return Result;
8940 }
8941
8942
8943 /// Check to see if IVal is something that provides a value as specified by
8944 /// MaskInfo. If so, replace the specified store with a narrower store of
8945 /// truncated IVal.
8946 static SDNode *
8947 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8948                                 SDValue IVal, StoreSDNode *St,
8949                                 DAGCombiner *DC) {
8950   unsigned NumBytes = MaskInfo.first;
8951   unsigned ByteShift = MaskInfo.second;
8952   SelectionDAG &DAG = DC->getDAG();
8953
8954   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8955   // that uses this.  If not, this is not a replacement.
8956   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8957                                   ByteShift*8, (ByteShift+NumBytes)*8);
8958   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8959
8960   // Check that it is legal on the target to do this.  It is legal if the new
8961   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8962   // legalization.
8963   MVT VT = MVT::getIntegerVT(NumBytes*8);
8964   if (!DC->isTypeLegal(VT))
8965     return nullptr;
8966
8967   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8968   // shifted by ByteShift and truncated down to NumBytes.
8969   if (ByteShift)
8970     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8971                        DAG.getConstant(ByteShift*8,
8972                                     DC->getShiftAmountTy(IVal.getValueType())));
8973
8974   // Figure out the offset for the store and the alignment of the access.
8975   unsigned StOffset;
8976   unsigned NewAlign = St->getAlignment();
8977
8978   if (DAG.getTargetLoweringInfo().isLittleEndian())
8979     StOffset = ByteShift;
8980   else
8981     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8982
8983   SDValue Ptr = St->getBasePtr();
8984   if (StOffset) {
8985     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8986                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8987     NewAlign = MinAlign(NewAlign, StOffset);
8988   }
8989
8990   // Truncate down to the new size.
8991   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8992
8993   ++OpsNarrowed;
8994   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8995                       St->getPointerInfo().getWithOffset(StOffset),
8996                       false, false, NewAlign).getNode();
8997 }
8998
8999
9000 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9001 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9002 /// narrowing the load and store if it would end up being a win for performance
9003 /// or code size.
9004 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9005   StoreSDNode *ST  = cast<StoreSDNode>(N);
9006   if (ST->isVolatile())
9007     return SDValue();
9008
9009   SDValue Chain = ST->getChain();
9010   SDValue Value = ST->getValue();
9011   SDValue Ptr   = ST->getBasePtr();
9012   EVT VT = Value.getValueType();
9013
9014   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9015     return SDValue();
9016
9017   unsigned Opc = Value.getOpcode();
9018
9019   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9020   // is a byte mask indicating a consecutive number of bytes, check to see if
9021   // Y is known to provide just those bytes.  If so, we try to replace the
9022   // load + replace + store sequence with a single (narrower) store, which makes
9023   // the load dead.
9024   if (Opc == ISD::OR) {
9025     std::pair<unsigned, unsigned> MaskedLoad;
9026     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9027     if (MaskedLoad.first)
9028       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9029                                                   Value.getOperand(1), ST,this))
9030         return SDValue(NewST, 0);
9031
9032     // Or is commutative, so try swapping X and Y.
9033     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9034     if (MaskedLoad.first)
9035       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9036                                                   Value.getOperand(0), ST,this))
9037         return SDValue(NewST, 0);
9038   }
9039
9040   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9041       Value.getOperand(1).getOpcode() != ISD::Constant)
9042     return SDValue();
9043
9044   SDValue N0 = Value.getOperand(0);
9045   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9046       Chain == SDValue(N0.getNode(), 1)) {
9047     LoadSDNode *LD = cast<LoadSDNode>(N0);
9048     if (LD->getBasePtr() != Ptr ||
9049         LD->getPointerInfo().getAddrSpace() !=
9050         ST->getPointerInfo().getAddrSpace())
9051       return SDValue();
9052
9053     // Find the type to narrow it the load / op / store to.
9054     SDValue N1 = Value.getOperand(1);
9055     unsigned BitWidth = N1.getValueSizeInBits();
9056     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9057     if (Opc == ISD::AND)
9058       Imm ^= APInt::getAllOnesValue(BitWidth);
9059     if (Imm == 0 || Imm.isAllOnesValue())
9060       return SDValue();
9061     unsigned ShAmt = Imm.countTrailingZeros();
9062     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9063     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9064     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9065     while (NewBW < BitWidth &&
9066            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9067              TLI.isNarrowingProfitable(VT, NewVT))) {
9068       NewBW = NextPowerOf2(NewBW);
9069       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9070     }
9071     if (NewBW >= BitWidth)
9072       return SDValue();
9073
9074     // If the lsb changed does not start at the type bitwidth boundary,
9075     // start at the previous one.
9076     if (ShAmt % NewBW)
9077       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9078     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9079                                    std::min(BitWidth, ShAmt + NewBW));
9080     if ((Imm & Mask) == Imm) {
9081       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9082       if (Opc == ISD::AND)
9083         NewImm ^= APInt::getAllOnesValue(NewBW);
9084       uint64_t PtrOff = ShAmt / 8;
9085       // For big endian targets, we need to adjust the offset to the pointer to
9086       // load the correct bytes.
9087       if (TLI.isBigEndian())
9088         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9089
9090       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9091       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9092       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9093         return SDValue();
9094
9095       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9096                                    Ptr.getValueType(), Ptr,
9097                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9098       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9099                                   LD->getChain(), NewPtr,
9100                                   LD->getPointerInfo().getWithOffset(PtrOff),
9101                                   LD->isVolatile(), LD->isNonTemporal(),
9102                                   LD->isInvariant(), NewAlign,
9103                                   LD->getAAInfo());
9104       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9105                                    DAG.getConstant(NewImm, NewVT));
9106       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9107                                    NewVal, NewPtr,
9108                                    ST->getPointerInfo().getWithOffset(PtrOff),
9109                                    false, false, NewAlign);
9110
9111       AddToWorklist(NewPtr.getNode());
9112       AddToWorklist(NewLD.getNode());
9113       AddToWorklist(NewVal.getNode());
9114       WorklistRemover DeadNodes(*this);
9115       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9116       ++OpsNarrowed;
9117       return NewST;
9118     }
9119   }
9120
9121   return SDValue();
9122 }
9123
9124 /// For a given floating point load / store pair, if the load value isn't used
9125 /// by any other operations, then consider transforming the pair to integer
9126 /// load / store operations if the target deems the transformation profitable.
9127 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9128   StoreSDNode *ST  = cast<StoreSDNode>(N);
9129   SDValue Chain = ST->getChain();
9130   SDValue Value = ST->getValue();
9131   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9132       Value.hasOneUse() &&
9133       Chain == SDValue(Value.getNode(), 1)) {
9134     LoadSDNode *LD = cast<LoadSDNode>(Value);
9135     EVT VT = LD->getMemoryVT();
9136     if (!VT.isFloatingPoint() ||
9137         VT != ST->getMemoryVT() ||
9138         LD->isNonTemporal() ||
9139         ST->isNonTemporal() ||
9140         LD->getPointerInfo().getAddrSpace() != 0 ||
9141         ST->getPointerInfo().getAddrSpace() != 0)
9142       return SDValue();
9143
9144     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9145     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9146         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9147         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9148         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9149       return SDValue();
9150
9151     unsigned LDAlign = LD->getAlignment();
9152     unsigned STAlign = ST->getAlignment();
9153     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9154     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9155     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9156       return SDValue();
9157
9158     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9159                                 LD->getChain(), LD->getBasePtr(),
9160                                 LD->getPointerInfo(),
9161                                 false, false, false, LDAlign);
9162
9163     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9164                                  NewLD, ST->getBasePtr(),
9165                                  ST->getPointerInfo(),
9166                                  false, false, STAlign);
9167
9168     AddToWorklist(NewLD.getNode());
9169     AddToWorklist(NewST.getNode());
9170     WorklistRemover DeadNodes(*this);
9171     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9172     ++LdStFP2Int;
9173     return NewST;
9174   }
9175
9176   return SDValue();
9177 }
9178
9179 /// Helper struct to parse and store a memory address as base + index + offset.
9180 /// We ignore sign extensions when it is safe to do so.
9181 /// The following two expressions are not equivalent. To differentiate we need
9182 /// to store whether there was a sign extension involved in the index
9183 /// computation.
9184 ///  (load (i64 add (i64 copyfromreg %c)
9185 ///                 (i64 signextend (add (i8 load %index)
9186 ///                                      (i8 1))))
9187 /// vs
9188 ///
9189 /// (load (i64 add (i64 copyfromreg %c)
9190 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9191 ///                                         (i32 1)))))
9192 struct BaseIndexOffset {
9193   SDValue Base;
9194   SDValue Index;
9195   int64_t Offset;
9196   bool IsIndexSignExt;
9197
9198   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9199
9200   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9201                   bool IsIndexSignExt) :
9202     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9203
9204   bool equalBaseIndex(const BaseIndexOffset &Other) {
9205     return Other.Base == Base && Other.Index == Index &&
9206       Other.IsIndexSignExt == IsIndexSignExt;
9207   }
9208
9209   /// Parses tree in Ptr for base, index, offset addresses.
9210   static BaseIndexOffset match(SDValue Ptr) {
9211     bool IsIndexSignExt = false;
9212
9213     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9214     // instruction, then it could be just the BASE or everything else we don't
9215     // know how to handle. Just use Ptr as BASE and give up.
9216     if (Ptr->getOpcode() != ISD::ADD)
9217       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9218
9219     // We know that we have at least an ADD instruction. Try to pattern match
9220     // the simple case of BASE + OFFSET.
9221     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9222       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9223       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9224                               IsIndexSignExt);
9225     }
9226
9227     // Inside a loop the current BASE pointer is calculated using an ADD and a
9228     // MUL instruction. In this case Ptr is the actual BASE pointer.
9229     // (i64 add (i64 %array_ptr)
9230     //          (i64 mul (i64 %induction_var)
9231     //                   (i64 %element_size)))
9232     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9233       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9234
9235     // Look at Base + Index + Offset cases.
9236     SDValue Base = Ptr->getOperand(0);
9237     SDValue IndexOffset = Ptr->getOperand(1);
9238
9239     // Skip signextends.
9240     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9241       IndexOffset = IndexOffset->getOperand(0);
9242       IsIndexSignExt = true;
9243     }
9244
9245     // Either the case of Base + Index (no offset) or something else.
9246     if (IndexOffset->getOpcode() != ISD::ADD)
9247       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9248
9249     // Now we have the case of Base + Index + offset.
9250     SDValue Index = IndexOffset->getOperand(0);
9251     SDValue Offset = IndexOffset->getOperand(1);
9252
9253     if (!isa<ConstantSDNode>(Offset))
9254       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9255
9256     // Ignore signextends.
9257     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9258       Index = Index->getOperand(0);
9259       IsIndexSignExt = true;
9260     } else IsIndexSignExt = false;
9261
9262     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9263     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9264   }
9265 };
9266
9267 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9268 /// is located in a sequence of memory operations connected by a chain.
9269 struct MemOpLink {
9270   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9271     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9272   // Ptr to the mem node.
9273   LSBaseSDNode *MemNode;
9274   // Offset from the base ptr.
9275   int64_t OffsetFromBase;
9276   // What is the sequence number of this mem node.
9277   // Lowest mem operand in the DAG starts at zero.
9278   unsigned SequenceNum;
9279 };
9280
9281 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9282   EVT MemVT = St->getMemoryVT();
9283   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9284   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9285     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9286
9287   // Don't merge vectors into wider inputs.
9288   if (MemVT.isVector() || !MemVT.isSimple())
9289     return false;
9290
9291   // Perform an early exit check. Do not bother looking at stored values that
9292   // are not constants or loads.
9293   SDValue StoredVal = St->getValue();
9294   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9295   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9296       !IsLoadSrc)
9297     return false;
9298
9299   // Only look at ends of store sequences.
9300   SDValue Chain = SDValue(St, 0);
9301   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9302     return false;
9303
9304   // This holds the base pointer, index, and the offset in bytes from the base
9305   // pointer.
9306   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9307
9308   // We must have a base and an offset.
9309   if (!BasePtr.Base.getNode())
9310     return false;
9311
9312   // Do not handle stores to undef base pointers.
9313   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9314     return false;
9315
9316   // Save the LoadSDNodes that we find in the chain.
9317   // We need to make sure that these nodes do not interfere with
9318   // any of the store nodes.
9319   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9320
9321   // Save the StoreSDNodes that we find in the chain.
9322   SmallVector<MemOpLink, 8> StoreNodes;
9323
9324   // Walk up the chain and look for nodes with offsets from the same
9325   // base pointer. Stop when reaching an instruction with a different kind
9326   // or instruction which has a different base pointer.
9327   unsigned Seq = 0;
9328   StoreSDNode *Index = St;
9329   while (Index) {
9330     // If the chain has more than one use, then we can't reorder the mem ops.
9331     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9332       break;
9333
9334     // Find the base pointer and offset for this memory node.
9335     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9336
9337     // Check that the base pointer is the same as the original one.
9338     if (!Ptr.equalBaseIndex(BasePtr))
9339       break;
9340
9341     // Check that the alignment is the same.
9342     if (Index->getAlignment() != St->getAlignment())
9343       break;
9344
9345     // The memory operands must not be volatile.
9346     if (Index->isVolatile() || Index->isIndexed())
9347       break;
9348
9349     // No truncation.
9350     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9351       if (St->isTruncatingStore())
9352         break;
9353
9354     // The stored memory type must be the same.
9355     if (Index->getMemoryVT() != MemVT)
9356       break;
9357
9358     // We do not allow unaligned stores because we want to prevent overriding
9359     // stores.
9360     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9361       break;
9362
9363     // We found a potential memory operand to merge.
9364     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9365
9366     // Find the next memory operand in the chain. If the next operand in the
9367     // chain is a store then move up and continue the scan with the next
9368     // memory operand. If the next operand is a load save it and use alias
9369     // information to check if it interferes with anything.
9370     SDNode *NextInChain = Index->getChain().getNode();
9371     while (1) {
9372       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9373         // We found a store node. Use it for the next iteration.
9374         Index = STn;
9375         break;
9376       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9377         if (Ldn->isVolatile()) {
9378           Index = nullptr;
9379           break;
9380         }
9381
9382         // Save the load node for later. Continue the scan.
9383         AliasLoadNodes.push_back(Ldn);
9384         NextInChain = Ldn->getChain().getNode();
9385         continue;
9386       } else {
9387         Index = nullptr;
9388         break;
9389       }
9390     }
9391   }
9392
9393   // Check if there is anything to merge.
9394   if (StoreNodes.size() < 2)
9395     return false;
9396
9397   // Sort the memory operands according to their distance from the base pointer.
9398   std::sort(StoreNodes.begin(), StoreNodes.end(),
9399             [](MemOpLink LHS, MemOpLink RHS) {
9400     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9401            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9402             LHS.SequenceNum > RHS.SequenceNum);
9403   });
9404
9405   // Scan the memory operations on the chain and find the first non-consecutive
9406   // store memory address.
9407   unsigned LastConsecutiveStore = 0;
9408   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9409   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9410
9411     // Check that the addresses are consecutive starting from the second
9412     // element in the list of stores.
9413     if (i > 0) {
9414       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9415       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9416         break;
9417     }
9418
9419     bool Alias = false;
9420     // Check if this store interferes with any of the loads that we found.
9421     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9422       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9423         Alias = true;
9424         break;
9425       }
9426     // We found a load that alias with this store. Stop the sequence.
9427     if (Alias)
9428       break;
9429
9430     // Mark this node as useful.
9431     LastConsecutiveStore = i;
9432   }
9433
9434   // The node with the lowest store address.
9435   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9436
9437   // Store the constants into memory as one consecutive store.
9438   if (!IsLoadSrc) {
9439     unsigned LastLegalType = 0;
9440     unsigned LastLegalVectorType = 0;
9441     bool NonZero = false;
9442     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9443       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9444       SDValue StoredVal = St->getValue();
9445
9446       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9447         NonZero |= !C->isNullValue();
9448       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9449         NonZero |= !C->getConstantFPValue()->isNullValue();
9450       } else {
9451         // Non-constant.
9452         break;
9453       }
9454
9455       // Find a legal type for the constant store.
9456       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9457       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9458       if (TLI.isTypeLegal(StoreTy))
9459         LastLegalType = i+1;
9460       // Or check whether a truncstore is legal.
9461       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9462                TargetLowering::TypePromoteInteger) {
9463         EVT LegalizedStoredValueTy =
9464           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9465         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9466           LastLegalType = i+1;
9467       }
9468
9469       // Find a legal type for the vector store.
9470       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9471       if (TLI.isTypeLegal(Ty))
9472         LastLegalVectorType = i + 1;
9473     }
9474
9475     // We only use vectors if the constant is known to be zero and the
9476     // function is not marked with the noimplicitfloat attribute.
9477     if (NonZero || NoVectors)
9478       LastLegalVectorType = 0;
9479
9480     // Check if we found a legal integer type to store.
9481     if (LastLegalType == 0 && LastLegalVectorType == 0)
9482       return false;
9483
9484     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9485     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9486
9487     // Make sure we have something to merge.
9488     if (NumElem < 2)
9489       return false;
9490
9491     unsigned EarliestNodeUsed = 0;
9492     for (unsigned i=0; i < NumElem; ++i) {
9493       // Find a chain for the new wide-store operand. Notice that some
9494       // of the store nodes that we found may not be selected for inclusion
9495       // in the wide store. The chain we use needs to be the chain of the
9496       // earliest store node which is *used* and replaced by the wide store.
9497       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9498         EarliestNodeUsed = i;
9499     }
9500
9501     // The earliest Node in the DAG.
9502     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9503     SDLoc DL(StoreNodes[0].MemNode);
9504
9505     SDValue StoredVal;
9506     if (UseVector) {
9507       // Find a legal type for the vector store.
9508       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9509       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9510       StoredVal = DAG.getConstant(0, Ty);
9511     } else {
9512       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9513       APInt StoreInt(StoreBW, 0);
9514
9515       // Construct a single integer constant which is made of the smaller
9516       // constant inputs.
9517       bool IsLE = TLI.isLittleEndian();
9518       for (unsigned i = 0; i < NumElem ; ++i) {
9519         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9520         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9521         SDValue Val = St->getValue();
9522         StoreInt<<=ElementSizeBytes*8;
9523         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9524           StoreInt|=C->getAPIntValue().zext(StoreBW);
9525         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9526           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9527         } else {
9528           assert(false && "Invalid constant element type");
9529         }
9530       }
9531
9532       // Create the new Load and Store operations.
9533       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9534       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9535     }
9536
9537     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9538                                     FirstInChain->getBasePtr(),
9539                                     FirstInChain->getPointerInfo(),
9540                                     false, false,
9541                                     FirstInChain->getAlignment());
9542
9543     // Replace the first store with the new store
9544     CombineTo(EarliestOp, NewStore);
9545     // Erase all other stores.
9546     for (unsigned i = 0; i < NumElem ; ++i) {
9547       if (StoreNodes[i].MemNode == EarliestOp)
9548         continue;
9549       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9550       // ReplaceAllUsesWith will replace all uses that existed when it was
9551       // called, but graph optimizations may cause new ones to appear. For
9552       // example, the case in pr14333 looks like
9553       //
9554       //  St's chain -> St -> another store -> X
9555       //
9556       // And the only difference from St to the other store is the chain.
9557       // When we change it's chain to be St's chain they become identical,
9558       // get CSEed and the net result is that X is now a use of St.
9559       // Since we know that St is redundant, just iterate.
9560       while (!St->use_empty())
9561         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9562       deleteAndRecombine(St);
9563     }
9564
9565     return true;
9566   }
9567
9568   // Below we handle the case of multiple consecutive stores that
9569   // come from multiple consecutive loads. We merge them into a single
9570   // wide load and a single wide store.
9571
9572   // Look for load nodes which are used by the stored values.
9573   SmallVector<MemOpLink, 8> LoadNodes;
9574
9575   // Find acceptable loads. Loads need to have the same chain (token factor),
9576   // must not be zext, volatile, indexed, and they must be consecutive.
9577   BaseIndexOffset LdBasePtr;
9578   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9579     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9580     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9581     if (!Ld) break;
9582
9583     // Loads must only have one use.
9584     if (!Ld->hasNUsesOfValue(1, 0))
9585       break;
9586
9587     // Check that the alignment is the same as the stores.
9588     if (Ld->getAlignment() != St->getAlignment())
9589       break;
9590
9591     // The memory operands must not be volatile.
9592     if (Ld->isVolatile() || Ld->isIndexed())
9593       break;
9594
9595     // We do not accept ext loads.
9596     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9597       break;
9598
9599     // The stored memory type must be the same.
9600     if (Ld->getMemoryVT() != MemVT)
9601       break;
9602
9603     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9604     // If this is not the first ptr that we check.
9605     if (LdBasePtr.Base.getNode()) {
9606       // The base ptr must be the same.
9607       if (!LdPtr.equalBaseIndex(LdBasePtr))
9608         break;
9609     } else {
9610       // Check that all other base pointers are the same as this one.
9611       LdBasePtr = LdPtr;
9612     }
9613
9614     // We found a potential memory operand to merge.
9615     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9616   }
9617
9618   if (LoadNodes.size() < 2)
9619     return false;
9620
9621   // If we have load/store pair instructions and we only have two values,
9622   // don't bother.
9623   unsigned RequiredAlignment;
9624   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9625       St->getAlignment() >= RequiredAlignment)
9626     return false;
9627
9628   // Scan the memory operations on the chain and find the first non-consecutive
9629   // load memory address. These variables hold the index in the store node
9630   // array.
9631   unsigned LastConsecutiveLoad = 0;
9632   // This variable refers to the size and not index in the array.
9633   unsigned LastLegalVectorType = 0;
9634   unsigned LastLegalIntegerType = 0;
9635   StartAddress = LoadNodes[0].OffsetFromBase;
9636   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9637   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9638     // All loads much share the same chain.
9639     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9640       break;
9641
9642     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9643     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9644       break;
9645     LastConsecutiveLoad = i;
9646
9647     // Find a legal type for the vector store.
9648     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9649     if (TLI.isTypeLegal(StoreTy))
9650       LastLegalVectorType = i + 1;
9651
9652     // Find a legal type for the integer store.
9653     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9654     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9655     if (TLI.isTypeLegal(StoreTy))
9656       LastLegalIntegerType = i + 1;
9657     // Or check whether a truncstore and extload is legal.
9658     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9659              TargetLowering::TypePromoteInteger) {
9660       EVT LegalizedStoredValueTy =
9661         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9662       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9663           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9664           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9665           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9666         LastLegalIntegerType = i+1;
9667     }
9668   }
9669
9670   // Only use vector types if the vector type is larger than the integer type.
9671   // If they are the same, use integers.
9672   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9673   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9674
9675   // We add +1 here because the LastXXX variables refer to location while
9676   // the NumElem refers to array/index size.
9677   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9678   NumElem = std::min(LastLegalType, NumElem);
9679
9680   if (NumElem < 2)
9681     return false;
9682
9683   // The earliest Node in the DAG.
9684   unsigned EarliestNodeUsed = 0;
9685   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9686   for (unsigned i=1; i<NumElem; ++i) {
9687     // Find a chain for the new wide-store operand. Notice that some
9688     // of the store nodes that we found may not be selected for inclusion
9689     // in the wide store. The chain we use needs to be the chain of the
9690     // earliest store node which is *used* and replaced by the wide store.
9691     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9692       EarliestNodeUsed = i;
9693   }
9694
9695   // Find if it is better to use vectors or integers to load and store
9696   // to memory.
9697   EVT JointMemOpVT;
9698   if (UseVectorTy) {
9699     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9700   } else {
9701     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9702     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9703   }
9704
9705   SDLoc LoadDL(LoadNodes[0].MemNode);
9706   SDLoc StoreDL(StoreNodes[0].MemNode);
9707
9708   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9709   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9710                                 FirstLoad->getChain(),
9711                                 FirstLoad->getBasePtr(),
9712                                 FirstLoad->getPointerInfo(),
9713                                 false, false, false,
9714                                 FirstLoad->getAlignment());
9715
9716   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9717                                   FirstInChain->getBasePtr(),
9718                                   FirstInChain->getPointerInfo(), false, false,
9719                                   FirstInChain->getAlignment());
9720
9721   // Replace one of the loads with the new load.
9722   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9723   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9724                                 SDValue(NewLoad.getNode(), 1));
9725
9726   // Remove the rest of the load chains.
9727   for (unsigned i = 1; i < NumElem ; ++i) {
9728     // Replace all chain users of the old load nodes with the chain of the new
9729     // load node.
9730     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9731     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9732   }
9733
9734   // Replace the first store with the new store.
9735   CombineTo(EarliestOp, NewStore);
9736   // Erase all other stores.
9737   for (unsigned i = 0; i < NumElem ; ++i) {
9738     // Remove all Store nodes.
9739     if (StoreNodes[i].MemNode == EarliestOp)
9740       continue;
9741     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9742     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9743     deleteAndRecombine(St);
9744   }
9745
9746   return true;
9747 }
9748
9749 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9750   StoreSDNode *ST  = cast<StoreSDNode>(N);
9751   SDValue Chain = ST->getChain();
9752   SDValue Value = ST->getValue();
9753   SDValue Ptr   = ST->getBasePtr();
9754
9755   // If this is a store of a bit convert, store the input value if the
9756   // resultant store does not need a higher alignment than the original.
9757   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9758       ST->isUnindexed()) {
9759     unsigned OrigAlign = ST->getAlignment();
9760     EVT SVT = Value.getOperand(0).getValueType();
9761     unsigned Align = TLI.getDataLayout()->
9762       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9763     if (Align <= OrigAlign &&
9764         ((!LegalOperations && !ST->isVolatile()) ||
9765          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9766       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9767                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9768                           ST->isNonTemporal(), OrigAlign,
9769                           ST->getAAInfo());
9770   }
9771
9772   // Turn 'store undef, Ptr' -> nothing.
9773   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9774     return Chain;
9775
9776   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9777   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9778     // NOTE: If the original store is volatile, this transform must not increase
9779     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9780     // processor operation but an i64 (which is not legal) requires two.  So the
9781     // transform should not be done in this case.
9782     if (Value.getOpcode() != ISD::TargetConstantFP) {
9783       SDValue Tmp;
9784       switch (CFP->getSimpleValueType(0).SimpleTy) {
9785       default: llvm_unreachable("Unknown FP type");
9786       case MVT::f16:    // We don't do this for these yet.
9787       case MVT::f80:
9788       case MVT::f128:
9789       case MVT::ppcf128:
9790         break;
9791       case MVT::f32:
9792         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9793             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9794           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9795                               bitcastToAPInt().getZExtValue(), MVT::i32);
9796           return DAG.getStore(Chain, SDLoc(N), Tmp,
9797                               Ptr, ST->getMemOperand());
9798         }
9799         break;
9800       case MVT::f64:
9801         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9802              !ST->isVolatile()) ||
9803             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9804           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9805                                 getZExtValue(), MVT::i64);
9806           return DAG.getStore(Chain, SDLoc(N), Tmp,
9807                               Ptr, ST->getMemOperand());
9808         }
9809
9810         if (!ST->isVolatile() &&
9811             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9812           // Many FP stores are not made apparent until after legalize, e.g. for
9813           // argument passing.  Since this is so common, custom legalize the
9814           // 64-bit integer store into two 32-bit stores.
9815           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9816           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9817           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9818           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9819
9820           unsigned Alignment = ST->getAlignment();
9821           bool isVolatile = ST->isVolatile();
9822           bool isNonTemporal = ST->isNonTemporal();
9823           AAMDNodes AAInfo = ST->getAAInfo();
9824
9825           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9826                                      Ptr, ST->getPointerInfo(),
9827                                      isVolatile, isNonTemporal,
9828                                      ST->getAlignment(), AAInfo);
9829           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9830                             DAG.getConstant(4, Ptr.getValueType()));
9831           Alignment = MinAlign(Alignment, 4U);
9832           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9833                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9834                                      isVolatile, isNonTemporal,
9835                                      Alignment, AAInfo);
9836           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9837                              St0, St1);
9838         }
9839
9840         break;
9841       }
9842     }
9843   }
9844
9845   // Try to infer better alignment information than the store already has.
9846   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9847     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9848       if (Align > ST->getAlignment())
9849         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9850                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9851                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9852                                  ST->getAAInfo());
9853     }
9854   }
9855
9856   // Try transforming a pair floating point load / store ops to integer
9857   // load / store ops.
9858   SDValue NewST = TransformFPLoadStorePair(N);
9859   if (NewST.getNode())
9860     return NewST;
9861
9862   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9863                                                   : DAG.getSubtarget().useAA();
9864 #ifndef NDEBUG
9865   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9866       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9867     UseAA = false;
9868 #endif
9869   if (UseAA && ST->isUnindexed()) {
9870     // Walk up chain skipping non-aliasing memory nodes.
9871     SDValue BetterChain = FindBetterChain(N, Chain);
9872
9873     // If there is a better chain.
9874     if (Chain != BetterChain) {
9875       SDValue ReplStore;
9876
9877       // Replace the chain to avoid dependency.
9878       if (ST->isTruncatingStore()) {
9879         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9880                                       ST->getMemoryVT(), ST->getMemOperand());
9881       } else {
9882         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9883                                  ST->getMemOperand());
9884       }
9885
9886       // Create token to keep both nodes around.
9887       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9888                                   MVT::Other, Chain, ReplStore);
9889
9890       // Make sure the new and old chains are cleaned up.
9891       AddToWorklist(Token.getNode());
9892
9893       // Don't add users to work list.
9894       return CombineTo(N, Token, false);
9895     }
9896   }
9897
9898   // Try transforming N to an indexed store.
9899   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9900     return SDValue(N, 0);
9901
9902   // FIXME: is there such a thing as a truncating indexed store?
9903   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9904       Value.getValueType().isInteger()) {
9905     // See if we can simplify the input to this truncstore with knowledge that
9906     // only the low bits are being used.  For example:
9907     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9908     SDValue Shorter =
9909       GetDemandedBits(Value,
9910                       APInt::getLowBitsSet(
9911                         Value.getValueType().getScalarType().getSizeInBits(),
9912                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9913     AddToWorklist(Value.getNode());
9914     if (Shorter.getNode())
9915       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9916                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9917
9918     // Otherwise, see if we can simplify the operation with
9919     // SimplifyDemandedBits, which only works if the value has a single use.
9920     if (SimplifyDemandedBits(Value,
9921                         APInt::getLowBitsSet(
9922                           Value.getValueType().getScalarType().getSizeInBits(),
9923                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9924       return SDValue(N, 0);
9925   }
9926
9927   // If this is a load followed by a store to the same location, then the store
9928   // is dead/noop.
9929   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9930     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9931         ST->isUnindexed() && !ST->isVolatile() &&
9932         // There can't be any side effects between the load and store, such as
9933         // a call or store.
9934         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9935       // The store is dead, remove it.
9936       return Chain;
9937     }
9938   }
9939
9940   // If this is a store followed by a store with the same value to the same
9941   // location, then the store is dead/noop.
9942   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9943     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9944         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9945         ST1->isUnindexed() && !ST1->isVolatile()) {
9946       // The store is dead, remove it.
9947       return Chain;
9948     }
9949   }
9950
9951   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9952   // truncating store.  We can do this even if this is already a truncstore.
9953   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9954       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9955       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9956                             ST->getMemoryVT())) {
9957     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9958                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9959   }
9960
9961   // Only perform this optimization before the types are legal, because we
9962   // don't want to perform this optimization on every DAGCombine invocation.
9963   if (!LegalTypes) {
9964     bool EverChanged = false;
9965
9966     do {
9967       // There can be multiple store sequences on the same chain.
9968       // Keep trying to merge store sequences until we are unable to do so
9969       // or until we merge the last store on the chain.
9970       bool Changed = MergeConsecutiveStores(ST);
9971       EverChanged |= Changed;
9972       if (!Changed) break;
9973     } while (ST->getOpcode() != ISD::DELETED_NODE);
9974
9975     if (EverChanged)
9976       return SDValue(N, 0);
9977   }
9978
9979   return ReduceLoadOpStoreWidth(N);
9980 }
9981
9982 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9983   SDValue InVec = N->getOperand(0);
9984   SDValue InVal = N->getOperand(1);
9985   SDValue EltNo = N->getOperand(2);
9986   SDLoc dl(N);
9987
9988   // If the inserted element is an UNDEF, just use the input vector.
9989   if (InVal.getOpcode() == ISD::UNDEF)
9990     return InVec;
9991
9992   EVT VT = InVec.getValueType();
9993
9994   // If we can't generate a legal BUILD_VECTOR, exit
9995   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9996     return SDValue();
9997
9998   // Check that we know which element is being inserted
9999   if (!isa<ConstantSDNode>(EltNo))
10000     return SDValue();
10001   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10002
10003   // Canonicalize insert_vector_elt dag nodes.
10004   // Example:
10005   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10006   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10007   //
10008   // Do this only if the child insert_vector node has one use; also
10009   // do this only if indices are both constants and Idx1 < Idx0.
10010   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10011       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10012     unsigned OtherElt =
10013       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10014     if (Elt < OtherElt) {
10015       // Swap nodes.
10016       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10017                                   InVec.getOperand(0), InVal, EltNo);
10018       AddToWorklist(NewOp.getNode());
10019       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10020                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10021     }
10022   }
10023
10024   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10025   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10026   // vector elements.
10027   SmallVector<SDValue, 8> Ops;
10028   // Do not combine these two vectors if the output vector will not replace
10029   // the input vector.
10030   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10031     Ops.append(InVec.getNode()->op_begin(),
10032                InVec.getNode()->op_end());
10033   } else if (InVec.getOpcode() == ISD::UNDEF) {
10034     unsigned NElts = VT.getVectorNumElements();
10035     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10036   } else {
10037     return SDValue();
10038   }
10039
10040   // Insert the element
10041   if (Elt < Ops.size()) {
10042     // All the operands of BUILD_VECTOR must have the same type;
10043     // we enforce that here.
10044     EVT OpVT = Ops[0].getValueType();
10045     if (InVal.getValueType() != OpVT)
10046       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10047                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10048                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10049     Ops[Elt] = InVal;
10050   }
10051
10052   // Return the new vector
10053   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10054 }
10055
10056 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10057     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10058   EVT ResultVT = EVE->getValueType(0);
10059   EVT VecEltVT = InVecVT.getVectorElementType();
10060   unsigned Align = OriginalLoad->getAlignment();
10061   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10062       VecEltVT.getTypeForEVT(*DAG.getContext()));
10063
10064   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10065     return SDValue();
10066
10067   Align = NewAlign;
10068
10069   SDValue NewPtr = OriginalLoad->getBasePtr();
10070   SDValue Offset;
10071   EVT PtrType = NewPtr.getValueType();
10072   MachinePointerInfo MPI;
10073   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10074     int Elt = ConstEltNo->getZExtValue();
10075     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10076     if (TLI.isBigEndian())
10077       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10078     Offset = DAG.getConstant(PtrOff, PtrType);
10079     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10080   } else {
10081     Offset = DAG.getNode(
10082         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10083         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10084     if (TLI.isBigEndian())
10085       Offset = DAG.getNode(
10086           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10087           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10088     MPI = OriginalLoad->getPointerInfo();
10089   }
10090   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10091
10092   // The replacement we need to do here is a little tricky: we need to
10093   // replace an extractelement of a load with a load.
10094   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10095   // Note that this replacement assumes that the extractvalue is the only
10096   // use of the load; that's okay because we don't want to perform this
10097   // transformation in other cases anyway.
10098   SDValue Load;
10099   SDValue Chain;
10100   if (ResultVT.bitsGT(VecEltVT)) {
10101     // If the result type of vextract is wider than the load, then issue an
10102     // extending load instead.
10103     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10104                                    ? ISD::ZEXTLOAD
10105                                    : ISD::EXTLOAD;
10106     Load = DAG.getExtLoad(
10107         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10108         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10109         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10110     Chain = Load.getValue(1);
10111   } else {
10112     Load = DAG.getLoad(
10113         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10114         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10115         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10116     Chain = Load.getValue(1);
10117     if (ResultVT.bitsLT(VecEltVT))
10118       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10119     else
10120       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10121   }
10122   WorklistRemover DeadNodes(*this);
10123   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10124   SDValue To[] = { Load, Chain };
10125   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10126   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10127   // worklist explicitly as well.
10128   AddToWorklist(Load.getNode());
10129   AddUsersToWorklist(Load.getNode()); // Add users too
10130   // Make sure to revisit this node to clean it up; it will usually be dead.
10131   AddToWorklist(EVE);
10132   ++OpsNarrowed;
10133   return SDValue(EVE, 0);
10134 }
10135
10136 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10137   // (vextract (scalar_to_vector val, 0) -> val
10138   SDValue InVec = N->getOperand(0);
10139   EVT VT = InVec.getValueType();
10140   EVT NVT = N->getValueType(0);
10141
10142   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10143     // Check if the result type doesn't match the inserted element type. A
10144     // SCALAR_TO_VECTOR may truncate the inserted element and the
10145     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10146     SDValue InOp = InVec.getOperand(0);
10147     if (InOp.getValueType() != NVT) {
10148       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10149       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10150     }
10151     return InOp;
10152   }
10153
10154   SDValue EltNo = N->getOperand(1);
10155   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10156
10157   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10158   // We only perform this optimization before the op legalization phase because
10159   // we may introduce new vector instructions which are not backed by TD
10160   // patterns. For example on AVX, extracting elements from a wide vector
10161   // without using extract_subvector. However, if we can find an underlying
10162   // scalar value, then we can always use that.
10163   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10164       && ConstEltNo) {
10165     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10166     int NumElem = VT.getVectorNumElements();
10167     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10168     // Find the new index to extract from.
10169     int OrigElt = SVOp->getMaskElt(Elt);
10170
10171     // Extracting an undef index is undef.
10172     if (OrigElt == -1)
10173       return DAG.getUNDEF(NVT);
10174
10175     // Select the right vector half to extract from.
10176     SDValue SVInVec;
10177     if (OrigElt < NumElem) {
10178       SVInVec = InVec->getOperand(0);
10179     } else {
10180       SVInVec = InVec->getOperand(1);
10181       OrigElt -= NumElem;
10182     }
10183
10184     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10185       SDValue InOp = SVInVec.getOperand(OrigElt);
10186       if (InOp.getValueType() != NVT) {
10187         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10188         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10189       }
10190
10191       return InOp;
10192     }
10193
10194     // FIXME: We should handle recursing on other vector shuffles and
10195     // scalar_to_vector here as well.
10196
10197     if (!LegalOperations) {
10198       EVT IndexTy = TLI.getVectorIdxTy();
10199       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10200                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10201     }
10202   }
10203
10204   bool BCNumEltsChanged = false;
10205   EVT ExtVT = VT.getVectorElementType();
10206   EVT LVT = ExtVT;
10207
10208   // If the result of load has to be truncated, then it's not necessarily
10209   // profitable.
10210   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10211     return SDValue();
10212
10213   if (InVec.getOpcode() == ISD::BITCAST) {
10214     // Don't duplicate a load with other uses.
10215     if (!InVec.hasOneUse())
10216       return SDValue();
10217
10218     EVT BCVT = InVec.getOperand(0).getValueType();
10219     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10220       return SDValue();
10221     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10222       BCNumEltsChanged = true;
10223     InVec = InVec.getOperand(0);
10224     ExtVT = BCVT.getVectorElementType();
10225   }
10226
10227   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10228   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10229       ISD::isNormalLoad(InVec.getNode()) &&
10230       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10231     SDValue Index = N->getOperand(1);
10232     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10233       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10234                                                            OrigLoad);
10235   }
10236
10237   // Perform only after legalization to ensure build_vector / vector_shuffle
10238   // optimizations have already been done.
10239   if (!LegalOperations) return SDValue();
10240
10241   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10242   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10243   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10244
10245   if (ConstEltNo) {
10246     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10247
10248     LoadSDNode *LN0 = nullptr;
10249     const ShuffleVectorSDNode *SVN = nullptr;
10250     if (ISD::isNormalLoad(InVec.getNode())) {
10251       LN0 = cast<LoadSDNode>(InVec);
10252     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10253                InVec.getOperand(0).getValueType() == ExtVT &&
10254                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10255       // Don't duplicate a load with other uses.
10256       if (!InVec.hasOneUse())
10257         return SDValue();
10258
10259       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10260     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10261       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10262       // =>
10263       // (load $addr+1*size)
10264
10265       // Don't duplicate a load with other uses.
10266       if (!InVec.hasOneUse())
10267         return SDValue();
10268
10269       // If the bit convert changed the number of elements, it is unsafe
10270       // to examine the mask.
10271       if (BCNumEltsChanged)
10272         return SDValue();
10273
10274       // Select the input vector, guarding against out of range extract vector.
10275       unsigned NumElems = VT.getVectorNumElements();
10276       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10277       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10278
10279       if (InVec.getOpcode() == ISD::BITCAST) {
10280         // Don't duplicate a load with other uses.
10281         if (!InVec.hasOneUse())
10282           return SDValue();
10283
10284         InVec = InVec.getOperand(0);
10285       }
10286       if (ISD::isNormalLoad(InVec.getNode())) {
10287         LN0 = cast<LoadSDNode>(InVec);
10288         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10289         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10290       }
10291     }
10292
10293     // Make sure we found a non-volatile load and the extractelement is
10294     // the only use.
10295     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10296       return SDValue();
10297
10298     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10299     if (Elt == -1)
10300       return DAG.getUNDEF(LVT);
10301
10302     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10303   }
10304
10305   return SDValue();
10306 }
10307
10308 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10309 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10310   // We perform this optimization post type-legalization because
10311   // the type-legalizer often scalarizes integer-promoted vectors.
10312   // Performing this optimization before may create bit-casts which
10313   // will be type-legalized to complex code sequences.
10314   // We perform this optimization only before the operation legalizer because we
10315   // may introduce illegal operations.
10316   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10317     return SDValue();
10318
10319   unsigned NumInScalars = N->getNumOperands();
10320   SDLoc dl(N);
10321   EVT VT = N->getValueType(0);
10322
10323   // Check to see if this is a BUILD_VECTOR of a bunch of values
10324   // which come from any_extend or zero_extend nodes. If so, we can create
10325   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10326   // optimizations. We do not handle sign-extend because we can't fill the sign
10327   // using shuffles.
10328   EVT SourceType = MVT::Other;
10329   bool AllAnyExt = true;
10330
10331   for (unsigned i = 0; i != NumInScalars; ++i) {
10332     SDValue In = N->getOperand(i);
10333     // Ignore undef inputs.
10334     if (In.getOpcode() == ISD::UNDEF) continue;
10335
10336     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10337     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10338
10339     // Abort if the element is not an extension.
10340     if (!ZeroExt && !AnyExt) {
10341       SourceType = MVT::Other;
10342       break;
10343     }
10344
10345     // The input is a ZeroExt or AnyExt. Check the original type.
10346     EVT InTy = In.getOperand(0).getValueType();
10347
10348     // Check that all of the widened source types are the same.
10349     if (SourceType == MVT::Other)
10350       // First time.
10351       SourceType = InTy;
10352     else if (InTy != SourceType) {
10353       // Multiple income types. Abort.
10354       SourceType = MVT::Other;
10355       break;
10356     }
10357
10358     // Check if all of the extends are ANY_EXTENDs.
10359     AllAnyExt &= AnyExt;
10360   }
10361
10362   // In order to have valid types, all of the inputs must be extended from the
10363   // same source type and all of the inputs must be any or zero extend.
10364   // Scalar sizes must be a power of two.
10365   EVT OutScalarTy = VT.getScalarType();
10366   bool ValidTypes = SourceType != MVT::Other &&
10367                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10368                  isPowerOf2_32(SourceType.getSizeInBits());
10369
10370   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10371   // turn into a single shuffle instruction.
10372   if (!ValidTypes)
10373     return SDValue();
10374
10375   bool isLE = TLI.isLittleEndian();
10376   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10377   assert(ElemRatio > 1 && "Invalid element size ratio");
10378   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10379                                DAG.getConstant(0, SourceType);
10380
10381   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10382   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10383
10384   // Populate the new build_vector
10385   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10386     SDValue Cast = N->getOperand(i);
10387     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10388             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10389             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10390     SDValue In;
10391     if (Cast.getOpcode() == ISD::UNDEF)
10392       In = DAG.getUNDEF(SourceType);
10393     else
10394       In = Cast->getOperand(0);
10395     unsigned Index = isLE ? (i * ElemRatio) :
10396                             (i * ElemRatio + (ElemRatio - 1));
10397
10398     assert(Index < Ops.size() && "Invalid index");
10399     Ops[Index] = In;
10400   }
10401
10402   // The type of the new BUILD_VECTOR node.
10403   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10404   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10405          "Invalid vector size");
10406   // Check if the new vector type is legal.
10407   if (!isTypeLegal(VecVT)) return SDValue();
10408
10409   // Make the new BUILD_VECTOR.
10410   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10411
10412   // The new BUILD_VECTOR node has the potential to be further optimized.
10413   AddToWorklist(BV.getNode());
10414   // Bitcast to the desired type.
10415   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10416 }
10417
10418 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10419   EVT VT = N->getValueType(0);
10420
10421   unsigned NumInScalars = N->getNumOperands();
10422   SDLoc dl(N);
10423
10424   EVT SrcVT = MVT::Other;
10425   unsigned Opcode = ISD::DELETED_NODE;
10426   unsigned NumDefs = 0;
10427
10428   for (unsigned i = 0; i != NumInScalars; ++i) {
10429     SDValue In = N->getOperand(i);
10430     unsigned Opc = In.getOpcode();
10431
10432     if (Opc == ISD::UNDEF)
10433       continue;
10434
10435     // If all scalar values are floats and converted from integers.
10436     if (Opcode == ISD::DELETED_NODE &&
10437         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10438       Opcode = Opc;
10439     }
10440
10441     if (Opc != Opcode)
10442       return SDValue();
10443
10444     EVT InVT = In.getOperand(0).getValueType();
10445
10446     // If all scalar values are typed differently, bail out. It's chosen to
10447     // simplify BUILD_VECTOR of integer types.
10448     if (SrcVT == MVT::Other)
10449       SrcVT = InVT;
10450     if (SrcVT != InVT)
10451       return SDValue();
10452     NumDefs++;
10453   }
10454
10455   // If the vector has just one element defined, it's not worth to fold it into
10456   // a vectorized one.
10457   if (NumDefs < 2)
10458     return SDValue();
10459
10460   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10461          && "Should only handle conversion from integer to float.");
10462   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10463
10464   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10465
10466   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10467     return SDValue();
10468
10469   SmallVector<SDValue, 8> Opnds;
10470   for (unsigned i = 0; i != NumInScalars; ++i) {
10471     SDValue In = N->getOperand(i);
10472
10473     if (In.getOpcode() == ISD::UNDEF)
10474       Opnds.push_back(DAG.getUNDEF(SrcVT));
10475     else
10476       Opnds.push_back(In.getOperand(0));
10477   }
10478   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10479   AddToWorklist(BV.getNode());
10480
10481   return DAG.getNode(Opcode, dl, VT, BV);
10482 }
10483
10484 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10485   unsigned NumInScalars = N->getNumOperands();
10486   SDLoc dl(N);
10487   EVT VT = N->getValueType(0);
10488
10489   // A vector built entirely of undefs is undef.
10490   if (ISD::allOperandsUndef(N))
10491     return DAG.getUNDEF(VT);
10492
10493   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10494   if (V.getNode())
10495     return V;
10496
10497   V = reduceBuildVecConvertToConvertBuildVec(N);
10498   if (V.getNode())
10499     return V;
10500
10501   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10502   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10503   // at most two distinct vectors, turn this into a shuffle node.
10504
10505   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10506   if (!isTypeLegal(VT))
10507     return SDValue();
10508
10509   // May only combine to shuffle after legalize if shuffle is legal.
10510   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10511     return SDValue();
10512
10513   SDValue VecIn1, VecIn2;
10514   for (unsigned i = 0; i != NumInScalars; ++i) {
10515     // Ignore undef inputs.
10516     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10517
10518     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10519     // constant index, bail out.
10520     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10521         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10522       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10523       break;
10524     }
10525
10526     // We allow up to two distinct input vectors.
10527     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10528     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10529       continue;
10530
10531     if (!VecIn1.getNode()) {
10532       VecIn1 = ExtractedFromVec;
10533     } else if (!VecIn2.getNode()) {
10534       VecIn2 = ExtractedFromVec;
10535     } else {
10536       // Too many inputs.
10537       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10538       break;
10539     }
10540   }
10541
10542   // If everything is good, we can make a shuffle operation.
10543   if (VecIn1.getNode()) {
10544     SmallVector<int, 8> Mask;
10545     for (unsigned i = 0; i != NumInScalars; ++i) {
10546       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10547         Mask.push_back(-1);
10548         continue;
10549       }
10550
10551       // If extracting from the first vector, just use the index directly.
10552       SDValue Extract = N->getOperand(i);
10553       SDValue ExtVal = Extract.getOperand(1);
10554       if (Extract.getOperand(0) == VecIn1) {
10555         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10556         if (ExtIndex > VT.getVectorNumElements())
10557           return SDValue();
10558
10559         Mask.push_back(ExtIndex);
10560         continue;
10561       }
10562
10563       // Otherwise, use InIdx + VecSize
10564       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10565       Mask.push_back(Idx+NumInScalars);
10566     }
10567
10568     // We can't generate a shuffle node with mismatched input and output types.
10569     // Attempt to transform a single input vector to the correct type.
10570     if ((VT != VecIn1.getValueType())) {
10571       // We don't support shuffeling between TWO values of different types.
10572       if (VecIn2.getNode())
10573         return SDValue();
10574
10575       // We only support widening of vectors which are half the size of the
10576       // output registers. For example XMM->YMM widening on X86 with AVX.
10577       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10578         return SDValue();
10579
10580       // If the input vector type has a different base type to the output
10581       // vector type, bail out.
10582       if (VecIn1.getValueType().getVectorElementType() !=
10583           VT.getVectorElementType())
10584         return SDValue();
10585
10586       // Widen the input vector by adding undef values.
10587       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10588                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10589     }
10590
10591     // If VecIn2 is unused then change it to undef.
10592     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10593
10594     // Check that we were able to transform all incoming values to the same
10595     // type.
10596     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10597         VecIn1.getValueType() != VT)
10598           return SDValue();
10599
10600     // Return the new VECTOR_SHUFFLE node.
10601     SDValue Ops[2];
10602     Ops[0] = VecIn1;
10603     Ops[1] = VecIn2;
10604     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10605   }
10606
10607   return SDValue();
10608 }
10609
10610 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10611   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10612   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10613   // inputs come from at most two distinct vectors, turn this into a shuffle
10614   // node.
10615
10616   // If we only have one input vector, we don't need to do any concatenation.
10617   if (N->getNumOperands() == 1)
10618     return N->getOperand(0);
10619
10620   // Check if all of the operands are undefs.
10621   EVT VT = N->getValueType(0);
10622   if (ISD::allOperandsUndef(N))
10623     return DAG.getUNDEF(VT);
10624
10625   // Optimize concat_vectors where one of the vectors is undef.
10626   if (N->getNumOperands() == 2 &&
10627       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10628     SDValue In = N->getOperand(0);
10629     assert(In.getValueType().isVector() && "Must concat vectors");
10630
10631     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10632     if (In->getOpcode() == ISD::BITCAST &&
10633         !In->getOperand(0)->getValueType(0).isVector()) {
10634       SDValue Scalar = In->getOperand(0);
10635       EVT SclTy = Scalar->getValueType(0);
10636
10637       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10638         return SDValue();
10639
10640       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10641                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10642       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10643         return SDValue();
10644
10645       SDLoc dl = SDLoc(N);
10646       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10647       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10648     }
10649   }
10650
10651   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10652   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10653   if (N->getNumOperands() == 2 &&
10654       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10655       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10656     EVT VT = N->getValueType(0);
10657     SDValue N0 = N->getOperand(0);
10658     SDValue N1 = N->getOperand(1);
10659     SmallVector<SDValue, 8> Opnds;
10660     unsigned BuildVecNumElts =  N0.getNumOperands();
10661
10662     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10663     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10664     if (SclTy0.isFloatingPoint()) {
10665       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10666         Opnds.push_back(N0.getOperand(i));
10667       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10668         Opnds.push_back(N1.getOperand(i));
10669     } else {
10670       // If BUILD_VECTOR are from built from integer, they may have different
10671       // operand types. Get the smaller type and truncate all operands to it.
10672       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10673       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10674         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10675                         N0.getOperand(i)));
10676       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10677         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10678                         N1.getOperand(i)));
10679     }
10680
10681     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10682   }
10683
10684   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10685   // nodes often generate nop CONCAT_VECTOR nodes.
10686   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10687   // place the incoming vectors at the exact same location.
10688   SDValue SingleSource = SDValue();
10689   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10690
10691   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10692     SDValue Op = N->getOperand(i);
10693
10694     if (Op.getOpcode() == ISD::UNDEF)
10695       continue;
10696
10697     // Check if this is the identity extract:
10698     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10699       return SDValue();
10700
10701     // Find the single incoming vector for the extract_subvector.
10702     if (SingleSource.getNode()) {
10703       if (Op.getOperand(0) != SingleSource)
10704         return SDValue();
10705     } else {
10706       SingleSource = Op.getOperand(0);
10707
10708       // Check the source type is the same as the type of the result.
10709       // If not, this concat may extend the vector, so we can not
10710       // optimize it away.
10711       if (SingleSource.getValueType() != N->getValueType(0))
10712         return SDValue();
10713     }
10714
10715     unsigned IdentityIndex = i * PartNumElem;
10716     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10717     // The extract index must be constant.
10718     if (!CS)
10719       return SDValue();
10720
10721     // Check that we are reading from the identity index.
10722     if (CS->getZExtValue() != IdentityIndex)
10723       return SDValue();
10724   }
10725
10726   if (SingleSource.getNode())
10727     return SingleSource;
10728
10729   return SDValue();
10730 }
10731
10732 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10733   EVT NVT = N->getValueType(0);
10734   SDValue V = N->getOperand(0);
10735
10736   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10737     // Combine:
10738     //    (extract_subvec (concat V1, V2, ...), i)
10739     // Into:
10740     //    Vi if possible
10741     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10742     // type.
10743     if (V->getOperand(0).getValueType() != NVT)
10744       return SDValue();
10745     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10746     unsigned NumElems = NVT.getVectorNumElements();
10747     assert((Idx % NumElems) == 0 &&
10748            "IDX in concat is not a multiple of the result vector length.");
10749     return V->getOperand(Idx / NumElems);
10750   }
10751
10752   // Skip bitcasting
10753   if (V->getOpcode() == ISD::BITCAST)
10754     V = V.getOperand(0);
10755
10756   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10757     SDLoc dl(N);
10758     // Handle only simple case where vector being inserted and vector
10759     // being extracted are of same type, and are half size of larger vectors.
10760     EVT BigVT = V->getOperand(0).getValueType();
10761     EVT SmallVT = V->getOperand(1).getValueType();
10762     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10763       return SDValue();
10764
10765     // Only handle cases where both indexes are constants with the same type.
10766     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10767     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10768
10769     if (InsIdx && ExtIdx &&
10770         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10771         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10772       // Combine:
10773       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10774       // Into:
10775       //    indices are equal or bit offsets are equal => V1
10776       //    otherwise => (extract_subvec V1, ExtIdx)
10777       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10778           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10779         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10780       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10781                          DAG.getNode(ISD::BITCAST, dl,
10782                                      N->getOperand(0).getValueType(),
10783                                      V->getOperand(0)), N->getOperand(1));
10784     }
10785   }
10786
10787   return SDValue();
10788 }
10789
10790 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10791                                                  SDValue V, SelectionDAG &DAG) {
10792   SDLoc DL(V);
10793   EVT VT = V.getValueType();
10794
10795   switch (V.getOpcode()) {
10796   default:
10797     return V;
10798
10799   case ISD::CONCAT_VECTORS: {
10800     EVT OpVT = V->getOperand(0).getValueType();
10801     int OpSize = OpVT.getVectorNumElements();
10802     SmallBitVector OpUsedElements(OpSize, false);
10803     bool FoundSimplification = false;
10804     SmallVector<SDValue, 4> NewOps;
10805     NewOps.reserve(V->getNumOperands());
10806     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10807       SDValue Op = V->getOperand(i);
10808       bool OpUsed = false;
10809       for (int j = 0; j < OpSize; ++j)
10810         if (UsedElements[i * OpSize + j]) {
10811           OpUsedElements[j] = true;
10812           OpUsed = true;
10813         }
10814       NewOps.push_back(
10815           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10816                  : DAG.getUNDEF(OpVT));
10817       FoundSimplification |= Op == NewOps.back();
10818       OpUsedElements.reset();
10819     }
10820     if (FoundSimplification)
10821       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10822     return V;
10823   }
10824
10825   case ISD::INSERT_SUBVECTOR: {
10826     SDValue BaseV = V->getOperand(0);
10827     SDValue SubV = V->getOperand(1);
10828     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10829     if (!IdxN)
10830       return V;
10831
10832     int SubSize = SubV.getValueType().getVectorNumElements();
10833     int Idx = IdxN->getZExtValue();
10834     bool SubVectorUsed = false;
10835     SmallBitVector SubUsedElements(SubSize, false);
10836     for (int i = 0; i < SubSize; ++i)
10837       if (UsedElements[i + Idx]) {
10838         SubVectorUsed = true;
10839         SubUsedElements[i] = true;
10840         UsedElements[i + Idx] = false;
10841       }
10842
10843     // Now recurse on both the base and sub vectors.
10844     SDValue SimplifiedSubV =
10845         SubVectorUsed
10846             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10847             : DAG.getUNDEF(SubV.getValueType());
10848     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10849     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10850       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10851                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10852     return V;
10853   }
10854   }
10855 }
10856
10857 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10858                                        SDValue N1, SelectionDAG &DAG) {
10859   EVT VT = SVN->getValueType(0);
10860   int NumElts = VT.getVectorNumElements();
10861   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10862   for (int M : SVN->getMask())
10863     if (M >= 0 && M < NumElts)
10864       N0UsedElements[M] = true;
10865     else if (M >= NumElts)
10866       N1UsedElements[M - NumElts] = true;
10867
10868   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10869   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10870   if (S0 == N0 && S1 == N1)
10871     return SDValue();
10872
10873   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10874 }
10875
10876 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10877 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10878   EVT VT = N->getValueType(0);
10879   unsigned NumElts = VT.getVectorNumElements();
10880
10881   SDValue N0 = N->getOperand(0);
10882   SDValue N1 = N->getOperand(1);
10883   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10884
10885   SmallVector<SDValue, 4> Ops;
10886   EVT ConcatVT = N0.getOperand(0).getValueType();
10887   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10888   unsigned NumConcats = NumElts / NumElemsPerConcat;
10889
10890   // Look at every vector that's inserted. We're looking for exact
10891   // subvector-sized copies from a concatenated vector
10892   for (unsigned I = 0; I != NumConcats; ++I) {
10893     // Make sure we're dealing with a copy.
10894     unsigned Begin = I * NumElemsPerConcat;
10895     bool AllUndef = true, NoUndef = true;
10896     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10897       if (SVN->getMaskElt(J) >= 0)
10898         AllUndef = false;
10899       else
10900         NoUndef = false;
10901     }
10902
10903     if (NoUndef) {
10904       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10905         return SDValue();
10906
10907       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10908         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10909           return SDValue();
10910
10911       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10912       if (FirstElt < N0.getNumOperands())
10913         Ops.push_back(N0.getOperand(FirstElt));
10914       else
10915         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10916
10917     } else if (AllUndef) {
10918       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10919     } else { // Mixed with general masks and undefs, can't do optimization.
10920       return SDValue();
10921     }
10922   }
10923
10924   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10925 }
10926
10927 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10928   EVT VT = N->getValueType(0);
10929   unsigned NumElts = VT.getVectorNumElements();
10930
10931   SDValue N0 = N->getOperand(0);
10932   SDValue N1 = N->getOperand(1);
10933
10934   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10935
10936   // Canonicalize shuffle undef, undef -> undef
10937   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10938     return DAG.getUNDEF(VT);
10939
10940   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10941
10942   // Canonicalize shuffle v, v -> v, undef
10943   if (N0 == N1) {
10944     SmallVector<int, 8> NewMask;
10945     for (unsigned i = 0; i != NumElts; ++i) {
10946       int Idx = SVN->getMaskElt(i);
10947       if (Idx >= (int)NumElts) Idx -= NumElts;
10948       NewMask.push_back(Idx);
10949     }
10950     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10951                                 &NewMask[0]);
10952   }
10953
10954   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10955   if (N0.getOpcode() == ISD::UNDEF) {
10956     SmallVector<int, 8> NewMask;
10957     for (unsigned i = 0; i != NumElts; ++i) {
10958       int Idx = SVN->getMaskElt(i);
10959       if (Idx >= 0) {
10960         if (Idx >= (int)NumElts)
10961           Idx -= NumElts;
10962         else
10963           Idx = -1; // remove reference to lhs
10964       }
10965       NewMask.push_back(Idx);
10966     }
10967     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10968                                 &NewMask[0]);
10969   }
10970
10971   // Remove references to rhs if it is undef
10972   if (N1.getOpcode() == ISD::UNDEF) {
10973     bool Changed = false;
10974     SmallVector<int, 8> NewMask;
10975     for (unsigned i = 0; i != NumElts; ++i) {
10976       int Idx = SVN->getMaskElt(i);
10977       if (Idx >= (int)NumElts) {
10978         Idx = -1;
10979         Changed = true;
10980       }
10981       NewMask.push_back(Idx);
10982     }
10983     if (Changed)
10984       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10985   }
10986
10987   // If it is a splat, check if the argument vector is another splat or a
10988   // build_vector with all scalar elements the same.
10989   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10990     SDNode *V = N0.getNode();
10991
10992     // If this is a bit convert that changes the element type of the vector but
10993     // not the number of vector elements, look through it.  Be careful not to
10994     // look though conversions that change things like v4f32 to v2f64.
10995     if (V->getOpcode() == ISD::BITCAST) {
10996       SDValue ConvInput = V->getOperand(0);
10997       if (ConvInput.getValueType().isVector() &&
10998           ConvInput.getValueType().getVectorNumElements() == NumElts)
10999         V = ConvInput.getNode();
11000     }
11001
11002     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11003       assert(V->getNumOperands() == NumElts &&
11004              "BUILD_VECTOR has wrong number of operands");
11005       SDValue Base;
11006       bool AllSame = true;
11007       for (unsigned i = 0; i != NumElts; ++i) {
11008         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11009           Base = V->getOperand(i);
11010           break;
11011         }
11012       }
11013       // Splat of <u, u, u, u>, return <u, u, u, u>
11014       if (!Base.getNode())
11015         return N0;
11016       for (unsigned i = 0; i != NumElts; ++i) {
11017         if (V->getOperand(i) != Base) {
11018           AllSame = false;
11019           break;
11020         }
11021       }
11022       // Splat of <x, x, x, x>, return <x, x, x, x>
11023       if (AllSame)
11024         return N0;
11025     }
11026   }
11027
11028   // There are various patterns used to build up a vector from smaller vectors,
11029   // subvectors, or elements. Scan chains of these and replace unused insertions
11030   // or components with undef.
11031   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11032     return S;
11033
11034   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11035       Level < AfterLegalizeVectorOps &&
11036       (N1.getOpcode() == ISD::UNDEF ||
11037       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11038        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11039     SDValue V = partitionShuffleOfConcats(N, DAG);
11040
11041     if (V.getNode())
11042       return V;
11043   }
11044
11045   // If this shuffle node is simply a swizzle of another shuffle node,
11046   // then try to simplify it.
11047   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11048       N1.getOpcode() == ISD::UNDEF) {
11049
11050     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11051
11052     // The incoming shuffle must be of the same type as the result of the
11053     // current shuffle.
11054     assert(OtherSV->getOperand(0).getValueType() == VT &&
11055            "Shuffle types don't match");
11056
11057     SmallVector<int, 4> Mask;
11058     // Compute the combined shuffle mask.
11059     for (unsigned i = 0; i != NumElts; ++i) {
11060       int Idx = SVN->getMaskElt(i);
11061       assert(Idx < (int)NumElts && "Index references undef operand");
11062       // Next, this index comes from the first value, which is the incoming
11063       // shuffle. Adopt the incoming index.
11064       if (Idx >= 0)
11065         Idx = OtherSV->getMaskElt(Idx);
11066       Mask.push_back(Idx);
11067     }
11068
11069     // Check if all indices in Mask are Undef. In case, propagate Undef.
11070     bool isUndefMask = true;
11071     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11072       isUndefMask &= Mask[i] < 0;
11073
11074     if (isUndefMask)
11075       return DAG.getUNDEF(VT);
11076     
11077     bool CommuteOperands = false;
11078     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11079       // To be valid, the combine shuffle mask should only reference elements
11080       // from one of the two vectors in input to the inner shufflevector.
11081       bool IsValidMask = true;
11082       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11083         // See if the combined mask only reference undefs or elements coming
11084         // from the first shufflevector operand.
11085         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11086
11087       if (!IsValidMask) {
11088         IsValidMask = true;
11089         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11090           // Check that all the elements come from the second shuffle operand.
11091           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11092         CommuteOperands = IsValidMask;
11093       }
11094
11095       // Early exit if the combined shuffle mask is not valid.
11096       if (!IsValidMask)
11097         return SDValue();
11098     }
11099
11100     // See if this pair of shuffles can be safely folded according to either
11101     // of the following rules:
11102     //   shuffle(shuffle(x, y), undef) -> x
11103     //   shuffle(shuffle(x, undef), undef) -> x
11104     //   shuffle(shuffle(x, y), undef) -> y
11105     bool IsIdentityMask = true;
11106     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11107     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11108       // Skip Undefs.
11109       if (Mask[i] < 0)
11110         continue;
11111
11112       // The combined shuffle must map each index to itself.
11113       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11114     }
11115     
11116     if (IsIdentityMask) {
11117       if (CommuteOperands)
11118         // optimize shuffle(shuffle(x, y), undef) -> y.
11119         return OtherSV->getOperand(1);
11120       
11121       // optimize shuffle(shuffle(x, undef), undef) -> x
11122       // optimize shuffle(shuffle(x, y), undef) -> x
11123       return OtherSV->getOperand(0);
11124     }
11125
11126     // It may still be beneficial to combine the two shuffles if the
11127     // resulting shuffle is legal.
11128     if (TLI.isTypeLegal(VT)) {
11129       if (!CommuteOperands) {
11130         if (TLI.isShuffleMaskLegal(Mask, VT))
11131           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11132           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11133           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11134                                       &Mask[0]);
11135       } else {
11136         // Compute the commuted shuffle mask.
11137         for (unsigned i = 0; i != NumElts; ++i) {
11138           int idx = Mask[i];
11139           if (idx < 0)
11140             continue;
11141           else if (idx < (int)NumElts)
11142             Mask[i] = idx + NumElts;
11143           else
11144             Mask[i] = idx - NumElts;
11145         }
11146
11147         if (TLI.isShuffleMaskLegal(Mask, VT))
11148           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11149           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11150                                       &Mask[0]);
11151       }
11152     }
11153   }
11154
11155   // Canonicalize shuffles according to rules:
11156   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11157   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11158   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11159   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11160       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11161       TLI.isTypeLegal(VT)) {
11162     // The incoming shuffle must be of the same type as the result of the
11163     // current shuffle.
11164     assert(N1->getOperand(0).getValueType() == VT &&
11165            "Shuffle types don't match");
11166
11167     SDValue SV0 = N1->getOperand(0);
11168     SDValue SV1 = N1->getOperand(1);
11169     bool HasSameOp0 = N0 == SV0;
11170     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11171     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11172       // Commute the operands of this shuffle so that next rule
11173       // will trigger.
11174       return DAG.getCommutedVectorShuffle(*SVN);
11175   }
11176
11177   // Try to fold according to rules:
11178   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11179   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11180   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11181   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11182   // Don't try to fold shuffles with illegal type.
11183   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11184       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11185     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11186
11187     // The incoming shuffle must be of the same type as the result of the
11188     // current shuffle.
11189     assert(OtherSV->getOperand(0).getValueType() == VT &&
11190            "Shuffle types don't match");
11191
11192     SDValue SV0 = OtherSV->getOperand(0);
11193     SDValue SV1 = OtherSV->getOperand(1);
11194     bool HasSameOp0 = N1 == SV0;
11195     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11196     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11197       // Early exit.
11198       return SDValue();
11199
11200     SmallVector<int, 4> Mask;
11201     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11202     // operand, and SV1 as the second operand.
11203     for (unsigned i = 0; i != NumElts; ++i) {
11204       int Idx = SVN->getMaskElt(i);
11205       if (Idx < 0) {
11206         // Propagate Undef.
11207         Mask.push_back(Idx);
11208         continue;
11209       }
11210
11211       if (Idx < (int)NumElts) {
11212         Idx = OtherSV->getMaskElt(Idx);
11213         if (IsSV1Undef && Idx >= (int) NumElts)
11214           Idx = -1;  // Propagate Undef.
11215       } else
11216         Idx = HasSameOp0 ? Idx - NumElts : Idx;
11217
11218       Mask.push_back(Idx);
11219     }
11220
11221     // Check if all indices in Mask are Undef. In case, propagate Undef.
11222     bool isUndefMask = true;
11223     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11224       isUndefMask &= Mask[i] < 0;
11225
11226     if (isUndefMask)
11227       return DAG.getUNDEF(VT);
11228
11229     // Avoid introducing shuffles with illegal mask.
11230     if (TLI.isShuffleMaskLegal(Mask, VT)) {
11231       if (IsSV1Undef)
11232         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11233         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11234         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11235       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11236     }
11237   }
11238
11239   return SDValue();
11240 }
11241
11242 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11243   SDValue N0 = N->getOperand(0);
11244   SDValue N2 = N->getOperand(2);
11245
11246   // If the input vector is a concatenation, and the insert replaces
11247   // one of the halves, we can optimize into a single concat_vectors.
11248   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11249       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11250     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11251     EVT VT = N->getValueType(0);
11252
11253     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11254     // (concat_vectors Z, Y)
11255     if (InsIdx == 0)
11256       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11257                          N->getOperand(1), N0.getOperand(1));
11258
11259     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11260     // (concat_vectors X, Z)
11261     if (InsIdx == VT.getVectorNumElements()/2)
11262       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11263                          N0.getOperand(0), N->getOperand(1));
11264   }
11265
11266   return SDValue();
11267 }
11268
11269 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11270 /// with the destination vector and a zero vector.
11271 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11272 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11273 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11274   EVT VT = N->getValueType(0);
11275   SDLoc dl(N);
11276   SDValue LHS = N->getOperand(0);
11277   SDValue RHS = N->getOperand(1);
11278   if (N->getOpcode() == ISD::AND) {
11279     if (RHS.getOpcode() == ISD::BITCAST)
11280       RHS = RHS.getOperand(0);
11281     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11282       SmallVector<int, 8> Indices;
11283       unsigned NumElts = RHS.getNumOperands();
11284       for (unsigned i = 0; i != NumElts; ++i) {
11285         SDValue Elt = RHS.getOperand(i);
11286         if (!isa<ConstantSDNode>(Elt))
11287           return SDValue();
11288
11289         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11290           Indices.push_back(i);
11291         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11292           Indices.push_back(NumElts);
11293         else
11294           return SDValue();
11295       }
11296
11297       // Let's see if the target supports this vector_shuffle.
11298       EVT RVT = RHS.getValueType();
11299       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11300         return SDValue();
11301
11302       // Return the new VECTOR_SHUFFLE node.
11303       EVT EltVT = RVT.getVectorElementType();
11304       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11305                                      DAG.getConstant(0, EltVT));
11306       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11307       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11308       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11309       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11310     }
11311   }
11312
11313   return SDValue();
11314 }
11315
11316 /// Visit a binary vector operation, like ADD.
11317 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11318   assert(N->getValueType(0).isVector() &&
11319          "SimplifyVBinOp only works on vectors!");
11320
11321   SDValue LHS = N->getOperand(0);
11322   SDValue RHS = N->getOperand(1);
11323   SDValue Shuffle = XformToShuffleWithZero(N);
11324   if (Shuffle.getNode()) return Shuffle;
11325
11326   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11327   // this operation.
11328   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11329       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11330     // Check if both vectors are constants. If not bail out.
11331     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11332           cast<BuildVectorSDNode>(RHS)->isConstant()))
11333       return SDValue();
11334
11335     SmallVector<SDValue, 8> Ops;
11336     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11337       SDValue LHSOp = LHS.getOperand(i);
11338       SDValue RHSOp = RHS.getOperand(i);
11339
11340       // Can't fold divide by zero.
11341       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11342           N->getOpcode() == ISD::FDIV) {
11343         if ((RHSOp.getOpcode() == ISD::Constant &&
11344              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11345             (RHSOp.getOpcode() == ISD::ConstantFP &&
11346              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11347           break;
11348       }
11349
11350       EVT VT = LHSOp.getValueType();
11351       EVT RVT = RHSOp.getValueType();
11352       if (RVT != VT) {
11353         // Integer BUILD_VECTOR operands may have types larger than the element
11354         // size (e.g., when the element type is not legal).  Prior to type
11355         // legalization, the types may not match between the two BUILD_VECTORS.
11356         // Truncate one of the operands to make them match.
11357         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11358           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11359         } else {
11360           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11361           VT = RVT;
11362         }
11363       }
11364       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11365                                    LHSOp, RHSOp);
11366       if (FoldOp.getOpcode() != ISD::UNDEF &&
11367           FoldOp.getOpcode() != ISD::Constant &&
11368           FoldOp.getOpcode() != ISD::ConstantFP)
11369         break;
11370       Ops.push_back(FoldOp);
11371       AddToWorklist(FoldOp.getNode());
11372     }
11373
11374     if (Ops.size() == LHS.getNumOperands())
11375       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11376   }
11377
11378   // Type legalization might introduce new shuffles in the DAG.
11379   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11380   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11381   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11382       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11383       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11384       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11385     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11386     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11387
11388     if (SVN0->getMask().equals(SVN1->getMask())) {
11389       EVT VT = N->getValueType(0);
11390       SDValue UndefVector = LHS.getOperand(1);
11391       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11392                                      LHS.getOperand(0), RHS.getOperand(0));
11393       AddUsersToWorklist(N);
11394       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11395                                   &SVN0->getMask()[0]);
11396     }
11397   }
11398
11399   return SDValue();
11400 }
11401
11402 /// Visit a binary vector operation, like FABS/FNEG.
11403 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11404   assert(N->getValueType(0).isVector() &&
11405          "SimplifyVUnaryOp only works on vectors!");
11406
11407   SDValue N0 = N->getOperand(0);
11408
11409   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11410     return SDValue();
11411
11412   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11413   SmallVector<SDValue, 8> Ops;
11414   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11415     SDValue Op = N0.getOperand(i);
11416     if (Op.getOpcode() != ISD::UNDEF &&
11417         Op.getOpcode() != ISD::ConstantFP)
11418       break;
11419     EVT EltVT = Op.getValueType();
11420     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11421     if (FoldOp.getOpcode() != ISD::UNDEF &&
11422         FoldOp.getOpcode() != ISD::ConstantFP)
11423       break;
11424     Ops.push_back(FoldOp);
11425     AddToWorklist(FoldOp.getNode());
11426   }
11427
11428   if (Ops.size() != N0.getNumOperands())
11429     return SDValue();
11430
11431   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11432 }
11433
11434 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11435                                     SDValue N1, SDValue N2){
11436   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11437
11438   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11439                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11440
11441   // If we got a simplified select_cc node back from SimplifySelectCC, then
11442   // break it down into a new SETCC node, and a new SELECT node, and then return
11443   // the SELECT node, since we were called with a SELECT node.
11444   if (SCC.getNode()) {
11445     // Check to see if we got a select_cc back (to turn into setcc/select).
11446     // Otherwise, just return whatever node we got back, like fabs.
11447     if (SCC.getOpcode() == ISD::SELECT_CC) {
11448       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11449                                   N0.getValueType(),
11450                                   SCC.getOperand(0), SCC.getOperand(1),
11451                                   SCC.getOperand(4));
11452       AddToWorklist(SETCC.getNode());
11453       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11454                            SCC.getOperand(2), SCC.getOperand(3));
11455     }
11456
11457     return SCC;
11458   }
11459   return SDValue();
11460 }
11461
11462 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11463 /// being selected between, see if we can simplify the select.  Callers of this
11464 /// should assume that TheSelect is deleted if this returns true.  As such, they
11465 /// should return the appropriate thing (e.g. the node) back to the top-level of
11466 /// the DAG combiner loop to avoid it being looked at.
11467 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11468                                     SDValue RHS) {
11469
11470   // Cannot simplify select with vector condition
11471   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11472
11473   // If this is a select from two identical things, try to pull the operation
11474   // through the select.
11475   if (LHS.getOpcode() != RHS.getOpcode() ||
11476       !LHS.hasOneUse() || !RHS.hasOneUse())
11477     return false;
11478
11479   // If this is a load and the token chain is identical, replace the select
11480   // of two loads with a load through a select of the address to load from.
11481   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11482   // constants have been dropped into the constant pool.
11483   if (LHS.getOpcode() == ISD::LOAD) {
11484     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11485     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11486
11487     // Token chains must be identical.
11488     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11489         // Do not let this transformation reduce the number of volatile loads.
11490         LLD->isVolatile() || RLD->isVolatile() ||
11491         // If this is an EXTLOAD, the VT's must match.
11492         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11493         // If this is an EXTLOAD, the kind of extension must match.
11494         (LLD->getExtensionType() != RLD->getExtensionType() &&
11495          // The only exception is if one of the extensions is anyext.
11496          LLD->getExtensionType() != ISD::EXTLOAD &&
11497          RLD->getExtensionType() != ISD::EXTLOAD) ||
11498         // FIXME: this discards src value information.  This is
11499         // over-conservative. It would be beneficial to be able to remember
11500         // both potential memory locations.  Since we are discarding
11501         // src value info, don't do the transformation if the memory
11502         // locations are not in the default address space.
11503         LLD->getPointerInfo().getAddrSpace() != 0 ||
11504         RLD->getPointerInfo().getAddrSpace() != 0 ||
11505         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11506                                       LLD->getBasePtr().getValueType()))
11507       return false;
11508
11509     // Check that the select condition doesn't reach either load.  If so,
11510     // folding this will induce a cycle into the DAG.  If not, this is safe to
11511     // xform, so create a select of the addresses.
11512     SDValue Addr;
11513     if (TheSelect->getOpcode() == ISD::SELECT) {
11514       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11515       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11516           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11517         return false;
11518       // The loads must not depend on one another.
11519       if (LLD->isPredecessorOf(RLD) ||
11520           RLD->isPredecessorOf(LLD))
11521         return false;
11522       Addr = DAG.getSelect(SDLoc(TheSelect),
11523                            LLD->getBasePtr().getValueType(),
11524                            TheSelect->getOperand(0), LLD->getBasePtr(),
11525                            RLD->getBasePtr());
11526     } else {  // Otherwise SELECT_CC
11527       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11528       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11529
11530       if ((LLD->hasAnyUseOfValue(1) &&
11531            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11532           (RLD->hasAnyUseOfValue(1) &&
11533            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11534         return false;
11535
11536       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11537                          LLD->getBasePtr().getValueType(),
11538                          TheSelect->getOperand(0),
11539                          TheSelect->getOperand(1),
11540                          LLD->getBasePtr(), RLD->getBasePtr(),
11541                          TheSelect->getOperand(4));
11542     }
11543
11544     SDValue Load;
11545     // It is safe to replace the two loads if they have different alignments,
11546     // but the new load must be the minimum (most restrictive) alignment of the
11547     // inputs.
11548     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11549     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11550     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11551       Load = DAG.getLoad(TheSelect->getValueType(0),
11552                          SDLoc(TheSelect),
11553                          // FIXME: Discards pointer and AA info.
11554                          LLD->getChain(), Addr, MachinePointerInfo(),
11555                          LLD->isVolatile(), LLD->isNonTemporal(),
11556                          isInvariant, Alignment);
11557     } else {
11558       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11559                             RLD->getExtensionType() : LLD->getExtensionType(),
11560                             SDLoc(TheSelect),
11561                             TheSelect->getValueType(0),
11562                             // FIXME: Discards pointer and AA info.
11563                             LLD->getChain(), Addr, MachinePointerInfo(),
11564                             LLD->getMemoryVT(), LLD->isVolatile(),
11565                             LLD->isNonTemporal(), isInvariant, Alignment);
11566     }
11567
11568     // Users of the select now use the result of the load.
11569     CombineTo(TheSelect, Load);
11570
11571     // Users of the old loads now use the new load's chain.  We know the
11572     // old-load value is dead now.
11573     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11574     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11575     return true;
11576   }
11577
11578   return false;
11579 }
11580
11581 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11582 /// where 'cond' is the comparison specified by CC.
11583 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11584                                       SDValue N2, SDValue N3,
11585                                       ISD::CondCode CC, bool NotExtCompare) {
11586   // (x ? y : y) -> y.
11587   if (N2 == N3) return N2;
11588
11589   EVT VT = N2.getValueType();
11590   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11591   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11592   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11593
11594   // Determine if the condition we're dealing with is constant
11595   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11596                               N0, N1, CC, DL, false);
11597   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11598   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11599
11600   // fold select_cc true, x, y -> x
11601   if (SCCC && !SCCC->isNullValue())
11602     return N2;
11603   // fold select_cc false, x, y -> y
11604   if (SCCC && SCCC->isNullValue())
11605     return N3;
11606
11607   // Check to see if we can simplify the select into an fabs node
11608   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11609     // Allow either -0.0 or 0.0
11610     if (CFP->getValueAPF().isZero()) {
11611       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11612       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11613           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11614           N2 == N3.getOperand(0))
11615         return DAG.getNode(ISD::FABS, DL, VT, N0);
11616
11617       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11618       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11619           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11620           N2.getOperand(0) == N3)
11621         return DAG.getNode(ISD::FABS, DL, VT, N3);
11622     }
11623   }
11624
11625   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11626   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11627   // in it.  This is a win when the constant is not otherwise available because
11628   // it replaces two constant pool loads with one.  We only do this if the FP
11629   // type is known to be legal, because if it isn't, then we are before legalize
11630   // types an we want the other legalization to happen first (e.g. to avoid
11631   // messing with soft float) and if the ConstantFP is not legal, because if
11632   // it is legal, we may not need to store the FP constant in a constant pool.
11633   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11634     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11635       if (TLI.isTypeLegal(N2.getValueType()) &&
11636           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11637                TargetLowering::Legal &&
11638            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11639            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11640           // If both constants have multiple uses, then we won't need to do an
11641           // extra load, they are likely around in registers for other users.
11642           (TV->hasOneUse() || FV->hasOneUse())) {
11643         Constant *Elts[] = {
11644           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11645           const_cast<ConstantFP*>(TV->getConstantFPValue())
11646         };
11647         Type *FPTy = Elts[0]->getType();
11648         const DataLayout &TD = *TLI.getDataLayout();
11649
11650         // Create a ConstantArray of the two constants.
11651         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11652         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11653                                             TD.getPrefTypeAlignment(FPTy));
11654         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11655
11656         // Get the offsets to the 0 and 1 element of the array so that we can
11657         // select between them.
11658         SDValue Zero = DAG.getIntPtrConstant(0);
11659         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11660         SDValue One = DAG.getIntPtrConstant(EltSize);
11661
11662         SDValue Cond = DAG.getSetCC(DL,
11663                                     getSetCCResultType(N0.getValueType()),
11664                                     N0, N1, CC);
11665         AddToWorklist(Cond.getNode());
11666         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11667                                           Cond, One, Zero);
11668         AddToWorklist(CstOffset.getNode());
11669         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11670                             CstOffset);
11671         AddToWorklist(CPIdx.getNode());
11672         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11673                            MachinePointerInfo::getConstantPool(), false,
11674                            false, false, Alignment);
11675
11676       }
11677     }
11678
11679   // Check to see if we can perform the "gzip trick", transforming
11680   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11681   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11682       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11683        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11684     EVT XType = N0.getValueType();
11685     EVT AType = N2.getValueType();
11686     if (XType.bitsGE(AType)) {
11687       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11688       // single-bit constant.
11689       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11690         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11691         ShCtV = XType.getSizeInBits()-ShCtV-1;
11692         SDValue ShCt = DAG.getConstant(ShCtV,
11693                                        getShiftAmountTy(N0.getValueType()));
11694         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11695                                     XType, N0, ShCt);
11696         AddToWorklist(Shift.getNode());
11697
11698         if (XType.bitsGT(AType)) {
11699           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11700           AddToWorklist(Shift.getNode());
11701         }
11702
11703         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11704       }
11705
11706       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11707                                   XType, N0,
11708                                   DAG.getConstant(XType.getSizeInBits()-1,
11709                                          getShiftAmountTy(N0.getValueType())));
11710       AddToWorklist(Shift.getNode());
11711
11712       if (XType.bitsGT(AType)) {
11713         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11714         AddToWorklist(Shift.getNode());
11715       }
11716
11717       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11718     }
11719   }
11720
11721   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11722   // where y is has a single bit set.
11723   // A plaintext description would be, we can turn the SELECT_CC into an AND
11724   // when the condition can be materialized as an all-ones register.  Any
11725   // single bit-test can be materialized as an all-ones register with
11726   // shift-left and shift-right-arith.
11727   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11728       N0->getValueType(0) == VT &&
11729       N1C && N1C->isNullValue() &&
11730       N2C && N2C->isNullValue()) {
11731     SDValue AndLHS = N0->getOperand(0);
11732     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11733     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11734       // Shift the tested bit over the sign bit.
11735       APInt AndMask = ConstAndRHS->getAPIntValue();
11736       SDValue ShlAmt =
11737         DAG.getConstant(AndMask.countLeadingZeros(),
11738                         getShiftAmountTy(AndLHS.getValueType()));
11739       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11740
11741       // Now arithmetic right shift it all the way over, so the result is either
11742       // all-ones, or zero.
11743       SDValue ShrAmt =
11744         DAG.getConstant(AndMask.getBitWidth()-1,
11745                         getShiftAmountTy(Shl.getValueType()));
11746       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11747
11748       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11749     }
11750   }
11751
11752   // fold select C, 16, 0 -> shl C, 4
11753   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11754       TLI.getBooleanContents(N0.getValueType()) ==
11755           TargetLowering::ZeroOrOneBooleanContent) {
11756
11757     // If the caller doesn't want us to simplify this into a zext of a compare,
11758     // don't do it.
11759     if (NotExtCompare && N2C->getAPIntValue() == 1)
11760       return SDValue();
11761
11762     // Get a SetCC of the condition
11763     // NOTE: Don't create a SETCC if it's not legal on this target.
11764     if (!LegalOperations ||
11765         TLI.isOperationLegal(ISD::SETCC,
11766           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11767       SDValue Temp, SCC;
11768       // cast from setcc result type to select result type
11769       if (LegalTypes) {
11770         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11771                             N0, N1, CC);
11772         if (N2.getValueType().bitsLT(SCC.getValueType()))
11773           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11774                                         N2.getValueType());
11775         else
11776           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11777                              N2.getValueType(), SCC);
11778       } else {
11779         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11780         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11781                            N2.getValueType(), SCC);
11782       }
11783
11784       AddToWorklist(SCC.getNode());
11785       AddToWorklist(Temp.getNode());
11786
11787       if (N2C->getAPIntValue() == 1)
11788         return Temp;
11789
11790       // shl setcc result by log2 n2c
11791       return DAG.getNode(
11792           ISD::SHL, DL, N2.getValueType(), Temp,
11793           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11794                           getShiftAmountTy(Temp.getValueType())));
11795     }
11796   }
11797
11798   // Check to see if this is the equivalent of setcc
11799   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11800   // otherwise, go ahead with the folds.
11801   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11802     EVT XType = N0.getValueType();
11803     if (!LegalOperations ||
11804         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11805       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11806       if (Res.getValueType() != VT)
11807         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11808       return Res;
11809     }
11810
11811     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11812     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11813         (!LegalOperations ||
11814          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11815       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11816       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11817                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11818                                        getShiftAmountTy(Ctlz.getValueType())));
11819     }
11820     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11821     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11822       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11823                                   XType, DAG.getConstant(0, XType), N0);
11824       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11825       return DAG.getNode(ISD::SRL, DL, XType,
11826                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11827                          DAG.getConstant(XType.getSizeInBits()-1,
11828                                          getShiftAmountTy(XType)));
11829     }
11830     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11831     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11832       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11833                                  DAG.getConstant(XType.getSizeInBits()-1,
11834                                          getShiftAmountTy(N0.getValueType())));
11835       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11836     }
11837   }
11838
11839   // Check to see if this is an integer abs.
11840   // select_cc setg[te] X,  0,  X, -X ->
11841   // select_cc setgt    X, -1,  X, -X ->
11842   // select_cc setl[te] X,  0, -X,  X ->
11843   // select_cc setlt    X,  1, -X,  X ->
11844   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11845   if (N1C) {
11846     ConstantSDNode *SubC = nullptr;
11847     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11848          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11849         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11850       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11851     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11852               (N1C->isOne() && CC == ISD::SETLT)) &&
11853              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11854       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11855
11856     EVT XType = N0.getValueType();
11857     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11858       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11859                                   N0,
11860                                   DAG.getConstant(XType.getSizeInBits()-1,
11861                                          getShiftAmountTy(N0.getValueType())));
11862       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11863                                 XType, N0, Shift);
11864       AddToWorklist(Shift.getNode());
11865       AddToWorklist(Add.getNode());
11866       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11867     }
11868   }
11869
11870   return SDValue();
11871 }
11872
11873 /// This is a stub for TargetLowering::SimplifySetCC.
11874 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11875                                    SDValue N1, ISD::CondCode Cond,
11876                                    SDLoc DL, bool foldBooleans) {
11877   TargetLowering::DAGCombinerInfo
11878     DagCombineInfo(DAG, Level, false, this);
11879   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11880 }
11881
11882 /// Given an ISD::SDIV node expressing a divide by constant, return
11883 /// a DAG expression to select that will generate the same value by multiplying
11884 /// by a magic number.
11885 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11886 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11887   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11888   if (!C)
11889     return SDValue();
11890
11891   // Avoid division by zero.
11892   if (!C->getAPIntValue())
11893     return SDValue();
11894
11895   std::vector<SDNode*> Built;
11896   SDValue S =
11897       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11898
11899   for (SDNode *N : Built)
11900     AddToWorklist(N);
11901   return S;
11902 }
11903
11904 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11905 /// DAG expression that will generate the same value by right shifting.
11906 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11907   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11908   if (!C)
11909     return SDValue();
11910
11911   // Avoid division by zero.
11912   if (!C->getAPIntValue())
11913     return SDValue();
11914
11915   std::vector<SDNode *> Built;
11916   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11917
11918   for (SDNode *N : Built)
11919     AddToWorklist(N);
11920   return S;
11921 }
11922
11923 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11924 /// expression that will generate the same value by multiplying by a magic
11925 /// number.
11926 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11927 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11928   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11929   if (!C)
11930     return SDValue();
11931
11932   // Avoid division by zero.
11933   if (!C->getAPIntValue())
11934     return SDValue();
11935
11936   std::vector<SDNode*> Built;
11937   SDValue S =
11938       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11939
11940   for (SDNode *N : Built)
11941     AddToWorklist(N);
11942   return S;
11943 }
11944
11945 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11946   if (Level >= AfterLegalizeDAG)
11947     return SDValue();
11948
11949   // Expose the DAG combiner to the target combiner implementations.
11950   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11951
11952   unsigned Iterations = 0;
11953   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11954     if (Iterations) {
11955       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11956       // For the reciprocal, we need to find the zero of the function:
11957       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11958       //     =>
11959       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11960       //     does not require additional intermediate precision]
11961       EVT VT = Op.getValueType();
11962       SDLoc DL(Op);
11963       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11964
11965       AddToWorklist(Est.getNode());
11966
11967       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11968       for (unsigned i = 0; i < Iterations; ++i) {
11969         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11970         AddToWorklist(NewEst.getNode());
11971
11972         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11973         AddToWorklist(NewEst.getNode());
11974
11975         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11976         AddToWorklist(NewEst.getNode());
11977
11978         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11979         AddToWorklist(Est.getNode());
11980       }
11981     }
11982     return Est;
11983   }
11984
11985   return SDValue();
11986 }
11987
11988 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
11989   if (Level >= AfterLegalizeDAG)
11990     return SDValue();
11991
11992   // Expose the DAG combiner to the target combiner implementations.
11993   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11994   unsigned Iterations = 0;
11995   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations)) {
11996     if (Iterations) {
11997       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11998       // For the reciprocal sqrt, we need to find the zero of the function:
11999       //   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12000       //     =>
12001       //   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12002       // As a result, we precompute A/2 prior to the iteration loop.
12003       EVT VT = Op.getValueType();
12004       SDLoc DL(Op);
12005       SDValue FPThreeHalves = DAG.getConstantFP(1.5, VT);
12006
12007       AddToWorklist(Est.getNode());
12008
12009       // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12010       // this entire sequence requires only one FP constant.
12011       SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, FPThreeHalves, Op);
12012       AddToWorklist(HalfArg.getNode());
12013
12014       HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Op);
12015       AddToWorklist(HalfArg.getNode());
12016
12017       // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12018       for (unsigned i = 0; i < Iterations; ++i) {
12019         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12020         AddToWorklist(NewEst.getNode());
12021
12022         NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12023         AddToWorklist(NewEst.getNode());
12024
12025         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPThreeHalves, NewEst);
12026         AddToWorklist(NewEst.getNode());
12027
12028         Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12029         AddToWorklist(Est.getNode());
12030       }
12031     }
12032     return Est;
12033   }
12034
12035   return SDValue();
12036 }
12037
12038 /// Return true if base is a frame index, which is known not to alias with
12039 /// anything but itself.  Provides base object and offset as results.
12040 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12041                            const GlobalValue *&GV, const void *&CV) {
12042   // Assume it is a primitive operation.
12043   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12044
12045   // If it's an adding a simple constant then integrate the offset.
12046   if (Base.getOpcode() == ISD::ADD) {
12047     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12048       Base = Base.getOperand(0);
12049       Offset += C->getZExtValue();
12050     }
12051   }
12052
12053   // Return the underlying GlobalValue, and update the Offset.  Return false
12054   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12055   // by multiple nodes with different offsets.
12056   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12057     GV = G->getGlobal();
12058     Offset += G->getOffset();
12059     return false;
12060   }
12061
12062   // Return the underlying Constant value, and update the Offset.  Return false
12063   // for ConstantSDNodes since the same constant pool entry may be represented
12064   // by multiple nodes with different offsets.
12065   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12066     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12067                                          : (const void *)C->getConstVal();
12068     Offset += C->getOffset();
12069     return false;
12070   }
12071   // If it's any of the following then it can't alias with anything but itself.
12072   return isa<FrameIndexSDNode>(Base);
12073 }
12074
12075 /// Return true if there is any possibility that the two addresses overlap.
12076 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12077   // If they are the same then they must be aliases.
12078   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12079
12080   // If they are both volatile then they cannot be reordered.
12081   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12082
12083   // Gather base node and offset information.
12084   SDValue Base1, Base2;
12085   int64_t Offset1, Offset2;
12086   const GlobalValue *GV1, *GV2;
12087   const void *CV1, *CV2;
12088   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12089                                       Base1, Offset1, GV1, CV1);
12090   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12091                                       Base2, Offset2, GV2, CV2);
12092
12093   // If they have a same base address then check to see if they overlap.
12094   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12095     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12096              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12097
12098   // It is possible for different frame indices to alias each other, mostly
12099   // when tail call optimization reuses return address slots for arguments.
12100   // To catch this case, look up the actual index of frame indices to compute
12101   // the real alias relationship.
12102   if (isFrameIndex1 && isFrameIndex2) {
12103     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12104     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12105     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12106     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12107              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12108   }
12109
12110   // Otherwise, if we know what the bases are, and they aren't identical, then
12111   // we know they cannot alias.
12112   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12113     return false;
12114
12115   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12116   // compared to the size and offset of the access, we may be able to prove they
12117   // do not alias.  This check is conservative for now to catch cases created by
12118   // splitting vector types.
12119   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12120       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12121       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12122        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12123       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12124     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12125     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12126
12127     // There is no overlap between these relatively aligned accesses of similar
12128     // size, return no alias.
12129     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12130         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12131       return false;
12132   }
12133
12134   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12135                    ? CombinerGlobalAA
12136                    : DAG.getSubtarget().useAA();
12137 #ifndef NDEBUG
12138   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12139       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12140     UseAA = false;
12141 #endif
12142   if (UseAA &&
12143       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12144     // Use alias analysis information.
12145     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12146                                  Op1->getSrcValueOffset());
12147     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12148         Op0->getSrcValueOffset() - MinOffset;
12149     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12150         Op1->getSrcValueOffset() - MinOffset;
12151     AliasAnalysis::AliasResult AAResult =
12152         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12153                                          Overlap1,
12154                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12155                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12156                                          Overlap2,
12157                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12158     if (AAResult == AliasAnalysis::NoAlias)
12159       return false;
12160   }
12161
12162   // Otherwise we have to assume they alias.
12163   return true;
12164 }
12165
12166 /// Walk up chain skipping non-aliasing memory nodes,
12167 /// looking for aliasing nodes and adding them to the Aliases vector.
12168 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12169                                    SmallVectorImpl<SDValue> &Aliases) {
12170   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12171   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12172
12173   // Get alias information for node.
12174   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12175
12176   // Starting off.
12177   Chains.push_back(OriginalChain);
12178   unsigned Depth = 0;
12179
12180   // Look at each chain and determine if it is an alias.  If so, add it to the
12181   // aliases list.  If not, then continue up the chain looking for the next
12182   // candidate.
12183   while (!Chains.empty()) {
12184     SDValue Chain = Chains.back();
12185     Chains.pop_back();
12186
12187     // For TokenFactor nodes, look at each operand and only continue up the
12188     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12189     // find more and revert to original chain since the xform is unlikely to be
12190     // profitable.
12191     //
12192     // FIXME: The depth check could be made to return the last non-aliasing
12193     // chain we found before we hit a tokenfactor rather than the original
12194     // chain.
12195     if (Depth > 6 || Aliases.size() == 2) {
12196       Aliases.clear();
12197       Aliases.push_back(OriginalChain);
12198       return;
12199     }
12200
12201     // Don't bother if we've been before.
12202     if (!Visited.insert(Chain.getNode()))
12203       continue;
12204
12205     switch (Chain.getOpcode()) {
12206     case ISD::EntryToken:
12207       // Entry token is ideal chain operand, but handled in FindBetterChain.
12208       break;
12209
12210     case ISD::LOAD:
12211     case ISD::STORE: {
12212       // Get alias information for Chain.
12213       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12214           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12215
12216       // If chain is alias then stop here.
12217       if (!(IsLoad && IsOpLoad) &&
12218           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12219         Aliases.push_back(Chain);
12220       } else {
12221         // Look further up the chain.
12222         Chains.push_back(Chain.getOperand(0));
12223         ++Depth;
12224       }
12225       break;
12226     }
12227
12228     case ISD::TokenFactor:
12229       // We have to check each of the operands of the token factor for "small"
12230       // token factors, so we queue them up.  Adding the operands to the queue
12231       // (stack) in reverse order maintains the original order and increases the
12232       // likelihood that getNode will find a matching token factor (CSE.)
12233       if (Chain.getNumOperands() > 16) {
12234         Aliases.push_back(Chain);
12235         break;
12236       }
12237       for (unsigned n = Chain.getNumOperands(); n;)
12238         Chains.push_back(Chain.getOperand(--n));
12239       ++Depth;
12240       break;
12241
12242     default:
12243       // For all other instructions we will just have to take what we can get.
12244       Aliases.push_back(Chain);
12245       break;
12246     }
12247   }
12248
12249   // We need to be careful here to also search for aliases through the
12250   // value operand of a store, etc. Consider the following situation:
12251   //   Token1 = ...
12252   //   L1 = load Token1, %52
12253   //   S1 = store Token1, L1, %51
12254   //   L2 = load Token1, %52+8
12255   //   S2 = store Token1, L2, %51+8
12256   //   Token2 = Token(S1, S2)
12257   //   L3 = load Token2, %53
12258   //   S3 = store Token2, L3, %52
12259   //   L4 = load Token2, %53+8
12260   //   S4 = store Token2, L4, %52+8
12261   // If we search for aliases of S3 (which loads address %52), and we look
12262   // only through the chain, then we'll miss the trivial dependence on L1
12263   // (which also loads from %52). We then might change all loads and
12264   // stores to use Token1 as their chain operand, which could result in
12265   // copying %53 into %52 before copying %52 into %51 (which should
12266   // happen first).
12267   //
12268   // The problem is, however, that searching for such data dependencies
12269   // can become expensive, and the cost is not directly related to the
12270   // chain depth. Instead, we'll rule out such configurations here by
12271   // insisting that we've visited all chain users (except for users
12272   // of the original chain, which is not necessary). When doing this,
12273   // we need to look through nodes we don't care about (otherwise, things
12274   // like register copies will interfere with trivial cases).
12275
12276   SmallVector<const SDNode *, 16> Worklist;
12277   for (const SDNode *N : Visited)
12278     if (N != OriginalChain.getNode())
12279       Worklist.push_back(N);
12280
12281   while (!Worklist.empty()) {
12282     const SDNode *M = Worklist.pop_back_val();
12283
12284     // We have already visited M, and want to make sure we've visited any uses
12285     // of M that we care about. For uses that we've not visisted, and don't
12286     // care about, queue them to the worklist.
12287
12288     for (SDNode::use_iterator UI = M->use_begin(),
12289          UIE = M->use_end(); UI != UIE; ++UI)
12290       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12291         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12292           // We've not visited this use, and we care about it (it could have an
12293           // ordering dependency with the original node).
12294           Aliases.clear();
12295           Aliases.push_back(OriginalChain);
12296           return;
12297         }
12298
12299         // We've not visited this use, but we don't care about it. Mark it as
12300         // visited and enqueue it to the worklist.
12301         Worklist.push_back(*UI);
12302       }
12303   }
12304 }
12305
12306 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12307 /// (aliasing node.)
12308 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12309   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12310
12311   // Accumulate all the aliases to this node.
12312   GatherAllAliases(N, OldChain, Aliases);
12313
12314   // If no operands then chain to entry token.
12315   if (Aliases.size() == 0)
12316     return DAG.getEntryNode();
12317
12318   // If a single operand then chain to it.  We don't need to revisit it.
12319   if (Aliases.size() == 1)
12320     return Aliases[0];
12321
12322   // Construct a custom tailored token factor.
12323   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12324 }
12325
12326 /// This is the entry point for the file.
12327 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12328                            CodeGenOpt::Level OptLevel) {
12329   /// This is the main entry point to this class.
12330   DAGCombiner(*this, AA, OptLevel).Run(Level);
12331 }