propagate IR-level fast-math-flags to DAG nodes (NFC)
[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/SetVector.h"
21 #include "llvm/ADT/SmallBitVector.h"
22 #include "llvm/ADT/SmallPtrSet.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 visitANDLike(SDValue N0, SDValue N1, SDNode *LocReference);
250     SDValue visitOR(SDNode *N);
251     SDValue visitORLike(SDValue N0, SDValue N1, SDNode *LocReference);
252     SDValue visitXOR(SDNode *N);
253     SDValue SimplifyVBinOp(SDNode *N);
254     SDValue visitSHL(SDNode *N);
255     SDValue visitSRA(SDNode *N);
256     SDValue visitSRL(SDNode *N);
257     SDValue visitRotate(SDNode *N);
258     SDValue visitCTLZ(SDNode *N);
259     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
260     SDValue visitCTTZ(SDNode *N);
261     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
262     SDValue visitCTPOP(SDNode *N);
263     SDValue visitSELECT(SDNode *N);
264     SDValue visitVSELECT(SDNode *N);
265     SDValue visitSELECT_CC(SDNode *N);
266     SDValue visitSETCC(SDNode *N);
267     SDValue visitSIGN_EXTEND(SDNode *N);
268     SDValue visitZERO_EXTEND(SDNode *N);
269     SDValue visitANY_EXTEND(SDNode *N);
270     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
271     SDValue visitTRUNCATE(SDNode *N);
272     SDValue visitBITCAST(SDNode *N);
273     SDValue visitBUILD_PAIR(SDNode *N);
274     SDValue visitFADD(SDNode *N);
275     SDValue visitFSUB(SDNode *N);
276     SDValue visitFMUL(SDNode *N);
277     SDValue visitFMA(SDNode *N);
278     SDValue visitFDIV(SDNode *N);
279     SDValue visitFREM(SDNode *N);
280     SDValue visitFSQRT(SDNode *N);
281     SDValue visitFCOPYSIGN(SDNode *N);
282     SDValue visitSINT_TO_FP(SDNode *N);
283     SDValue visitUINT_TO_FP(SDNode *N);
284     SDValue visitFP_TO_SINT(SDNode *N);
285     SDValue visitFP_TO_UINT(SDNode *N);
286     SDValue visitFP_ROUND(SDNode *N);
287     SDValue visitFP_ROUND_INREG(SDNode *N);
288     SDValue visitFP_EXTEND(SDNode *N);
289     SDValue visitFNEG(SDNode *N);
290     SDValue visitFABS(SDNode *N);
291     SDValue visitFCEIL(SDNode *N);
292     SDValue visitFTRUNC(SDNode *N);
293     SDValue visitFFLOOR(SDNode *N);
294     SDValue visitFMINNUM(SDNode *N);
295     SDValue visitFMAXNUM(SDNode *N);
296     SDValue visitBRCOND(SDNode *N);
297     SDValue visitBR_CC(SDNode *N);
298     SDValue visitLOAD(SDNode *N);
299     SDValue visitSTORE(SDNode *N);
300     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
301     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
302     SDValue visitBUILD_VECTOR(SDNode *N);
303     SDValue visitCONCAT_VECTORS(SDNode *N);
304     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
305     SDValue visitVECTOR_SHUFFLE(SDNode *N);
306     SDValue visitSCALAR_TO_VECTOR(SDNode *N);
307     SDValue visitINSERT_SUBVECTOR(SDNode *N);
308     SDValue visitMLOAD(SDNode *N);
309     SDValue visitMSTORE(SDNode *N);
310     SDValue visitMGATHER(SDNode *N);
311     SDValue visitMSCATTER(SDNode *N);
312     SDValue visitFP_TO_FP16(SDNode *N);
313
314     SDValue visitFADDForFMACombine(SDNode *N);
315     SDValue visitFSUBForFMACombine(SDNode *N);
316
317     SDValue XformToShuffleWithZero(SDNode *N);
318     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
319
320     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
321
322     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
323     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
324     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
325     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
326                              SDValue N3, ISD::CondCode CC,
327                              bool NotExtCompare = false);
328     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
329                           SDLoc DL, bool foldBooleans = true);
330
331     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
332                            SDValue &CC) const;
333     bool isOneUseSetCC(SDValue N) const;
334
335     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
336                                          unsigned HiOp);
337     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
338     SDValue CombineExtLoad(SDNode *N);
339     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
340     SDValue BuildSDIV(SDNode *N);
341     SDValue BuildSDIVPow2(SDNode *N);
342     SDValue BuildUDIV(SDNode *N);
343     SDValue BuildReciprocalEstimate(SDValue Op);
344     SDValue BuildRsqrtEstimate(SDValue Op);
345     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
346     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
347     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
348                                bool DemandHighBits = true);
349     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
350     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
351                               SDValue InnerPos, SDValue InnerNeg,
352                               unsigned PosOpcode, unsigned NegOpcode,
353                               SDLoc DL);
354     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
355     SDValue ReduceLoadWidth(SDNode *N);
356     SDValue ReduceLoadOpStoreWidth(SDNode *N);
357     SDValue TransformFPLoadStorePair(SDNode *N);
358     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
359     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
360
361     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
362
363     /// Walk up chain skipping non-aliasing memory nodes,
364     /// looking for aliasing nodes and adding them to the Aliases vector.
365     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
366                           SmallVectorImpl<SDValue> &Aliases);
367
368     /// Return true if there is any possibility that the two addresses overlap.
369     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
370
371     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
372     /// chain (aliasing node.)
373     SDValue FindBetterChain(SDNode *N, SDValue Chain);
374
375     /// Holds a pointer to an LSBaseSDNode as well as information on where it
376     /// is located in a sequence of memory operations connected by a chain.
377     struct MemOpLink {
378       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
379       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
380       // Ptr to the mem node.
381       LSBaseSDNode *MemNode;
382       // Offset from the base ptr.
383       int64_t OffsetFromBase;
384       // What is the sequence number of this mem node.
385       // Lowest mem operand in the DAG starts at zero.
386       unsigned SequenceNum;
387     };
388
389     /// This is a helper function for MergeConsecutiveStores. When the source
390     /// elements of the consecutive stores are all constants or all extracted
391     /// vector elements, try to merge them into one larger store.
392     /// \return True if a merged store was created.
393     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
394                                          EVT MemVT, unsigned NumElem,
395                                          bool IsConstantSrc, bool UseVector);
396
397     /// Merge consecutive store operations into a wide store.
398     /// This optimization uses wide integers or vectors when possible.
399     /// \return True if some memory operations were changed.
400     bool MergeConsecutiveStores(StoreSDNode *N);
401
402     /// \brief Try to transform a truncation where C is a constant:
403     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
404     ///
405     /// \p N needs to be a truncation and its first operand an AND. Other
406     /// requirements are checked by the function (e.g. that trunc is
407     /// single-use) and if missed an empty SDValue is returned.
408     SDValue distributeTruncateThroughAnd(SDNode *N);
409
410   public:
411     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
412         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
413           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
414       auto *F = DAG.getMachineFunction().getFunction();
415       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
416                     F->hasFnAttribute(Attribute::MinSize);
417     }
418
419     /// Runs the dag combiner on all nodes in the work list
420     void Run(CombineLevel AtLevel);
421
422     SelectionDAG &getDAG() const { return DAG; }
423
424     /// Returns a type large enough to hold any valid shift amount - before type
425     /// legalization these can be huge.
426     EVT getShiftAmountTy(EVT LHSTy) {
427       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
428       if (LHSTy.isVector())
429         return LHSTy;
430       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
431                         : TLI.getPointerTy();
432     }
433
434     /// This method returns true if we are running before type legalization or
435     /// if the specified VT is legal.
436     bool isTypeLegal(const EVT &VT) {
437       if (!LegalTypes) return true;
438       return TLI.isTypeLegal(VT);
439     }
440
441     /// Convenience wrapper around TargetLowering::getSetCCResultType
442     EVT getSetCCResultType(EVT VT) const {
443       return TLI.getSetCCResultType(*DAG.getContext(), VT);
444     }
445   };
446 }
447
448
449 namespace {
450 /// This class is a DAGUpdateListener that removes any deleted
451 /// nodes from the worklist.
452 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
453   DAGCombiner &DC;
454 public:
455   explicit WorklistRemover(DAGCombiner &dc)
456     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
457
458   void NodeDeleted(SDNode *N, SDNode *E) override {
459     DC.removeFromWorklist(N);
460   }
461 };
462 }
463
464 //===----------------------------------------------------------------------===//
465 //  TargetLowering::DAGCombinerInfo implementation
466 //===----------------------------------------------------------------------===//
467
468 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
469   ((DAGCombiner*)DC)->AddToWorklist(N);
470 }
471
472 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
473   ((DAGCombiner*)DC)->removeFromWorklist(N);
474 }
475
476 SDValue TargetLowering::DAGCombinerInfo::
477 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
478   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
479 }
480
481 SDValue TargetLowering::DAGCombinerInfo::
482 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
483   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
484 }
485
486
487 SDValue TargetLowering::DAGCombinerInfo::
488 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
489   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
490 }
491
492 void TargetLowering::DAGCombinerInfo::
493 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
494   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
495 }
496
497 //===----------------------------------------------------------------------===//
498 // Helper Functions
499 //===----------------------------------------------------------------------===//
500
501 void DAGCombiner::deleteAndRecombine(SDNode *N) {
502   removeFromWorklist(N);
503
504   // If the operands of this node are only used by the node, they will now be
505   // dead. Make sure to re-visit them and recursively delete dead nodes.
506   for (const SDValue &Op : N->ops())
507     // For an operand generating multiple values, one of the values may
508     // become dead allowing further simplification (e.g. split index
509     // arithmetic from an indexed load).
510     if (Op->hasOneUse() || Op->getNumValues() > 1)
511       AddToWorklist(Op.getNode());
512
513   DAG.DeleteNode(N);
514 }
515
516 /// Return 1 if we can compute the negated form of the specified expression for
517 /// the same cost as the expression itself, or 2 if we can compute the negated
518 /// form more cheaply than the expression itself.
519 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
520                                const TargetLowering &TLI,
521                                const TargetOptions *Options,
522                                unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return 2;
525
526   // Don't allow anything with multiple uses.
527   if (!Op.hasOneUse()) return 0;
528
529   // Don't recurse exponentially.
530   if (Depth > 6) return 0;
531
532   switch (Op.getOpcode()) {
533   default: return false;
534   case ISD::ConstantFP:
535     // Don't invert constant FP values after legalize.  The negated constant
536     // isn't necessarily legal.
537     return LegalOperations ? 0 : 1;
538   case ISD::FADD:
539     // FIXME: determine better conditions for this xform.
540     if (!Options->UnsafeFPMath) return 0;
541
542     // After operation legalization, it might not be legal to create new FSUBs.
543     if (LegalOperations &&
544         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
545       return 0;
546
547     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
548     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
549                                     Options, Depth + 1))
550       return V;
551     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
552     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
553                               Depth + 1);
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     if (!Options->UnsafeFPMath) return 0;
557
558     // fold (fneg (fsub A, B)) -> (fsub B, A)
559     return 1;
560
561   case ISD::FMUL:
562   case ISD::FDIV:
563     if (Options->HonorSignDependentRoundingFPMath()) return 0;
564
565     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
566     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
567                                     Options, Depth + 1))
568       return V;
569
570     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
571                               Depth + 1);
572
573   case ISD::FP_EXTEND:
574   case ISD::FP_ROUND:
575   case ISD::FSIN:
576     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
577                               Depth + 1);
578   }
579 }
580
581 /// If isNegatibleForFree returns true, return the newly negated expression.
582 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
583                                     bool LegalOperations, unsigned Depth = 0) {
584   const TargetOptions &Options = DAG.getTarget().Options;
585   // fneg is removable even if it has multiple uses.
586   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
587
588   // Don't allow anything with multiple uses.
589   assert(Op.hasOneUse() && "Unknown reuse!");
590
591   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
592   switch (Op.getOpcode()) {
593   default: llvm_unreachable("Unknown code");
594   case ISD::ConstantFP: {
595     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
596     V.changeSign();
597     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
598   }
599   case ISD::FADD:
600     // FIXME: determine better conditions for this xform.
601     assert(Options.UnsafeFPMath);
602
603     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
604     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
605                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
606       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
607                          GetNegatedExpression(Op.getOperand(0), DAG,
608                                               LegalOperations, Depth+1),
609                          Op.getOperand(1));
610     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
611     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
612                        GetNegatedExpression(Op.getOperand(1), DAG,
613                                             LegalOperations, Depth+1),
614                        Op.getOperand(0));
615   case ISD::FSUB:
616     // We can't turn -(A-B) into B-A when we honor signed zeros.
617     assert(Options.UnsafeFPMath);
618
619     // fold (fneg (fsub 0, B)) -> B
620     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
621       if (N0CFP->getValueAPF().isZero())
622         return Op.getOperand(1);
623
624     // fold (fneg (fsub A, B)) -> (fsub B, A)
625     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
626                        Op.getOperand(1), Op.getOperand(0));
627
628   case ISD::FMUL:
629   case ISD::FDIV:
630     assert(!Options.HonorSignDependentRoundingFPMath());
631
632     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
633     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
634                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
635       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
636                          GetNegatedExpression(Op.getOperand(0), DAG,
637                                               LegalOperations, Depth+1),
638                          Op.getOperand(1));
639
640     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
641     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
642                        Op.getOperand(0),
643                        GetNegatedExpression(Op.getOperand(1), DAG,
644                                             LegalOperations, Depth+1));
645
646   case ISD::FP_EXTEND:
647   case ISD::FSIN:
648     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
649                        GetNegatedExpression(Op.getOperand(0), DAG,
650                                             LegalOperations, Depth+1));
651   case ISD::FP_ROUND:
652       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
653                          GetNegatedExpression(Op.getOperand(0), DAG,
654                                               LegalOperations, Depth+1),
655                          Op.getOperand(1));
656   }
657 }
658
659 // Return true if this node is a setcc, or is a select_cc
660 // that selects between the target values used for true and false, making it
661 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
662 // the appropriate nodes based on the type of node we are checking. This
663 // simplifies life a bit for the callers.
664 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
665                                     SDValue &CC) const {
666   if (N.getOpcode() == ISD::SETCC) {
667     LHS = N.getOperand(0);
668     RHS = N.getOperand(1);
669     CC  = N.getOperand(2);
670     return true;
671   }
672
673   if (N.getOpcode() != ISD::SELECT_CC ||
674       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
675       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
676     return false;
677
678   if (TLI.getBooleanContents(N.getValueType()) ==
679       TargetLowering::UndefinedBooleanContent)
680     return false;
681
682   LHS = N.getOperand(0);
683   RHS = N.getOperand(1);
684   CC  = N.getOperand(4);
685   return true;
686 }
687
688 /// Return true if this is a SetCC-equivalent operation with only one use.
689 /// If this is true, it allows the users to invert the operation for free when
690 /// it is profitable to do so.
691 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
692   SDValue N0, N1, N2;
693   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
694     return true;
695   return false;
696 }
697
698 /// Returns true if N is a BUILD_VECTOR node whose
699 /// elements are all the same constant or undefined.
700 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
701   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
702   if (!C)
703     return false;
704
705   APInt SplatUndef;
706   unsigned SplatBitSize;
707   bool HasAnyUndefs;
708   EVT EltVT = N->getValueType(0).getVectorElementType();
709   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
710                              HasAnyUndefs) &&
711           EltVT.getSizeInBits() >= SplatBitSize);
712 }
713
714 // \brief Returns the SDNode if it is a constant integer BuildVector
715 // or constant integer.
716 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
717   if (isa<ConstantSDNode>(N))
718     return N.getNode();
719   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
720     return N.getNode();
721   return nullptr;
722 }
723
724 // \brief Returns the SDNode if it is a constant float BuildVector
725 // or constant float.
726 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
727   if (isa<ConstantFPSDNode>(N))
728     return N.getNode();
729   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
730     return N.getNode();
731   return nullptr;
732 }
733
734 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
735 // int.
736 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
737   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
738     return CN;
739
740   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
741     BitVector UndefElements;
742     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
743
744     // BuildVectors can truncate their operands. Ignore that case here.
745     // FIXME: We blindly ignore splats which include undef which is overly
746     // pessimistic.
747     if (CN && UndefElements.none() &&
748         CN->getValueType(0) == N.getValueType().getScalarType())
749       return CN;
750   }
751
752   return nullptr;
753 }
754
755 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
756 // float.
757 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
758   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
759     return CN;
760
761   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
762     BitVector UndefElements;
763     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
764
765     if (CN && UndefElements.none())
766       return CN;
767   }
768
769   return nullptr;
770 }
771
772 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
773                                     SDValue N0, SDValue N1) {
774   EVT VT = N0.getValueType();
775   if (N0.getOpcode() == Opc) {
776     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
777       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
778         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
779         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
780           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
781         return SDValue();
782       }
783       if (N0.hasOneUse()) {
784         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
785         // use
786         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
787         if (!OpNode.getNode())
788           return SDValue();
789         AddToWorklist(OpNode.getNode());
790         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
791       }
792     }
793   }
794
795   if (N1.getOpcode() == Opc) {
796     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
797       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
798         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
799         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
800           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
801         return SDValue();
802       }
803       if (N1.hasOneUse()) {
804         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
805         // use
806         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
807         if (!OpNode.getNode())
808           return SDValue();
809         AddToWorklist(OpNode.getNode());
810         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
811       }
812     }
813   }
814
815   return SDValue();
816 }
817
818 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
819                                bool AddTo) {
820   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
821   ++NodesCombined;
822   DEBUG(dbgs() << "\nReplacing.1 ";
823         N->dump(&DAG);
824         dbgs() << "\nWith: ";
825         To[0].getNode()->dump(&DAG);
826         dbgs() << " and " << NumTo-1 << " other values\n");
827   for (unsigned i = 0, e = NumTo; i != e; ++i)
828     assert((!To[i].getNode() ||
829             N->getValueType(i) == To[i].getValueType()) &&
830            "Cannot combine value to value of different type!");
831
832   WorklistRemover DeadNodes(*this);
833   DAG.ReplaceAllUsesWith(N, To);
834   if (AddTo) {
835     // Push the new nodes and any users onto the worklist
836     for (unsigned i = 0, e = NumTo; i != e; ++i) {
837       if (To[i].getNode()) {
838         AddToWorklist(To[i].getNode());
839         AddUsersToWorklist(To[i].getNode());
840       }
841     }
842   }
843
844   // Finally, if the node is now dead, remove it from the graph.  The node
845   // may not be dead if the replacement process recursively simplified to
846   // something else needing this node.
847   if (N->use_empty())
848     deleteAndRecombine(N);
849   return SDValue(N, 0);
850 }
851
852 void DAGCombiner::
853 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
854   // Replace all uses.  If any nodes become isomorphic to other nodes and
855   // are deleted, make sure to remove them from our worklist.
856   WorklistRemover DeadNodes(*this);
857   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
858
859   // Push the new node and any (possibly new) users onto the worklist.
860   AddToWorklist(TLO.New.getNode());
861   AddUsersToWorklist(TLO.New.getNode());
862
863   // Finally, if the node is now dead, remove it from the graph.  The node
864   // may not be dead if the replacement process recursively simplified to
865   // something else needing this node.
866   if (TLO.Old.getNode()->use_empty())
867     deleteAndRecombine(TLO.Old.getNode());
868 }
869
870 /// Check the specified integer node value to see if it can be simplified or if
871 /// things it uses can be simplified by bit propagation. If so, return true.
872 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
873   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
874   APInt KnownZero, KnownOne;
875   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
876     return false;
877
878   // Revisit the node.
879   AddToWorklist(Op.getNode());
880
881   // Replace the old value with the new one.
882   ++NodesCombined;
883   DEBUG(dbgs() << "\nReplacing.2 ";
884         TLO.Old.getNode()->dump(&DAG);
885         dbgs() << "\nWith: ";
886         TLO.New.getNode()->dump(&DAG);
887         dbgs() << '\n');
888
889   CommitTargetLoweringOpt(TLO);
890   return true;
891 }
892
893 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
894   SDLoc dl(Load);
895   EVT VT = Load->getValueType(0);
896   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
897
898   DEBUG(dbgs() << "\nReplacing.9 ";
899         Load->dump(&DAG);
900         dbgs() << "\nWith: ";
901         Trunc.getNode()->dump(&DAG);
902         dbgs() << '\n');
903   WorklistRemover DeadNodes(*this);
904   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
905   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
906   deleteAndRecombine(Load);
907   AddToWorklist(Trunc.getNode());
908 }
909
910 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
911   Replace = false;
912   SDLoc dl(Op);
913   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
914     EVT MemVT = LD->getMemoryVT();
915     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
916       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
917                                                        : ISD::EXTLOAD)
918       : LD->getExtensionType();
919     Replace = true;
920     return DAG.getExtLoad(ExtType, dl, PVT,
921                           LD->getChain(), LD->getBasePtr(),
922                           MemVT, LD->getMemOperand());
923   }
924
925   unsigned Opc = Op.getOpcode();
926   switch (Opc) {
927   default: break;
928   case ISD::AssertSext:
929     return DAG.getNode(ISD::AssertSext, dl, PVT,
930                        SExtPromoteOperand(Op.getOperand(0), PVT),
931                        Op.getOperand(1));
932   case ISD::AssertZext:
933     return DAG.getNode(ISD::AssertZext, dl, PVT,
934                        ZExtPromoteOperand(Op.getOperand(0), PVT),
935                        Op.getOperand(1));
936   case ISD::Constant: {
937     unsigned ExtOpc =
938       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
939     return DAG.getNode(ExtOpc, dl, PVT, Op);
940   }
941   }
942
943   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
944     return SDValue();
945   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
946 }
947
948 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
949   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
950     return SDValue();
951   EVT OldVT = Op.getValueType();
952   SDLoc dl(Op);
953   bool Replace = false;
954   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
955   if (!NewOp.getNode())
956     return SDValue();
957   AddToWorklist(NewOp.getNode());
958
959   if (Replace)
960     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
961   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
962                      DAG.getValueType(OldVT));
963 }
964
965 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
966   EVT OldVT = Op.getValueType();
967   SDLoc dl(Op);
968   bool Replace = false;
969   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
970   if (!NewOp.getNode())
971     return SDValue();
972   AddToWorklist(NewOp.getNode());
973
974   if (Replace)
975     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
976   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
977 }
978
979 /// Promote the specified integer binary operation if the target indicates it is
980 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
981 /// i32 since i16 instructions are longer.
982 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
983   if (!LegalOperations)
984     return SDValue();
985
986   EVT VT = Op.getValueType();
987   if (VT.isVector() || !VT.isInteger())
988     return SDValue();
989
990   // If operation type is 'undesirable', e.g. i16 on x86, consider
991   // promoting it.
992   unsigned Opc = Op.getOpcode();
993   if (TLI.isTypeDesirableForOp(Opc, VT))
994     return SDValue();
995
996   EVT PVT = VT;
997   // Consult target whether it is a good idea to promote this operation and
998   // what's the right type to promote it to.
999   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1000     assert(PVT != VT && "Don't know what type to promote to!");
1001
1002     bool Replace0 = false;
1003     SDValue N0 = Op.getOperand(0);
1004     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1005     if (!NN0.getNode())
1006       return SDValue();
1007
1008     bool Replace1 = false;
1009     SDValue N1 = Op.getOperand(1);
1010     SDValue NN1;
1011     if (N0 == N1)
1012       NN1 = NN0;
1013     else {
1014       NN1 = PromoteOperand(N1, PVT, Replace1);
1015       if (!NN1.getNode())
1016         return SDValue();
1017     }
1018
1019     AddToWorklist(NN0.getNode());
1020     if (NN1.getNode())
1021       AddToWorklist(NN1.getNode());
1022
1023     if (Replace0)
1024       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1025     if (Replace1)
1026       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1027
1028     DEBUG(dbgs() << "\nPromoting ";
1029           Op.getNode()->dump(&DAG));
1030     SDLoc dl(Op);
1031     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1032                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1033   }
1034   return SDValue();
1035 }
1036
1037 /// Promote the specified integer shift operation if the target indicates it is
1038 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1039 /// i32 since i16 instructions are longer.
1040 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1041   if (!LegalOperations)
1042     return SDValue();
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return SDValue();
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return SDValue();
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     bool Replace = false;
1061     SDValue N0 = Op.getOperand(0);
1062     if (Opc == ISD::SRA)
1063       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1064     else if (Opc == ISD::SRL)
1065       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1066     else
1067       N0 = PromoteOperand(N0, PVT, Replace);
1068     if (!N0.getNode())
1069       return SDValue();
1070
1071     AddToWorklist(N0.getNode());
1072     if (Replace)
1073       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1074
1075     DEBUG(dbgs() << "\nPromoting ";
1076           Op.getNode()->dump(&DAG));
1077     SDLoc dl(Op);
1078     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1079                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1080   }
1081   return SDValue();
1082 }
1083
1084 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1085   if (!LegalOperations)
1086     return SDValue();
1087
1088   EVT VT = Op.getValueType();
1089   if (VT.isVector() || !VT.isInteger())
1090     return SDValue();
1091
1092   // If operation type is 'undesirable', e.g. i16 on x86, consider
1093   // promoting it.
1094   unsigned Opc = Op.getOpcode();
1095   if (TLI.isTypeDesirableForOp(Opc, VT))
1096     return SDValue();
1097
1098   EVT PVT = VT;
1099   // Consult target whether it is a good idea to promote this operation and
1100   // what's the right type to promote it to.
1101   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1102     assert(PVT != VT && "Don't know what type to promote to!");
1103     // fold (aext (aext x)) -> (aext x)
1104     // fold (aext (zext x)) -> (zext x)
1105     // fold (aext (sext x)) -> (sext x)
1106     DEBUG(dbgs() << "\nPromoting ";
1107           Op.getNode()->dump(&DAG));
1108     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1109   }
1110   return SDValue();
1111 }
1112
1113 bool DAGCombiner::PromoteLoad(SDValue Op) {
1114   if (!LegalOperations)
1115     return false;
1116
1117   EVT VT = Op.getValueType();
1118   if (VT.isVector() || !VT.isInteger())
1119     return false;
1120
1121   // If operation type is 'undesirable', e.g. i16 on x86, consider
1122   // promoting it.
1123   unsigned Opc = Op.getOpcode();
1124   if (TLI.isTypeDesirableForOp(Opc, VT))
1125     return false;
1126
1127   EVT PVT = VT;
1128   // Consult target whether it is a good idea to promote this operation and
1129   // what's the right type to promote it to.
1130   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1131     assert(PVT != VT && "Don't know what type to promote to!");
1132
1133     SDLoc dl(Op);
1134     SDNode *N = Op.getNode();
1135     LoadSDNode *LD = cast<LoadSDNode>(N);
1136     EVT MemVT = LD->getMemoryVT();
1137     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1138       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1139                                                        : ISD::EXTLOAD)
1140       : LD->getExtensionType();
1141     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1142                                    LD->getChain(), LD->getBasePtr(),
1143                                    MemVT, LD->getMemOperand());
1144     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1145
1146     DEBUG(dbgs() << "\nPromoting ";
1147           N->dump(&DAG);
1148           dbgs() << "\nTo: ";
1149           Result.getNode()->dump(&DAG);
1150           dbgs() << '\n');
1151     WorklistRemover DeadNodes(*this);
1152     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1153     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1154     deleteAndRecombine(N);
1155     AddToWorklist(Result.getNode());
1156     return true;
1157   }
1158   return false;
1159 }
1160
1161 /// \brief Recursively delete a node which has no uses and any operands for
1162 /// which it is the only use.
1163 ///
1164 /// Note that this both deletes the nodes and removes them from the worklist.
1165 /// It also adds any nodes who have had a user deleted to the worklist as they
1166 /// may now have only one use and subject to other combines.
1167 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1168   if (!N->use_empty())
1169     return false;
1170
1171   SmallSetVector<SDNode *, 16> Nodes;
1172   Nodes.insert(N);
1173   do {
1174     N = Nodes.pop_back_val();
1175     if (!N)
1176       continue;
1177
1178     if (N->use_empty()) {
1179       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1180         Nodes.insert(N->getOperand(i).getNode());
1181
1182       removeFromWorklist(N);
1183       DAG.DeleteNode(N);
1184     } else {
1185       AddToWorklist(N);
1186     }
1187   } while (!Nodes.empty());
1188   return true;
1189 }
1190
1191 //===----------------------------------------------------------------------===//
1192 //  Main DAG Combiner implementation
1193 //===----------------------------------------------------------------------===//
1194
1195 void DAGCombiner::Run(CombineLevel AtLevel) {
1196   // set the instance variables, so that the various visit routines may use it.
1197   Level = AtLevel;
1198   LegalOperations = Level >= AfterLegalizeVectorOps;
1199   LegalTypes = Level >= AfterLegalizeTypes;
1200
1201   // Add all the dag nodes to the worklist.
1202   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1203        E = DAG.allnodes_end(); I != E; ++I)
1204     AddToWorklist(I);
1205
1206   // Create a dummy node (which is not added to allnodes), that adds a reference
1207   // to the root node, preventing it from being deleted, and tracking any
1208   // changes of the root.
1209   HandleSDNode Dummy(DAG.getRoot());
1210
1211   // while the worklist isn't empty, find a node and
1212   // try and combine it.
1213   while (!WorklistMap.empty()) {
1214     SDNode *N;
1215     // The Worklist holds the SDNodes in order, but it may contain null entries.
1216     do {
1217       N = Worklist.pop_back_val();
1218     } while (!N);
1219
1220     bool GoodWorklistEntry = WorklistMap.erase(N);
1221     (void)GoodWorklistEntry;
1222     assert(GoodWorklistEntry &&
1223            "Found a worklist entry without a corresponding map entry!");
1224
1225     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1226     // N is deleted from the DAG, since they too may now be dead or may have a
1227     // reduced number of uses, allowing other xforms.
1228     if (recursivelyDeleteUnusedNodes(N))
1229       continue;
1230
1231     WorklistRemover DeadNodes(*this);
1232
1233     // If this combine is running after legalizing the DAG, re-legalize any
1234     // nodes pulled off the worklist.
1235     if (Level == AfterLegalizeDAG) {
1236       SmallSetVector<SDNode *, 16> UpdatedNodes;
1237       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1238
1239       for (SDNode *LN : UpdatedNodes) {
1240         AddToWorklist(LN);
1241         AddUsersToWorklist(LN);
1242       }
1243       if (!NIsValid)
1244         continue;
1245     }
1246
1247     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1248
1249     // Add any operands of the new node which have not yet been combined to the
1250     // worklist as well. Because the worklist uniques things already, this
1251     // won't repeatedly process the same operand.
1252     CombinedNodes.insert(N);
1253     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1254       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1255         AddToWorklist(N->getOperand(i).getNode());
1256
1257     SDValue RV = combine(N);
1258
1259     if (!RV.getNode())
1260       continue;
1261
1262     ++NodesCombined;
1263
1264     // If we get back the same node we passed in, rather than a new node or
1265     // zero, we know that the node must have defined multiple values and
1266     // CombineTo was used.  Since CombineTo takes care of the worklist
1267     // mechanics for us, we have no work to do in this case.
1268     if (RV.getNode() == N)
1269       continue;
1270
1271     assert(N->getOpcode() != ISD::DELETED_NODE &&
1272            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1273            "Node was deleted but visit returned new node!");
1274
1275     DEBUG(dbgs() << " ... into: ";
1276           RV.getNode()->dump(&DAG));
1277
1278     // Transfer debug value.
1279     DAG.TransferDbgValues(SDValue(N, 0), RV);
1280     if (N->getNumValues() == RV.getNode()->getNumValues())
1281       DAG.ReplaceAllUsesWith(N, RV.getNode());
1282     else {
1283       assert(N->getValueType(0) == RV.getValueType() &&
1284              N->getNumValues() == 1 && "Type mismatch");
1285       SDValue OpV = RV;
1286       DAG.ReplaceAllUsesWith(N, &OpV);
1287     }
1288
1289     // Push the new node and any users onto the worklist
1290     AddToWorklist(RV.getNode());
1291     AddUsersToWorklist(RV.getNode());
1292
1293     // Finally, if the node is now dead, remove it from the graph.  The node
1294     // may not be dead if the replacement process recursively simplified to
1295     // something else needing this node. This will also take care of adding any
1296     // operands which have lost a user to the worklist.
1297     recursivelyDeleteUnusedNodes(N);
1298   }
1299
1300   // If the root changed (e.g. it was a dead load, update the root).
1301   DAG.setRoot(Dummy.getValue());
1302   DAG.RemoveDeadNodes();
1303 }
1304
1305 SDValue DAGCombiner::visit(SDNode *N) {
1306   switch (N->getOpcode()) {
1307   default: break;
1308   case ISD::TokenFactor:        return visitTokenFactor(N);
1309   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1310   case ISD::ADD:                return visitADD(N);
1311   case ISD::SUB:                return visitSUB(N);
1312   case ISD::ADDC:               return visitADDC(N);
1313   case ISD::SUBC:               return visitSUBC(N);
1314   case ISD::ADDE:               return visitADDE(N);
1315   case ISD::SUBE:               return visitSUBE(N);
1316   case ISD::MUL:                return visitMUL(N);
1317   case ISD::SDIV:               return visitSDIV(N);
1318   case ISD::UDIV:               return visitUDIV(N);
1319   case ISD::SREM:               return visitSREM(N);
1320   case ISD::UREM:               return visitUREM(N);
1321   case ISD::MULHU:              return visitMULHU(N);
1322   case ISD::MULHS:              return visitMULHS(N);
1323   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1324   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1325   case ISD::SMULO:              return visitSMULO(N);
1326   case ISD::UMULO:              return visitUMULO(N);
1327   case ISD::SDIVREM:            return visitSDIVREM(N);
1328   case ISD::UDIVREM:            return visitUDIVREM(N);
1329   case ISD::AND:                return visitAND(N);
1330   case ISD::OR:                 return visitOR(N);
1331   case ISD::XOR:                return visitXOR(N);
1332   case ISD::SHL:                return visitSHL(N);
1333   case ISD::SRA:                return visitSRA(N);
1334   case ISD::SRL:                return visitSRL(N);
1335   case ISD::ROTR:
1336   case ISD::ROTL:               return visitRotate(N);
1337   case ISD::CTLZ:               return visitCTLZ(N);
1338   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1339   case ISD::CTTZ:               return visitCTTZ(N);
1340   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1341   case ISD::CTPOP:              return visitCTPOP(N);
1342   case ISD::SELECT:             return visitSELECT(N);
1343   case ISD::VSELECT:            return visitVSELECT(N);
1344   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1345   case ISD::SETCC:              return visitSETCC(N);
1346   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1347   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1348   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1349   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1350   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1351   case ISD::BITCAST:            return visitBITCAST(N);
1352   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1353   case ISD::FADD:               return visitFADD(N);
1354   case ISD::FSUB:               return visitFSUB(N);
1355   case ISD::FMUL:               return visitFMUL(N);
1356   case ISD::FMA:                return visitFMA(N);
1357   case ISD::FDIV:               return visitFDIV(N);
1358   case ISD::FREM:               return visitFREM(N);
1359   case ISD::FSQRT:              return visitFSQRT(N);
1360   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1361   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1362   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1363   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1364   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1365   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1366   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1367   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1368   case ISD::FNEG:               return visitFNEG(N);
1369   case ISD::FABS:               return visitFABS(N);
1370   case ISD::FFLOOR:             return visitFFLOOR(N);
1371   case ISD::FMINNUM:            return visitFMINNUM(N);
1372   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1373   case ISD::FCEIL:              return visitFCEIL(N);
1374   case ISD::FTRUNC:             return visitFTRUNC(N);
1375   case ISD::BRCOND:             return visitBRCOND(N);
1376   case ISD::BR_CC:              return visitBR_CC(N);
1377   case ISD::LOAD:               return visitLOAD(N);
1378   case ISD::STORE:              return visitSTORE(N);
1379   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1380   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1381   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1382   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1383   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1384   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1385   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1386   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1387   case ISD::MGATHER:            return visitMGATHER(N);
1388   case ISD::MLOAD:              return visitMLOAD(N);
1389   case ISD::MSCATTER:           return visitMSCATTER(N);
1390   case ISD::MSTORE:             return visitMSTORE(N);
1391   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1392   }
1393   return SDValue();
1394 }
1395
1396 SDValue DAGCombiner::combine(SDNode *N) {
1397   SDValue RV = visit(N);
1398
1399   // If nothing happened, try a target-specific DAG combine.
1400   if (!RV.getNode()) {
1401     assert(N->getOpcode() != ISD::DELETED_NODE &&
1402            "Node was deleted but visit returned NULL!");
1403
1404     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1405         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1406
1407       // Expose the DAG combiner to the target combiner impls.
1408       TargetLowering::DAGCombinerInfo
1409         DagCombineInfo(DAG, Level, false, this);
1410
1411       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1412     }
1413   }
1414
1415   // If nothing happened still, try promoting the operation.
1416   if (!RV.getNode()) {
1417     switch (N->getOpcode()) {
1418     default: break;
1419     case ISD::ADD:
1420     case ISD::SUB:
1421     case ISD::MUL:
1422     case ISD::AND:
1423     case ISD::OR:
1424     case ISD::XOR:
1425       RV = PromoteIntBinOp(SDValue(N, 0));
1426       break;
1427     case ISD::SHL:
1428     case ISD::SRA:
1429     case ISD::SRL:
1430       RV = PromoteIntShiftOp(SDValue(N, 0));
1431       break;
1432     case ISD::SIGN_EXTEND:
1433     case ISD::ZERO_EXTEND:
1434     case ISD::ANY_EXTEND:
1435       RV = PromoteExtend(SDValue(N, 0));
1436       break;
1437     case ISD::LOAD:
1438       if (PromoteLoad(SDValue(N, 0)))
1439         RV = SDValue(N, 0);
1440       break;
1441     }
1442   }
1443
1444   // If N is a commutative binary node, try commuting it to enable more
1445   // sdisel CSE.
1446   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1447       N->getNumValues() == 1) {
1448     SDValue N0 = N->getOperand(0);
1449     SDValue N1 = N->getOperand(1);
1450
1451     // Constant operands are canonicalized to RHS.
1452     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1453       SDValue Ops[] = {N1, N0};
1454       SDNode *CSENode;
1455       if (auto *FlagsNode = dyn_cast<SDNodeWithFlags>(N)) {
1456         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1457                                       Ops, &FlagsNode->Flags);
1458       } else {
1459         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1460       }
1461       if (CSENode)
1462         return SDValue(CSENode, 0);
1463     }
1464   }
1465
1466   return RV;
1467 }
1468
1469 /// Given a node, return its input chain if it has one, otherwise return a null
1470 /// sd operand.
1471 static SDValue getInputChainForNode(SDNode *N) {
1472   if (unsigned NumOps = N->getNumOperands()) {
1473     if (N->getOperand(0).getValueType() == MVT::Other)
1474       return N->getOperand(0);
1475     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1476       return N->getOperand(NumOps-1);
1477     for (unsigned i = 1; i < NumOps-1; ++i)
1478       if (N->getOperand(i).getValueType() == MVT::Other)
1479         return N->getOperand(i);
1480   }
1481   return SDValue();
1482 }
1483
1484 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1485   // If N has two operands, where one has an input chain equal to the other,
1486   // the 'other' chain is redundant.
1487   if (N->getNumOperands() == 2) {
1488     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1489       return N->getOperand(0);
1490     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1491       return N->getOperand(1);
1492   }
1493
1494   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1495   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1496   SmallPtrSet<SDNode*, 16> SeenOps;
1497   bool Changed = false;             // If we should replace this token factor.
1498
1499   // Start out with this token factor.
1500   TFs.push_back(N);
1501
1502   // Iterate through token factors.  The TFs grows when new token factors are
1503   // encountered.
1504   for (unsigned i = 0; i < TFs.size(); ++i) {
1505     SDNode *TF = TFs[i];
1506
1507     // Check each of the operands.
1508     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1509       SDValue Op = TF->getOperand(i);
1510
1511       switch (Op.getOpcode()) {
1512       case ISD::EntryToken:
1513         // Entry tokens don't need to be added to the list. They are
1514         // redundant.
1515         Changed = true;
1516         break;
1517
1518       case ISD::TokenFactor:
1519         if (Op.hasOneUse() &&
1520             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1521           // Queue up for processing.
1522           TFs.push_back(Op.getNode());
1523           // Clean up in case the token factor is removed.
1524           AddToWorklist(Op.getNode());
1525           Changed = true;
1526           break;
1527         }
1528         // Fall thru
1529
1530       default:
1531         // Only add if it isn't already in the list.
1532         if (SeenOps.insert(Op.getNode()).second)
1533           Ops.push_back(Op);
1534         else
1535           Changed = true;
1536         break;
1537       }
1538     }
1539   }
1540
1541   SDValue Result;
1542
1543   // If we've changed things around then replace token factor.
1544   if (Changed) {
1545     if (Ops.empty()) {
1546       // The entry token is the only possible outcome.
1547       Result = DAG.getEntryNode();
1548     } else {
1549       // New and improved token factor.
1550       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1551     }
1552
1553     // Add users to worklist if AA is enabled, since it may introduce
1554     // a lot of new chained token factors while removing memory deps.
1555     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1556       : DAG.getSubtarget().useAA();
1557     return CombineTo(N, Result, UseAA /*add to worklist*/);
1558   }
1559
1560   return Result;
1561 }
1562
1563 /// MERGE_VALUES can always be eliminated.
1564 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1565   WorklistRemover DeadNodes(*this);
1566   // Replacing results may cause a different MERGE_VALUES to suddenly
1567   // be CSE'd with N, and carry its uses with it. Iterate until no
1568   // uses remain, to ensure that the node can be safely deleted.
1569   // First add the users of this node to the work list so that they
1570   // can be tried again once they have new operands.
1571   AddUsersToWorklist(N);
1572   do {
1573     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1574       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1575   } while (!N->use_empty());
1576   deleteAndRecombine(N);
1577   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1578 }
1579
1580 SDValue DAGCombiner::visitADD(SDNode *N) {
1581   SDValue N0 = N->getOperand(0);
1582   SDValue N1 = N->getOperand(1);
1583   EVT VT = N0.getValueType();
1584
1585   // fold vector ops
1586   if (VT.isVector()) {
1587     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1588       return FoldedVOp;
1589
1590     // fold (add x, 0) -> x, vector edition
1591     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1592       return N0;
1593     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1594       return N1;
1595   }
1596
1597   // fold (add x, undef) -> undef
1598   if (N0.getOpcode() == ISD::UNDEF)
1599     return N0;
1600   if (N1.getOpcode() == ISD::UNDEF)
1601     return N1;
1602   // fold (add c1, c2) -> c1+c2
1603   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1604   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1605   if (N0C && N1C)
1606     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1607   // canonicalize constant to RHS
1608   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1609      !isConstantIntBuildVectorOrConstantInt(N1))
1610     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1611   // fold (add x, 0) -> x
1612   if (N1C && N1C->isNullValue())
1613     return N0;
1614   // fold (add Sym, c) -> Sym+c
1615   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1616     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1617         GA->getOpcode() == ISD::GlobalAddress)
1618       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1619                                   GA->getOffset() +
1620                                     (uint64_t)N1C->getSExtValue());
1621   // fold ((c1-A)+c2) -> (c1+c2)-A
1622   if (N1C && N0.getOpcode() == ISD::SUB)
1623     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1624       SDLoc DL(N);
1625       return DAG.getNode(ISD::SUB, DL, VT,
1626                          DAG.getConstant(N1C->getAPIntValue()+
1627                                          N0C->getAPIntValue(), DL, VT),
1628                          N0.getOperand(1));
1629     }
1630   // reassociate add
1631   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1632     return RADD;
1633   // fold ((0-A) + B) -> B-A
1634   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1635       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1636     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1637   // fold (A + (0-B)) -> A-B
1638   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1639       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1640     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1641   // fold (A+(B-A)) -> B
1642   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1643     return N1.getOperand(0);
1644   // fold ((B-A)+A) -> B
1645   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1646     return N0.getOperand(0);
1647   // fold (A+(B-(A+C))) to (B-C)
1648   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1649       N0 == N1.getOperand(1).getOperand(0))
1650     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1651                        N1.getOperand(1).getOperand(1));
1652   // fold (A+(B-(C+A))) to (B-C)
1653   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1654       N0 == N1.getOperand(1).getOperand(1))
1655     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1656                        N1.getOperand(1).getOperand(0));
1657   // fold (A+((B-A)+or-C)) to (B+or-C)
1658   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1659       N1.getOperand(0).getOpcode() == ISD::SUB &&
1660       N0 == N1.getOperand(0).getOperand(1))
1661     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1662                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1663
1664   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1665   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1666     SDValue N00 = N0.getOperand(0);
1667     SDValue N01 = N0.getOperand(1);
1668     SDValue N10 = N1.getOperand(0);
1669     SDValue N11 = N1.getOperand(1);
1670
1671     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1672       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1673                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1674                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1675   }
1676
1677   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1678     return SDValue(N, 0);
1679
1680   // fold (a+b) -> (a|b) iff a and b share no bits.
1681   if (VT.isInteger() && !VT.isVector()) {
1682     APInt LHSZero, LHSOne;
1683     APInt RHSZero, RHSOne;
1684     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1685
1686     if (LHSZero.getBoolValue()) {
1687       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1688
1689       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1690       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1691       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1692         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1693           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1694       }
1695     }
1696   }
1697
1698   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1699   if (N1.getOpcode() == ISD::SHL &&
1700       N1.getOperand(0).getOpcode() == ISD::SUB)
1701     if (ConstantSDNode *C =
1702           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1703       if (C->getAPIntValue() == 0)
1704         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1705                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1706                                        N1.getOperand(0).getOperand(1),
1707                                        N1.getOperand(1)));
1708   if (N0.getOpcode() == ISD::SHL &&
1709       N0.getOperand(0).getOpcode() == ISD::SUB)
1710     if (ConstantSDNode *C =
1711           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1712       if (C->getAPIntValue() == 0)
1713         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1714                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1715                                        N0.getOperand(0).getOperand(1),
1716                                        N0.getOperand(1)));
1717
1718   if (N1.getOpcode() == ISD::AND) {
1719     SDValue AndOp0 = N1.getOperand(0);
1720     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1721     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1722     unsigned DestBits = VT.getScalarType().getSizeInBits();
1723
1724     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1725     // and similar xforms where the inner op is either ~0 or 0.
1726     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1727       SDLoc DL(N);
1728       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1729     }
1730   }
1731
1732   // add (sext i1), X -> sub X, (zext i1)
1733   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1734       N0.getOperand(0).getValueType() == MVT::i1 &&
1735       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1736     SDLoc DL(N);
1737     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1738     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1739   }
1740
1741   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1742   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1743     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1744     if (TN->getVT() == MVT::i1) {
1745       SDLoc DL(N);
1746       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1747                                  DAG.getConstant(1, DL, VT));
1748       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1749     }
1750   }
1751
1752   return SDValue();
1753 }
1754
1755 SDValue DAGCombiner::visitADDC(SDNode *N) {
1756   SDValue N0 = N->getOperand(0);
1757   SDValue N1 = N->getOperand(1);
1758   EVT VT = N0.getValueType();
1759
1760   // If the flag result is dead, turn this into an ADD.
1761   if (!N->hasAnyUseOfValue(1))
1762     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1763                      DAG.getNode(ISD::CARRY_FALSE,
1764                                  SDLoc(N), MVT::Glue));
1765
1766   // canonicalize constant to RHS.
1767   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1768   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1769   if (N0C && !N1C)
1770     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1771
1772   // fold (addc x, 0) -> x + no carry out
1773   if (N1C && N1C->isNullValue())
1774     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1775                                         SDLoc(N), MVT::Glue));
1776
1777   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1778   APInt LHSZero, LHSOne;
1779   APInt RHSZero, RHSOne;
1780   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1781
1782   if (LHSZero.getBoolValue()) {
1783     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1784
1785     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1786     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1787     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1788       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1789                        DAG.getNode(ISD::CARRY_FALSE,
1790                                    SDLoc(N), MVT::Glue));
1791   }
1792
1793   return SDValue();
1794 }
1795
1796 SDValue DAGCombiner::visitADDE(SDNode *N) {
1797   SDValue N0 = N->getOperand(0);
1798   SDValue N1 = N->getOperand(1);
1799   SDValue CarryIn = N->getOperand(2);
1800
1801   // canonicalize constant to RHS
1802   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804   if (N0C && !N1C)
1805     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1806                        N1, N0, CarryIn);
1807
1808   // fold (adde x, y, false) -> (addc x, y)
1809   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1810     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1811
1812   return SDValue();
1813 }
1814
1815 // Since it may not be valid to emit a fold to zero for vector initializers
1816 // check if we can before folding.
1817 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1818                              SelectionDAG &DAG,
1819                              bool LegalOperations, bool LegalTypes) {
1820   if (!VT.isVector())
1821     return DAG.getConstant(0, DL, VT);
1822   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1823     return DAG.getConstant(0, DL, VT);
1824   return SDValue();
1825 }
1826
1827 SDValue DAGCombiner::visitSUB(SDNode *N) {
1828   SDValue N0 = N->getOperand(0);
1829   SDValue N1 = N->getOperand(1);
1830   EVT VT = N0.getValueType();
1831
1832   // fold vector ops
1833   if (VT.isVector()) {
1834     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1835       return FoldedVOp;
1836
1837     // fold (sub x, 0) -> x, vector edition
1838     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1839       return N0;
1840   }
1841
1842   // fold (sub x, x) -> 0
1843   // FIXME: Refactor this and xor and other similar operations together.
1844   if (N0 == N1)
1845     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1846   // fold (sub c1, c2) -> c1-c2
1847   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1848   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1849   if (N0C && N1C)
1850     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1851   // fold (sub x, c) -> (add x, -c)
1852   if (N1C) {
1853     SDLoc DL(N);
1854     return DAG.getNode(ISD::ADD, DL, VT, N0,
1855                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1856   }
1857   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1858   if (N0C && N0C->isAllOnesValue())
1859     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1860   // fold A-(A-B) -> B
1861   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1862     return N1.getOperand(1);
1863   // fold (A+B)-A -> B
1864   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1865     return N0.getOperand(1);
1866   // fold (A+B)-B -> A
1867   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1868     return N0.getOperand(0);
1869   // fold C2-(A+C1) -> (C2-C1)-A
1870   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1871     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1872   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1873     SDLoc DL(N);
1874     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1875                                    DL, VT);
1876     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1877                        N1.getOperand(0));
1878   }
1879   // fold ((A+(B+or-C))-B) -> A+or-C
1880   if (N0.getOpcode() == ISD::ADD &&
1881       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1882        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1883       N0.getOperand(1).getOperand(0) == N1)
1884     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1885                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1886   // fold ((A+(C+B))-B) -> A+C
1887   if (N0.getOpcode() == ISD::ADD &&
1888       N0.getOperand(1).getOpcode() == ISD::ADD &&
1889       N0.getOperand(1).getOperand(1) == N1)
1890     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1891                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1892   // fold ((A-(B-C))-C) -> A-B
1893   if (N0.getOpcode() == ISD::SUB &&
1894       N0.getOperand(1).getOpcode() == ISD::SUB &&
1895       N0.getOperand(1).getOperand(1) == N1)
1896     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1897                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1898
1899   // If either operand of a sub is undef, the result is undef
1900   if (N0.getOpcode() == ISD::UNDEF)
1901     return N0;
1902   if (N1.getOpcode() == ISD::UNDEF)
1903     return N1;
1904
1905   // If the relocation model supports it, consider symbol offsets.
1906   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1907     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1908       // fold (sub Sym, c) -> Sym-c
1909       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1910         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1911                                     GA->getOffset() -
1912                                       (uint64_t)N1C->getSExtValue());
1913       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1914       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1915         if (GA->getGlobal() == GB->getGlobal())
1916           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1917                                  SDLoc(N), VT);
1918     }
1919
1920   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1921   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1922     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1923     if (TN->getVT() == MVT::i1) {
1924       SDLoc DL(N);
1925       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1926                                  DAG.getConstant(1, DL, VT));
1927       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1928     }
1929   }
1930
1931   return SDValue();
1932 }
1933
1934 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1935   SDValue N0 = N->getOperand(0);
1936   SDValue N1 = N->getOperand(1);
1937   EVT VT = N0.getValueType();
1938
1939   // If the flag result is dead, turn this into an SUB.
1940   if (!N->hasAnyUseOfValue(1))
1941     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1942                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1943                                  MVT::Glue));
1944
1945   // fold (subc x, x) -> 0 + no borrow
1946   if (N0 == N1) {
1947     SDLoc DL(N);
1948     return CombineTo(N, DAG.getConstant(0, DL, VT),
1949                      DAG.getNode(ISD::CARRY_FALSE, DL,
1950                                  MVT::Glue));
1951   }
1952
1953   // fold (subc x, 0) -> x + no borrow
1954   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1955   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1956   if (N1C && N1C->isNullValue())
1957     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1958                                         MVT::Glue));
1959
1960   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1961   if (N0C && N0C->isAllOnesValue())
1962     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1963                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1964                                  MVT::Glue));
1965
1966   return SDValue();
1967 }
1968
1969 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1970   SDValue N0 = N->getOperand(0);
1971   SDValue N1 = N->getOperand(1);
1972   SDValue CarryIn = N->getOperand(2);
1973
1974   // fold (sube x, y, false) -> (subc x, y)
1975   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1976     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1977
1978   return SDValue();
1979 }
1980
1981 SDValue DAGCombiner::visitMUL(SDNode *N) {
1982   SDValue N0 = N->getOperand(0);
1983   SDValue N1 = N->getOperand(1);
1984   EVT VT = N0.getValueType();
1985
1986   // fold (mul x, undef) -> 0
1987   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1988     return DAG.getConstant(0, SDLoc(N), VT);
1989
1990   bool N0IsConst = false;
1991   bool N1IsConst = false;
1992   APInt ConstValue0, ConstValue1;
1993   // fold vector ops
1994   if (VT.isVector()) {
1995     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1996       return FoldedVOp;
1997
1998     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1999     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2000   } else {
2001     N0IsConst = isa<ConstantSDNode>(N0);
2002     if (N0IsConst)
2003       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2004     N1IsConst = isa<ConstantSDNode>(N1);
2005     if (N1IsConst)
2006       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2007   }
2008
2009   // fold (mul c1, c2) -> c1*c2
2010   if (N0IsConst && N1IsConst)
2011     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2012                                       N0.getNode(), N1.getNode());
2013
2014   // canonicalize constant to RHS (vector doesn't have to splat)
2015   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2016      !isConstantIntBuildVectorOrConstantInt(N1))
2017     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2018   // fold (mul x, 0) -> 0
2019   if (N1IsConst && ConstValue1 == 0)
2020     return N1;
2021   // We require a splat of the entire scalar bit width for non-contiguous
2022   // bit patterns.
2023   bool IsFullSplat =
2024     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2025   // fold (mul x, 1) -> x
2026   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2027     return N0;
2028   // fold (mul x, -1) -> 0-x
2029   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2030     SDLoc DL(N);
2031     return DAG.getNode(ISD::SUB, DL, VT,
2032                        DAG.getConstant(0, DL, VT), N0);
2033   }
2034   // fold (mul x, (1 << c)) -> x << c
2035   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2036     SDLoc DL(N);
2037     return DAG.getNode(ISD::SHL, DL, VT, N0,
2038                        DAG.getConstant(ConstValue1.logBase2(), DL,
2039                                        getShiftAmountTy(N0.getValueType())));
2040   }
2041   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2042   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2043     unsigned Log2Val = (-ConstValue1).logBase2();
2044     SDLoc DL(N);
2045     // FIXME: If the input is something that is easily negated (e.g. a
2046     // single-use add), we should put the negate there.
2047     return DAG.getNode(ISD::SUB, DL, VT,
2048                        DAG.getConstant(0, DL, VT),
2049                        DAG.getNode(ISD::SHL, DL, VT, N0,
2050                             DAG.getConstant(Log2Val, DL,
2051                                       getShiftAmountTy(N0.getValueType()))));
2052   }
2053
2054   APInt Val;
2055   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2056   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2057       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2058                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2059     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2060                              N1, N0.getOperand(1));
2061     AddToWorklist(C3.getNode());
2062     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2063                        N0.getOperand(0), C3);
2064   }
2065
2066   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2067   // use.
2068   {
2069     SDValue Sh(nullptr,0), Y(nullptr,0);
2070     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2071     if (N0.getOpcode() == ISD::SHL &&
2072         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2073                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2074         N0.getNode()->hasOneUse()) {
2075       Sh = N0; Y = N1;
2076     } else if (N1.getOpcode() == ISD::SHL &&
2077                isa<ConstantSDNode>(N1.getOperand(1)) &&
2078                N1.getNode()->hasOneUse()) {
2079       Sh = N1; Y = N0;
2080     }
2081
2082     if (Sh.getNode()) {
2083       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2084                                 Sh.getOperand(0), Y);
2085       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2086                          Mul, Sh.getOperand(1));
2087     }
2088   }
2089
2090   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2091   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2092       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2093                      isa<ConstantSDNode>(N0.getOperand(1))))
2094     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2095                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2096                                    N0.getOperand(0), N1),
2097                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2098                                    N0.getOperand(1), N1));
2099
2100   // reassociate mul
2101   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2102     return RMUL;
2103
2104   return SDValue();
2105 }
2106
2107 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2108   SDValue N0 = N->getOperand(0);
2109   SDValue N1 = N->getOperand(1);
2110   EVT VT = N->getValueType(0);
2111
2112   // fold vector ops
2113   if (VT.isVector())
2114     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2115       return FoldedVOp;
2116
2117   // fold (sdiv c1, c2) -> c1/c2
2118   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2119   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2120   if (N0C && N1C && !N1C->isNullValue())
2121     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2122   // fold (sdiv X, 1) -> X
2123   if (N1C && N1C->getAPIntValue() == 1LL)
2124     return N0;
2125   // fold (sdiv X, -1) -> 0-X
2126   if (N1C && N1C->isAllOnesValue()) {
2127     SDLoc DL(N);
2128     return DAG.getNode(ISD::SUB, DL, VT,
2129                        DAG.getConstant(0, DL, VT), N0);
2130   }
2131   // If we know the sign bits of both operands are zero, strength reduce to a
2132   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2133   if (!VT.isVector()) {
2134     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2135       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2136                          N0, N1);
2137   }
2138
2139   // fold (sdiv X, pow2) -> simple ops after legalize
2140   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2141                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2142     // If dividing by powers of two is cheap, then don't perform the following
2143     // fold.
2144     if (TLI.isPow2SDivCheap())
2145       return SDValue();
2146
2147     // Target-specific implementation of sdiv x, pow2.
2148     SDValue Res = BuildSDIVPow2(N);
2149     if (Res.getNode())
2150       return Res;
2151
2152     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2153     SDLoc DL(N);
2154
2155     // Splat the sign bit into the register
2156     SDValue SGN =
2157         DAG.getNode(ISD::SRA, DL, VT, N0,
2158                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2159                                     getShiftAmountTy(N0.getValueType())));
2160     AddToWorklist(SGN.getNode());
2161
2162     // Add (N0 < 0) ? abs2 - 1 : 0;
2163     SDValue SRL =
2164         DAG.getNode(ISD::SRL, DL, VT, SGN,
2165                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2166                                     getShiftAmountTy(SGN.getValueType())));
2167     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2168     AddToWorklist(SRL.getNode());
2169     AddToWorklist(ADD.getNode());    // Divide by pow2
2170     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2171                   DAG.getConstant(lg2, DL,
2172                                   getShiftAmountTy(ADD.getValueType())));
2173
2174     // If we're dividing by a positive value, we're done.  Otherwise, we must
2175     // negate the result.
2176     if (N1C->getAPIntValue().isNonNegative())
2177       return SRA;
2178
2179     AddToWorklist(SRA.getNode());
2180     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2181   }
2182
2183   // If integer divide is expensive and we satisfy the requirements, emit an
2184   // alternate sequence.
2185   if (N1C && !TLI.isIntDivCheap()) {
2186     SDValue Op = BuildSDIV(N);
2187     if (Op.getNode()) return Op;
2188   }
2189
2190   // undef / X -> 0
2191   if (N0.getOpcode() == ISD::UNDEF)
2192     return DAG.getConstant(0, SDLoc(N), VT);
2193   // X / undef -> undef
2194   if (N1.getOpcode() == ISD::UNDEF)
2195     return N1;
2196
2197   return SDValue();
2198 }
2199
2200 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2201   SDValue N0 = N->getOperand(0);
2202   SDValue N1 = N->getOperand(1);
2203   EVT VT = N->getValueType(0);
2204
2205   // fold vector ops
2206   if (VT.isVector())
2207     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2208       return FoldedVOp;
2209
2210   // fold (udiv c1, c2) -> c1/c2
2211   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2212   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2213   if (N0C && N1C && !N1C->isNullValue())
2214     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2215   // fold (udiv x, (1 << c)) -> x >>u c
2216   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2217     SDLoc DL(N);
2218     return DAG.getNode(ISD::SRL, DL, VT, N0,
2219                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2220                                        getShiftAmountTy(N0.getValueType())));
2221   }
2222   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2223   if (N1.getOpcode() == ISD::SHL) {
2224     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2225       if (SHC->getAPIntValue().isPowerOf2()) {
2226         EVT ADDVT = N1.getOperand(1).getValueType();
2227         SDLoc DL(N);
2228         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2229                                   N1.getOperand(1),
2230                                   DAG.getConstant(SHC->getAPIntValue()
2231                                                                   .logBase2(),
2232                                                   DL, ADDVT));
2233         AddToWorklist(Add.getNode());
2234         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2235       }
2236     }
2237   }
2238   // fold (udiv x, c) -> alternate
2239   if (N1C && !TLI.isIntDivCheap()) {
2240     SDValue Op = BuildUDIV(N);
2241     if (Op.getNode()) return Op;
2242   }
2243
2244   // undef / X -> 0
2245   if (N0.getOpcode() == ISD::UNDEF)
2246     return DAG.getConstant(0, SDLoc(N), VT);
2247   // X / undef -> undef
2248   if (N1.getOpcode() == ISD::UNDEF)
2249     return N1;
2250
2251   return SDValue();
2252 }
2253
2254 SDValue DAGCombiner::visitSREM(SDNode *N) {
2255   SDValue N0 = N->getOperand(0);
2256   SDValue N1 = N->getOperand(1);
2257   EVT VT = N->getValueType(0);
2258
2259   // fold (srem c1, c2) -> c1%c2
2260   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2261   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2262   if (N0C && N1C && !N1C->isNullValue())
2263     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2264   // If we know the sign bits of both operands are zero, strength reduce to a
2265   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2266   if (!VT.isVector()) {
2267     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2268       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2269   }
2270
2271   // If X/C can be simplified by the division-by-constant logic, lower
2272   // X%C to the equivalent of X-X/C*C.
2273   if (N1C && !N1C->isNullValue()) {
2274     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2275     AddToWorklist(Div.getNode());
2276     SDValue OptimizedDiv = combine(Div.getNode());
2277     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2278       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2279                                 OptimizedDiv, N1);
2280       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2281       AddToWorklist(Mul.getNode());
2282       return Sub;
2283     }
2284   }
2285
2286   // undef % X -> 0
2287   if (N0.getOpcode() == ISD::UNDEF)
2288     return DAG.getConstant(0, SDLoc(N), VT);
2289   // X % undef -> undef
2290   if (N1.getOpcode() == ISD::UNDEF)
2291     return N1;
2292
2293   return SDValue();
2294 }
2295
2296 SDValue DAGCombiner::visitUREM(SDNode *N) {
2297   SDValue N0 = N->getOperand(0);
2298   SDValue N1 = N->getOperand(1);
2299   EVT VT = N->getValueType(0);
2300
2301   // fold (urem c1, c2) -> c1%c2
2302   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2303   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2304   if (N0C && N1C && !N1C->isNullValue())
2305     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2306   // fold (urem x, pow2) -> (and x, pow2-1)
2307   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2308     SDLoc DL(N);
2309     return DAG.getNode(ISD::AND, DL, VT, N0,
2310                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2311   }
2312   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2313   if (N1.getOpcode() == ISD::SHL) {
2314     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2315       if (SHC->getAPIntValue().isPowerOf2()) {
2316         SDLoc DL(N);
2317         SDValue Add =
2318           DAG.getNode(ISD::ADD, DL, VT, N1,
2319                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2320                                  VT));
2321         AddToWorklist(Add.getNode());
2322         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2323       }
2324     }
2325   }
2326
2327   // If X/C can be simplified by the division-by-constant logic, lower
2328   // X%C to the equivalent of X-X/C*C.
2329   if (N1C && !N1C->isNullValue()) {
2330     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2331     AddToWorklist(Div.getNode());
2332     SDValue OptimizedDiv = combine(Div.getNode());
2333     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2334       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2335                                 OptimizedDiv, N1);
2336       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2337       AddToWorklist(Mul.getNode());
2338       return Sub;
2339     }
2340   }
2341
2342   // undef % X -> 0
2343   if (N0.getOpcode() == ISD::UNDEF)
2344     return DAG.getConstant(0, SDLoc(N), VT);
2345   // X % undef -> undef
2346   if (N1.getOpcode() == ISD::UNDEF)
2347     return N1;
2348
2349   return SDValue();
2350 }
2351
2352 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2353   SDValue N0 = N->getOperand(0);
2354   SDValue N1 = N->getOperand(1);
2355   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2356   EVT VT = N->getValueType(0);
2357   SDLoc DL(N);
2358
2359   // fold (mulhs x, 0) -> 0
2360   if (N1C && N1C->isNullValue())
2361     return N1;
2362   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2363   if (N1C && N1C->getAPIntValue() == 1) {
2364     SDLoc DL(N);
2365     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2366                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2367                                        DL,
2368                                        getShiftAmountTy(N0.getValueType())));
2369   }
2370   // fold (mulhs x, undef) -> 0
2371   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2372     return DAG.getConstant(0, SDLoc(N), VT);
2373
2374   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2375   // plus a shift.
2376   if (VT.isSimple() && !VT.isVector()) {
2377     MVT Simple = VT.getSimpleVT();
2378     unsigned SimpleSize = Simple.getSizeInBits();
2379     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2380     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2381       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2382       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2383       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2384       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2385             DAG.getConstant(SimpleSize, DL,
2386                             getShiftAmountTy(N1.getValueType())));
2387       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2388     }
2389   }
2390
2391   return SDValue();
2392 }
2393
2394 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2395   SDValue N0 = N->getOperand(0);
2396   SDValue N1 = N->getOperand(1);
2397   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2398   EVT VT = N->getValueType(0);
2399   SDLoc DL(N);
2400
2401   // fold (mulhu x, 0) -> 0
2402   if (N1C && N1C->isNullValue())
2403     return N1;
2404   // fold (mulhu x, 1) -> 0
2405   if (N1C && N1C->getAPIntValue() == 1)
2406     return DAG.getConstant(0, DL, N0.getValueType());
2407   // fold (mulhu x, undef) -> 0
2408   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2409     return DAG.getConstant(0, DL, VT);
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       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2419       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2420       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2421       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2422             DAG.getConstant(SimpleSize, DL,
2423                             getShiftAmountTy(N1.getValueType())));
2424       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2425     }
2426   }
2427
2428   return SDValue();
2429 }
2430
2431 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2432 /// give the opcodes for the two computations that are being performed. Return
2433 /// true if a simplification was made.
2434 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2435                                                 unsigned HiOp) {
2436   // If the high half is not needed, just compute the low half.
2437   bool HiExists = N->hasAnyUseOfValue(1);
2438   if (!HiExists &&
2439       (!LegalOperations ||
2440        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2441     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2442     return CombineTo(N, Res, Res);
2443   }
2444
2445   // If the low half is not needed, just compute the high half.
2446   bool LoExists = N->hasAnyUseOfValue(0);
2447   if (!LoExists &&
2448       (!LegalOperations ||
2449        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2450     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2451     return CombineTo(N, Res, Res);
2452   }
2453
2454   // If both halves are used, return as it is.
2455   if (LoExists && HiExists)
2456     return SDValue();
2457
2458   // If the two computed results can be simplified separately, separate them.
2459   if (LoExists) {
2460     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2461     AddToWorklist(Lo.getNode());
2462     SDValue LoOpt = combine(Lo.getNode());
2463     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2464         (!LegalOperations ||
2465          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2466       return CombineTo(N, LoOpt, LoOpt);
2467   }
2468
2469   if (HiExists) {
2470     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2471     AddToWorklist(Hi.getNode());
2472     SDValue HiOpt = combine(Hi.getNode());
2473     if (HiOpt.getNode() && HiOpt != Hi &&
2474         (!LegalOperations ||
2475          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2476       return CombineTo(N, HiOpt, HiOpt);
2477   }
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2483   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2484   if (Res.getNode()) return Res;
2485
2486   EVT VT = N->getValueType(0);
2487   SDLoc DL(N);
2488
2489   // If the type is twice as wide is legal, transform the mulhu to a wider
2490   // multiply plus a shift.
2491   if (VT.isSimple() && !VT.isVector()) {
2492     MVT Simple = VT.getSimpleVT();
2493     unsigned SimpleSize = Simple.getSizeInBits();
2494     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2495     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2496       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2497       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2498       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2499       // Compute the high part as N1.
2500       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2501             DAG.getConstant(SimpleSize, DL,
2502                             getShiftAmountTy(Lo.getValueType())));
2503       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2504       // Compute the low part as N0.
2505       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2506       return CombineTo(N, Lo, Hi);
2507     }
2508   }
2509
2510   return SDValue();
2511 }
2512
2513 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2514   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2515   if (Res.getNode()) return Res;
2516
2517   EVT VT = N->getValueType(0);
2518   SDLoc DL(N);
2519
2520   // If the type is twice as wide is legal, transform the mulhu to a wider
2521   // multiply plus a shift.
2522   if (VT.isSimple() && !VT.isVector()) {
2523     MVT Simple = VT.getSimpleVT();
2524     unsigned SimpleSize = Simple.getSizeInBits();
2525     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2526     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2527       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2528       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2529       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2530       // Compute the high part as N1.
2531       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2532             DAG.getConstant(SimpleSize, DL,
2533                             getShiftAmountTy(Lo.getValueType())));
2534       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2535       // Compute the low part as N0.
2536       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2537       return CombineTo(N, Lo, Hi);
2538     }
2539   }
2540
2541   return SDValue();
2542 }
2543
2544 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2545   // (smulo x, 2) -> (saddo x, x)
2546   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2547     if (C2->getAPIntValue() == 2)
2548       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2549                          N->getOperand(0), N->getOperand(0));
2550
2551   return SDValue();
2552 }
2553
2554 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2555   // (umulo x, 2) -> (uaddo x, x)
2556   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2557     if (C2->getAPIntValue() == 2)
2558       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2559                          N->getOperand(0), N->getOperand(0));
2560
2561   return SDValue();
2562 }
2563
2564 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2565   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2566   if (Res.getNode()) return Res;
2567
2568   return SDValue();
2569 }
2570
2571 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2572   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2573   if (Res.getNode()) return Res;
2574
2575   return SDValue();
2576 }
2577
2578 /// If this is a binary operator with two operands of the same opcode, try to
2579 /// simplify it.
2580 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2581   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2582   EVT VT = N0.getValueType();
2583   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2584
2585   // Bail early if none of these transforms apply.
2586   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2587
2588   // For each of OP in AND/OR/XOR:
2589   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2590   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2591   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2592   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2593   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2594   //
2595   // do not sink logical op inside of a vector extend, since it may combine
2596   // into a vsetcc.
2597   EVT Op0VT = N0.getOperand(0).getValueType();
2598   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2599        N0.getOpcode() == ISD::SIGN_EXTEND ||
2600        N0.getOpcode() == ISD::BSWAP ||
2601        // Avoid infinite looping with PromoteIntBinOp.
2602        (N0.getOpcode() == ISD::ANY_EXTEND &&
2603         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2604        (N0.getOpcode() == ISD::TRUNCATE &&
2605         (!TLI.isZExtFree(VT, Op0VT) ||
2606          !TLI.isTruncateFree(Op0VT, VT)) &&
2607         TLI.isTypeLegal(Op0VT))) &&
2608       !VT.isVector() &&
2609       Op0VT == N1.getOperand(0).getValueType() &&
2610       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2611     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2612                                  N0.getOperand(0).getValueType(),
2613                                  N0.getOperand(0), N1.getOperand(0));
2614     AddToWorklist(ORNode.getNode());
2615     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2616   }
2617
2618   // For each of OP in SHL/SRL/SRA/AND...
2619   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2620   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2621   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2622   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2623        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2624       N0.getOperand(1) == N1.getOperand(1)) {
2625     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2626                                  N0.getOperand(0).getValueType(),
2627                                  N0.getOperand(0), N1.getOperand(0));
2628     AddToWorklist(ORNode.getNode());
2629     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2630                        ORNode, N0.getOperand(1));
2631   }
2632
2633   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2634   // Only perform this optimization after type legalization and before
2635   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2636   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2637   // we don't want to undo this promotion.
2638   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2639   // on scalars.
2640   if ((N0.getOpcode() == ISD::BITCAST ||
2641        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2642       Level == AfterLegalizeTypes) {
2643     SDValue In0 = N0.getOperand(0);
2644     SDValue In1 = N1.getOperand(0);
2645     EVT In0Ty = In0.getValueType();
2646     EVT In1Ty = In1.getValueType();
2647     SDLoc DL(N);
2648     // If both incoming values are integers, and the original types are the
2649     // same.
2650     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2651       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2652       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2653       AddToWorklist(Op.getNode());
2654       return BC;
2655     }
2656   }
2657
2658   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2659   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2660   // If both shuffles use the same mask, and both shuffle within a single
2661   // vector, then it is worthwhile to move the swizzle after the operation.
2662   // The type-legalizer generates this pattern when loading illegal
2663   // vector types from memory. In many cases this allows additional shuffle
2664   // optimizations.
2665   // There are other cases where moving the shuffle after the xor/and/or
2666   // is profitable even if shuffles don't perform a swizzle.
2667   // If both shuffles use the same mask, and both shuffles have the same first
2668   // or second operand, then it might still be profitable to move the shuffle
2669   // after the xor/and/or operation.
2670   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2671     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2672     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2673
2674     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2675            "Inputs to shuffles are not the same type");
2676
2677     // Check that both shuffles use the same mask. The masks are known to be of
2678     // the same length because the result vector type is the same.
2679     // Check also that shuffles have only one use to avoid introducing extra
2680     // instructions.
2681     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2682         SVN0->getMask().equals(SVN1->getMask())) {
2683       SDValue ShOp = N0->getOperand(1);
2684
2685       // Don't try to fold this node if it requires introducing a
2686       // build vector of all zeros that might be illegal at this stage.
2687       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2688         if (!LegalTypes)
2689           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2690         else
2691           ShOp = SDValue();
2692       }
2693
2694       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2695       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2696       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2697       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2698         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2699                                       N0->getOperand(0), N1->getOperand(0));
2700         AddToWorklist(NewNode.getNode());
2701         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2702                                     &SVN0->getMask()[0]);
2703       }
2704
2705       // Don't try to fold this node if it requires introducing a
2706       // build vector of all zeros that might be illegal at this stage.
2707       ShOp = N0->getOperand(0);
2708       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2709         if (!LegalTypes)
2710           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2711         else
2712           ShOp = SDValue();
2713       }
2714
2715       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2716       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2717       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2718       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2719         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2720                                       N0->getOperand(1), N1->getOperand(1));
2721         AddToWorklist(NewNode.getNode());
2722         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2723                                     &SVN0->getMask()[0]);
2724       }
2725     }
2726   }
2727
2728   return SDValue();
2729 }
2730
2731 /// This contains all DAGCombine rules which reduce two values combined by
2732 /// an And operation to a single value. This makes them reusable in the context
2733 /// of visitSELECT(). Rules involving constants are not included as
2734 /// visitSELECT() already handles those cases.
2735 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2736                                   SDNode *LocReference) {
2737   EVT VT = N1.getValueType();
2738
2739   // fold (and x, undef) -> 0
2740   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2741     return DAG.getConstant(0, SDLoc(LocReference), VT);
2742   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2743   SDValue LL, LR, RL, RR, CC0, CC1;
2744   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2745     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2746     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2747
2748     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2749         LL.getValueType().isInteger()) {
2750       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2751       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2752         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2753                                      LR.getValueType(), LL, RL);
2754         AddToWorklist(ORNode.getNode());
2755         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2756       }
2757       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2758       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2759         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2760                                       LR.getValueType(), LL, RL);
2761         AddToWorklist(ANDNode.getNode());
2762         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2763       }
2764       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2765       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2766         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2767                                      LR.getValueType(), LL, RL);
2768         AddToWorklist(ORNode.getNode());
2769         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2770       }
2771     }
2772     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2773     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2774         Op0 == Op1 && LL.getValueType().isInteger() &&
2775       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2776                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2777                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2778                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2779       SDLoc DL(N0);
2780       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2781                                     LL, DAG.getConstant(1, DL,
2782                                                         LL.getValueType()));
2783       AddToWorklist(ADDNode.getNode());
2784       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2785                           DAG.getConstant(2, DL, LL.getValueType()),
2786                           ISD::SETUGE);
2787     }
2788     // canonicalize equivalent to ll == rl
2789     if (LL == RR && LR == RL) {
2790       Op1 = ISD::getSetCCSwappedOperands(Op1);
2791       std::swap(RL, RR);
2792     }
2793     if (LL == RL && LR == RR) {
2794       bool isInteger = LL.getValueType().isInteger();
2795       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2796       if (Result != ISD::SETCC_INVALID &&
2797           (!LegalOperations ||
2798            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2799             TLI.isOperationLegal(ISD::SETCC,
2800                             getSetCCResultType(N0.getSimpleValueType())))))
2801         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2802                             LL, LR, Result);
2803     }
2804   }
2805
2806   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2807       VT.getSizeInBits() <= 64) {
2808     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2809       APInt ADDC = ADDI->getAPIntValue();
2810       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2811         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2812         // immediate for an add, but it is legal if its top c2 bits are set,
2813         // transform the ADD so the immediate doesn't need to be materialized
2814         // in a register.
2815         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2816           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2817                                              SRLI->getZExtValue());
2818           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2819             ADDC |= Mask;
2820             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2821               SDLoc DL(N0);
2822               SDValue NewAdd =
2823                 DAG.getNode(ISD::ADD, DL, VT,
2824                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2825               CombineTo(N0.getNode(), NewAdd);
2826               // Return N so it doesn't get rechecked!
2827               return SDValue(LocReference, 0);
2828             }
2829           }
2830         }
2831       }
2832     }
2833   }
2834
2835   return SDValue();
2836 }
2837
2838 SDValue DAGCombiner::visitAND(SDNode *N) {
2839   SDValue N0 = N->getOperand(0);
2840   SDValue N1 = N->getOperand(1);
2841   EVT VT = N1.getValueType();
2842
2843   // fold vector ops
2844   if (VT.isVector()) {
2845     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2846       return FoldedVOp;
2847
2848     // fold (and x, 0) -> 0, vector edition
2849     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2850       // do not return N0, because undef node may exist in N0
2851       return DAG.getConstant(
2852           APInt::getNullValue(
2853               N0.getValueType().getScalarType().getSizeInBits()),
2854           SDLoc(N), N0.getValueType());
2855     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2856       // do not return N1, because undef node may exist in N1
2857       return DAG.getConstant(
2858           APInt::getNullValue(
2859               N1.getValueType().getScalarType().getSizeInBits()),
2860           SDLoc(N), N1.getValueType());
2861
2862     // fold (and x, -1) -> x, vector edition
2863     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2864       return N1;
2865     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2866       return N0;
2867   }
2868
2869   // fold (and c1, c2) -> c1&c2
2870   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2871   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2872   if (N0C && N1C)
2873     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2874   // canonicalize constant to RHS
2875   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2876      !isConstantIntBuildVectorOrConstantInt(N1))
2877     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2878   // fold (and x, -1) -> x
2879   if (N1C && N1C->isAllOnesValue())
2880     return N0;
2881   // if (and x, c) is known to be zero, return 0
2882   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2883   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2884                                    APInt::getAllOnesValue(BitWidth)))
2885     return DAG.getConstant(0, SDLoc(N), VT);
2886   // reassociate and
2887   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2888     return RAND;
2889   // fold (and (or x, C), D) -> D if (C & D) == D
2890   if (N1C && N0.getOpcode() == ISD::OR)
2891     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2892       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2893         return N1;
2894   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2895   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2896     SDValue N0Op0 = N0.getOperand(0);
2897     APInt Mask = ~N1C->getAPIntValue();
2898     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2899     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2900       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2901                                  N0.getValueType(), N0Op0);
2902
2903       // Replace uses of the AND with uses of the Zero extend node.
2904       CombineTo(N, Zext);
2905
2906       // We actually want to replace all uses of the any_extend with the
2907       // zero_extend, to avoid duplicating things.  This will later cause this
2908       // AND to be folded.
2909       CombineTo(N0.getNode(), Zext);
2910       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2911     }
2912   }
2913   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2914   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2915   // already be zero by virtue of the width of the base type of the load.
2916   //
2917   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2918   // more cases.
2919   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2920        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2921       N0.getOpcode() == ISD::LOAD) {
2922     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2923                                          N0 : N0.getOperand(0) );
2924
2925     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2926     // This can be a pure constant or a vector splat, in which case we treat the
2927     // vector as a scalar and use the splat value.
2928     APInt Constant = APInt::getNullValue(1);
2929     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2930       Constant = C->getAPIntValue();
2931     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2932       APInt SplatValue, SplatUndef;
2933       unsigned SplatBitSize;
2934       bool HasAnyUndefs;
2935       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2936                                              SplatBitSize, HasAnyUndefs);
2937       if (IsSplat) {
2938         // Undef bits can contribute to a possible optimisation if set, so
2939         // set them.
2940         SplatValue |= SplatUndef;
2941
2942         // The splat value may be something like "0x00FFFFFF", which means 0 for
2943         // the first vector value and FF for the rest, repeating. We need a mask
2944         // that will apply equally to all members of the vector, so AND all the
2945         // lanes of the constant together.
2946         EVT VT = Vector->getValueType(0);
2947         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2948
2949         // If the splat value has been compressed to a bitlength lower
2950         // than the size of the vector lane, we need to re-expand it to
2951         // the lane size.
2952         if (BitWidth > SplatBitSize)
2953           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2954                SplatBitSize < BitWidth;
2955                SplatBitSize = SplatBitSize * 2)
2956             SplatValue |= SplatValue.shl(SplatBitSize);
2957
2958         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2959         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2960         if (SplatBitSize % BitWidth == 0) {
2961           Constant = APInt::getAllOnesValue(BitWidth);
2962           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2963             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2964         }
2965       }
2966     }
2967
2968     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2969     // actually legal and isn't going to get expanded, else this is a false
2970     // optimisation.
2971     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2972                                                     Load->getValueType(0),
2973                                                     Load->getMemoryVT());
2974
2975     // Resize the constant to the same size as the original memory access before
2976     // extension. If it is still the AllOnesValue then this AND is completely
2977     // unneeded.
2978     Constant =
2979       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2980
2981     bool B;
2982     switch (Load->getExtensionType()) {
2983     default: B = false; break;
2984     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2985     case ISD::ZEXTLOAD:
2986     case ISD::NON_EXTLOAD: B = true; break;
2987     }
2988
2989     if (B && Constant.isAllOnesValue()) {
2990       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2991       // preserve semantics once we get rid of the AND.
2992       SDValue NewLoad(Load, 0);
2993       if (Load->getExtensionType() == ISD::EXTLOAD) {
2994         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2995                               Load->getValueType(0), SDLoc(Load),
2996                               Load->getChain(), Load->getBasePtr(),
2997                               Load->getOffset(), Load->getMemoryVT(),
2998                               Load->getMemOperand());
2999         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3000         if (Load->getNumValues() == 3) {
3001           // PRE/POST_INC loads have 3 values.
3002           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3003                            NewLoad.getValue(2) };
3004           CombineTo(Load, To, 3, true);
3005         } else {
3006           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3007         }
3008       }
3009
3010       // Fold the AND away, taking care not to fold to the old load node if we
3011       // replaced it.
3012       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3013
3014       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3015     }
3016   }
3017
3018   // fold (and (load x), 255) -> (zextload x, i8)
3019   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3020   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3021   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3022               (N0.getOpcode() == ISD::ANY_EXTEND &&
3023                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3024     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3025     LoadSDNode *LN0 = HasAnyExt
3026       ? cast<LoadSDNode>(N0.getOperand(0))
3027       : cast<LoadSDNode>(N0);
3028     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3029         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3030       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3031       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3032         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3033         EVT LoadedVT = LN0->getMemoryVT();
3034         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3035
3036         if (ExtVT == LoadedVT &&
3037             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3038                                                     ExtVT))) {
3039
3040           SDValue NewLoad =
3041             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3042                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3043                            LN0->getMemOperand());
3044           AddToWorklist(N);
3045           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3046           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3047         }
3048
3049         // Do not change the width of a volatile load.
3050         // Do not generate loads of non-round integer types since these can
3051         // be expensive (and would be wrong if the type is not byte sized).
3052         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3053             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3054                                                     ExtVT))) {
3055           EVT PtrType = LN0->getOperand(1).getValueType();
3056
3057           unsigned Alignment = LN0->getAlignment();
3058           SDValue NewPtr = LN0->getBasePtr();
3059
3060           // For big endian targets, we need to add an offset to the pointer
3061           // to load the correct bytes.  For little endian systems, we merely
3062           // need to read fewer bytes from the same pointer.
3063           if (TLI.isBigEndian()) {
3064             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3065             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3066             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3067             SDLoc DL(LN0);
3068             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3069                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3070             Alignment = MinAlign(Alignment, PtrOff);
3071           }
3072
3073           AddToWorklist(NewPtr.getNode());
3074
3075           SDValue Load =
3076             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3077                            LN0->getChain(), NewPtr,
3078                            LN0->getPointerInfo(),
3079                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3080                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3081           AddToWorklist(N);
3082           CombineTo(LN0, Load, Load.getValue(1));
3083           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3084         }
3085       }
3086     }
3087   }
3088
3089   if (SDValue Combined = visitANDLike(N0, N1, N))
3090     return Combined;
3091
3092   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3093   if (N0.getOpcode() == N1.getOpcode()) {
3094     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3095     if (Tmp.getNode()) return Tmp;
3096   }
3097
3098   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3099   // fold (and (sra)) -> (and (srl)) when possible.
3100   if (!VT.isVector() &&
3101       SimplifyDemandedBits(SDValue(N, 0)))
3102     return SDValue(N, 0);
3103
3104   // fold (zext_inreg (extload x)) -> (zextload x)
3105   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3106     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3107     EVT MemVT = LN0->getMemoryVT();
3108     // If we zero all the possible extended bits, then we can turn this into
3109     // a zextload if we are running before legalize or the operation is legal.
3110     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3111     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3112                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3113         ((!LegalOperations && !LN0->isVolatile()) ||
3114          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3115       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3116                                        LN0->getChain(), LN0->getBasePtr(),
3117                                        MemVT, LN0->getMemOperand());
3118       AddToWorklist(N);
3119       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3120       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3121     }
3122   }
3123   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3124   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3125       N0.hasOneUse()) {
3126     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3127     EVT MemVT = LN0->getMemoryVT();
3128     // If we zero all the possible extended bits, then we can turn this into
3129     // a zextload if we are running before legalize or the operation is legal.
3130     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3131     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3132                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3133         ((!LegalOperations && !LN0->isVolatile()) ||
3134          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3135       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3136                                        LN0->getChain(), LN0->getBasePtr(),
3137                                        MemVT, LN0->getMemOperand());
3138       AddToWorklist(N);
3139       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3140       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3141     }
3142   }
3143   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3144   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3145     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3146                                        N0.getOperand(1), false);
3147     if (BSwap.getNode())
3148       return BSwap;
3149   }
3150
3151   return SDValue();
3152 }
3153
3154 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3155 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3156                                         bool DemandHighBits) {
3157   if (!LegalOperations)
3158     return SDValue();
3159
3160   EVT VT = N->getValueType(0);
3161   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3162     return SDValue();
3163   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3164     return SDValue();
3165
3166   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3167   bool LookPassAnd0 = false;
3168   bool LookPassAnd1 = false;
3169   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3170       std::swap(N0, N1);
3171   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3172       std::swap(N0, N1);
3173   if (N0.getOpcode() == ISD::AND) {
3174     if (!N0.getNode()->hasOneUse())
3175       return SDValue();
3176     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3177     if (!N01C || N01C->getZExtValue() != 0xFF00)
3178       return SDValue();
3179     N0 = N0.getOperand(0);
3180     LookPassAnd0 = true;
3181   }
3182
3183   if (N1.getOpcode() == ISD::AND) {
3184     if (!N1.getNode()->hasOneUse())
3185       return SDValue();
3186     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3187     if (!N11C || N11C->getZExtValue() != 0xFF)
3188       return SDValue();
3189     N1 = N1.getOperand(0);
3190     LookPassAnd1 = true;
3191   }
3192
3193   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3194     std::swap(N0, N1);
3195   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3196     return SDValue();
3197   if (!N0.getNode()->hasOneUse() ||
3198       !N1.getNode()->hasOneUse())
3199     return SDValue();
3200
3201   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3202   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3203   if (!N01C || !N11C)
3204     return SDValue();
3205   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3206     return SDValue();
3207
3208   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3209   SDValue N00 = N0->getOperand(0);
3210   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3211     if (!N00.getNode()->hasOneUse())
3212       return SDValue();
3213     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3214     if (!N001C || N001C->getZExtValue() != 0xFF)
3215       return SDValue();
3216     N00 = N00.getOperand(0);
3217     LookPassAnd0 = true;
3218   }
3219
3220   SDValue N10 = N1->getOperand(0);
3221   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3222     if (!N10.getNode()->hasOneUse())
3223       return SDValue();
3224     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3225     if (!N101C || N101C->getZExtValue() != 0xFF00)
3226       return SDValue();
3227     N10 = N10.getOperand(0);
3228     LookPassAnd1 = true;
3229   }
3230
3231   if (N00 != N10)
3232     return SDValue();
3233
3234   // Make sure everything beyond the low halfword gets set to zero since the SRL
3235   // 16 will clear the top bits.
3236   unsigned OpSizeInBits = VT.getSizeInBits();
3237   if (DemandHighBits && OpSizeInBits > 16) {
3238     // If the left-shift isn't masked out then the only way this is a bswap is
3239     // if all bits beyond the low 8 are 0. In that case the entire pattern
3240     // reduces to a left shift anyway: leave it for other parts of the combiner.
3241     if (!LookPassAnd0)
3242       return SDValue();
3243
3244     // However, if the right shift isn't masked out then it might be because
3245     // it's not needed. See if we can spot that too.
3246     if (!LookPassAnd1 &&
3247         !DAG.MaskedValueIsZero(
3248             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3249       return SDValue();
3250   }
3251
3252   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3253   if (OpSizeInBits > 16) {
3254     SDLoc DL(N);
3255     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3256                       DAG.getConstant(OpSizeInBits - 16, DL,
3257                                       getShiftAmountTy(VT)));
3258   }
3259   return Res;
3260 }
3261
3262 /// Return true if the specified node is an element that makes up a 32-bit
3263 /// packed halfword byteswap.
3264 /// ((x & 0x000000ff) << 8) |
3265 /// ((x & 0x0000ff00) >> 8) |
3266 /// ((x & 0x00ff0000) << 8) |
3267 /// ((x & 0xff000000) >> 8)
3268 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3269   if (!N.getNode()->hasOneUse())
3270     return false;
3271
3272   unsigned Opc = N.getOpcode();
3273   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3274     return false;
3275
3276   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3277   if (!N1C)
3278     return false;
3279
3280   unsigned Num;
3281   switch (N1C->getZExtValue()) {
3282   default:
3283     return false;
3284   case 0xFF:       Num = 0; break;
3285   case 0xFF00:     Num = 1; break;
3286   case 0xFF0000:   Num = 2; break;
3287   case 0xFF000000: Num = 3; break;
3288   }
3289
3290   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3291   SDValue N0 = N.getOperand(0);
3292   if (Opc == ISD::AND) {
3293     if (Num == 0 || Num == 2) {
3294       // (x >> 8) & 0xff
3295       // (x >> 8) & 0xff0000
3296       if (N0.getOpcode() != ISD::SRL)
3297         return false;
3298       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3299       if (!C || C->getZExtValue() != 8)
3300         return false;
3301     } else {
3302       // (x << 8) & 0xff00
3303       // (x << 8) & 0xff000000
3304       if (N0.getOpcode() != ISD::SHL)
3305         return false;
3306       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3307       if (!C || C->getZExtValue() != 8)
3308         return false;
3309     }
3310   } else if (Opc == ISD::SHL) {
3311     // (x & 0xff) << 8
3312     // (x & 0xff0000) << 8
3313     if (Num != 0 && Num != 2)
3314       return false;
3315     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3316     if (!C || C->getZExtValue() != 8)
3317       return false;
3318   } else { // Opc == ISD::SRL
3319     // (x & 0xff00) >> 8
3320     // (x & 0xff000000) >> 8
3321     if (Num != 1 && Num != 3)
3322       return false;
3323     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3324     if (!C || C->getZExtValue() != 8)
3325       return false;
3326   }
3327
3328   if (Parts[Num])
3329     return false;
3330
3331   Parts[Num] = N0.getOperand(0).getNode();
3332   return true;
3333 }
3334
3335 /// Match a 32-bit packed halfword bswap. That is
3336 /// ((x & 0x000000ff) << 8) |
3337 /// ((x & 0x0000ff00) >> 8) |
3338 /// ((x & 0x00ff0000) << 8) |
3339 /// ((x & 0xff000000) >> 8)
3340 /// => (rotl (bswap x), 16)
3341 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3342   if (!LegalOperations)
3343     return SDValue();
3344
3345   EVT VT = N->getValueType(0);
3346   if (VT != MVT::i32)
3347     return SDValue();
3348   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3349     return SDValue();
3350
3351   // Look for either
3352   // (or (or (and), (and)), (or (and), (and)))
3353   // (or (or (or (and), (and)), (and)), (and))
3354   if (N0.getOpcode() != ISD::OR)
3355     return SDValue();
3356   SDValue N00 = N0.getOperand(0);
3357   SDValue N01 = N0.getOperand(1);
3358   SDNode *Parts[4] = {};
3359
3360   if (N1.getOpcode() == ISD::OR &&
3361       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3362     // (or (or (and), (and)), (or (and), (and)))
3363     SDValue N000 = N00.getOperand(0);
3364     if (!isBSwapHWordElement(N000, Parts))
3365       return SDValue();
3366
3367     SDValue N001 = N00.getOperand(1);
3368     if (!isBSwapHWordElement(N001, Parts))
3369       return SDValue();
3370     SDValue N010 = N01.getOperand(0);
3371     if (!isBSwapHWordElement(N010, Parts))
3372       return SDValue();
3373     SDValue N011 = N01.getOperand(1);
3374     if (!isBSwapHWordElement(N011, Parts))
3375       return SDValue();
3376   } else {
3377     // (or (or (or (and), (and)), (and)), (and))
3378     if (!isBSwapHWordElement(N1, Parts))
3379       return SDValue();
3380     if (!isBSwapHWordElement(N01, Parts))
3381       return SDValue();
3382     if (N00.getOpcode() != ISD::OR)
3383       return SDValue();
3384     SDValue N000 = N00.getOperand(0);
3385     if (!isBSwapHWordElement(N000, Parts))
3386       return SDValue();
3387     SDValue N001 = N00.getOperand(1);
3388     if (!isBSwapHWordElement(N001, Parts))
3389       return SDValue();
3390   }
3391
3392   // Make sure the parts are all coming from the same node.
3393   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3394     return SDValue();
3395
3396   SDLoc DL(N);
3397   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3398                               SDValue(Parts[0], 0));
3399
3400   // Result of the bswap should be rotated by 16. If it's not legal, then
3401   // do  (x << 16) | (x >> 16).
3402   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3403   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3404     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3405   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3406     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3407   return DAG.getNode(ISD::OR, DL, VT,
3408                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3409                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3410 }
3411
3412 /// This contains all DAGCombine rules which reduce two values combined by
3413 /// an Or operation to a single value \see visitANDLike().
3414 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3415   EVT VT = N1.getValueType();
3416   // fold (or x, undef) -> -1
3417   if (!LegalOperations &&
3418       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3419     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3420     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3421                            SDLoc(LocReference), VT);
3422   }
3423   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3424   SDValue LL, LR, RL, RR, CC0, CC1;
3425   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3426     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3427     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3428
3429     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3430         LL.getValueType().isInteger()) {
3431       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3432       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3433       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3434           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3435         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3436                                      LR.getValueType(), LL, RL);
3437         AddToWorklist(ORNode.getNode());
3438         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3439       }
3440       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3441       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3442       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3443           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3444         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3445                                       LR.getValueType(), LL, RL);
3446         AddToWorklist(ANDNode.getNode());
3447         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3448       }
3449     }
3450     // canonicalize equivalent to ll == rl
3451     if (LL == RR && LR == RL) {
3452       Op1 = ISD::getSetCCSwappedOperands(Op1);
3453       std::swap(RL, RR);
3454     }
3455     if (LL == RL && LR == RR) {
3456       bool isInteger = LL.getValueType().isInteger();
3457       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3458       if (Result != ISD::SETCC_INVALID &&
3459           (!LegalOperations ||
3460            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3461             TLI.isOperationLegal(ISD::SETCC,
3462               getSetCCResultType(N0.getValueType())))))
3463         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3464                             LL, LR, Result);
3465     }
3466   }
3467
3468   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3469   if (N0.getOpcode() == ISD::AND &&
3470       N1.getOpcode() == ISD::AND &&
3471       N0.getOperand(1).getOpcode() == ISD::Constant &&
3472       N1.getOperand(1).getOpcode() == ISD::Constant &&
3473       // Don't increase # computations.
3474       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3475     // We can only do this xform if we know that bits from X that are set in C2
3476     // but not in C1 are already zero.  Likewise for Y.
3477     const APInt &LHSMask =
3478       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3479     const APInt &RHSMask =
3480       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3481
3482     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3483         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3484       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3485                               N0.getOperand(0), N1.getOperand(0));
3486       SDLoc DL(LocReference);
3487       return DAG.getNode(ISD::AND, DL, VT, X,
3488                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3489     }
3490   }
3491
3492   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3493   if (N0.getOpcode() == ISD::AND &&
3494       N1.getOpcode() == ISD::AND &&
3495       N0.getOperand(0) == N1.getOperand(0) &&
3496       // Don't increase # computations.
3497       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3498     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3499                             N0.getOperand(1), N1.getOperand(1));
3500     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3501   }
3502
3503   return SDValue();
3504 }
3505
3506 SDValue DAGCombiner::visitOR(SDNode *N) {
3507   SDValue N0 = N->getOperand(0);
3508   SDValue N1 = N->getOperand(1);
3509   EVT VT = N1.getValueType();
3510
3511   // fold vector ops
3512   if (VT.isVector()) {
3513     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3514       return FoldedVOp;
3515
3516     // fold (or x, 0) -> x, vector edition
3517     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3518       return N1;
3519     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3520       return N0;
3521
3522     // fold (or x, -1) -> -1, vector edition
3523     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3524       // do not return N0, because undef node may exist in N0
3525       return DAG.getConstant(
3526           APInt::getAllOnesValue(
3527               N0.getValueType().getScalarType().getSizeInBits()),
3528           SDLoc(N), N0.getValueType());
3529     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3530       // do not return N1, because undef node may exist in N1
3531       return DAG.getConstant(
3532           APInt::getAllOnesValue(
3533               N1.getValueType().getScalarType().getSizeInBits()),
3534           SDLoc(N), N1.getValueType());
3535
3536     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3537     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3538     // Do this only if the resulting shuffle is legal.
3539     if (isa<ShuffleVectorSDNode>(N0) &&
3540         isa<ShuffleVectorSDNode>(N1) &&
3541         // Avoid folding a node with illegal type.
3542         TLI.isTypeLegal(VT) &&
3543         N0->getOperand(1) == N1->getOperand(1) &&
3544         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3545       bool CanFold = true;
3546       unsigned NumElts = VT.getVectorNumElements();
3547       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3548       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3549       // We construct two shuffle masks:
3550       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3551       // and N1 as the second operand.
3552       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3553       // and N0 as the second operand.
3554       // We do this because OR is commutable and therefore there might be
3555       // two ways to fold this node into a shuffle.
3556       SmallVector<int,4> Mask1;
3557       SmallVector<int,4> Mask2;
3558
3559       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3560         int M0 = SV0->getMaskElt(i);
3561         int M1 = SV1->getMaskElt(i);
3562
3563         // Both shuffle indexes are undef. Propagate Undef.
3564         if (M0 < 0 && M1 < 0) {
3565           Mask1.push_back(M0);
3566           Mask2.push_back(M0);
3567           continue;
3568         }
3569
3570         if (M0 < 0 || M1 < 0 ||
3571             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3572             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3573           CanFold = false;
3574           break;
3575         }
3576
3577         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3578         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3579       }
3580
3581       if (CanFold) {
3582         // Fold this sequence only if the resulting shuffle is 'legal'.
3583         if (TLI.isShuffleMaskLegal(Mask1, VT))
3584           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3585                                       N1->getOperand(0), &Mask1[0]);
3586         if (TLI.isShuffleMaskLegal(Mask2, VT))
3587           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3588                                       N0->getOperand(0), &Mask2[0]);
3589       }
3590     }
3591   }
3592
3593   // fold (or c1, c2) -> c1|c2
3594   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3595   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3596   if (N0C && N1C)
3597     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3598   // canonicalize constant to RHS
3599   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3600      !isConstantIntBuildVectorOrConstantInt(N1))
3601     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3602   // fold (or x, 0) -> x
3603   if (N1C && N1C->isNullValue())
3604     return N0;
3605   // fold (or x, -1) -> -1
3606   if (N1C && N1C->isAllOnesValue())
3607     return N1;
3608   // fold (or x, c) -> c iff (x & ~c) == 0
3609   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3610     return N1;
3611
3612   if (SDValue Combined = visitORLike(N0, N1, N))
3613     return Combined;
3614
3615   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3616   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3617   if (BSwap.getNode())
3618     return BSwap;
3619   BSwap = MatchBSwapHWordLow(N, N0, N1);
3620   if (BSwap.getNode())
3621     return BSwap;
3622
3623   // reassociate or
3624   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3625     return ROR;
3626   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3627   // iff (c1 & c2) == 0.
3628   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3629              isa<ConstantSDNode>(N0.getOperand(1))) {
3630     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3631     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3632       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3633                                                    N1C, C1))
3634         return DAG.getNode(
3635             ISD::AND, SDLoc(N), VT,
3636             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3637       return SDValue();
3638     }
3639   }
3640   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3641   if (N0.getOpcode() == N1.getOpcode()) {
3642     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3643     if (Tmp.getNode()) return Tmp;
3644   }
3645
3646   // See if this is some rotate idiom.
3647   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3648     return SDValue(Rot, 0);
3649
3650   // Simplify the operands using demanded-bits information.
3651   if (!VT.isVector() &&
3652       SimplifyDemandedBits(SDValue(N, 0)))
3653     return SDValue(N, 0);
3654
3655   return SDValue();
3656 }
3657
3658 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3659 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3660   if (Op.getOpcode() == ISD::AND) {
3661     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3662       Mask = Op.getOperand(1);
3663       Op = Op.getOperand(0);
3664     } else {
3665       return false;
3666     }
3667   }
3668
3669   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3670     Shift = Op;
3671     return true;
3672   }
3673
3674   return false;
3675 }
3676
3677 // Return true if we can prove that, whenever Neg and Pos are both in the
3678 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3679 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3680 //
3681 //     (or (shift1 X, Neg), (shift2 X, Pos))
3682 //
3683 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3684 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3685 // to consider shift amounts with defined behavior.
3686 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3687   // If OpSize is a power of 2 then:
3688   //
3689   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3690   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3691   //
3692   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3693   // for the stronger condition:
3694   //
3695   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3696   //
3697   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3698   // we can just replace Neg with Neg' for the rest of the function.
3699   //
3700   // In other cases we check for the even stronger condition:
3701   //
3702   //     Neg == OpSize - Pos                                    [B]
3703   //
3704   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3705   // behavior if Pos == 0 (and consequently Neg == OpSize).
3706   //
3707   // We could actually use [A] whenever OpSize is a power of 2, but the
3708   // only extra cases that it would match are those uninteresting ones
3709   // where Neg and Pos are never in range at the same time.  E.g. for
3710   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3711   // as well as (sub 32, Pos), but:
3712   //
3713   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3714   //
3715   // always invokes undefined behavior for 32-bit X.
3716   //
3717   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3718   unsigned MaskLoBits = 0;
3719   if (Neg.getOpcode() == ISD::AND &&
3720       isPowerOf2_64(OpSize) &&
3721       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3722       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3723     Neg = Neg.getOperand(0);
3724     MaskLoBits = Log2_64(OpSize);
3725   }
3726
3727   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3728   if (Neg.getOpcode() != ISD::SUB)
3729     return 0;
3730   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3731   if (!NegC)
3732     return 0;
3733   SDValue NegOp1 = Neg.getOperand(1);
3734
3735   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3736   // Pos'.  The truncation is redundant for the purpose of the equality.
3737   if (MaskLoBits &&
3738       Pos.getOpcode() == ISD::AND &&
3739       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3740       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3741     Pos = Pos.getOperand(0);
3742
3743   // The condition we need is now:
3744   //
3745   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3746   //
3747   // If NegOp1 == Pos then we need:
3748   //
3749   //              OpSize & Mask == NegC & Mask
3750   //
3751   // (because "x & Mask" is a truncation and distributes through subtraction).
3752   APInt Width;
3753   if (Pos == NegOp1)
3754     Width = NegC->getAPIntValue();
3755   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3756   // Then the condition we want to prove becomes:
3757   //
3758   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3759   //
3760   // which, again because "x & Mask" is a truncation, becomes:
3761   //
3762   //                NegC & Mask == (OpSize - PosC) & Mask
3763   //              OpSize & Mask == (NegC + PosC) & Mask
3764   else if (Pos.getOpcode() == ISD::ADD &&
3765            Pos.getOperand(0) == NegOp1 &&
3766            Pos.getOperand(1).getOpcode() == ISD::Constant)
3767     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3768              NegC->getAPIntValue());
3769   else
3770     return false;
3771
3772   // Now we just need to check that OpSize & Mask == Width & Mask.
3773   if (MaskLoBits)
3774     // Opsize & Mask is 0 since Mask is Opsize - 1.
3775     return Width.getLoBits(MaskLoBits) == 0;
3776   return Width == OpSize;
3777 }
3778
3779 // A subroutine of MatchRotate used once we have found an OR of two opposite
3780 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3781 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3782 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3783 // Neg with outer conversions stripped away.
3784 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3785                                        SDValue Neg, SDValue InnerPos,
3786                                        SDValue InnerNeg, unsigned PosOpcode,
3787                                        unsigned NegOpcode, SDLoc DL) {
3788   // fold (or (shl x, (*ext y)),
3789   //          (srl x, (*ext (sub 32, y)))) ->
3790   //   (rotl x, y) or (rotr x, (sub 32, y))
3791   //
3792   // fold (or (shl x, (*ext (sub 32, y))),
3793   //          (srl x, (*ext y))) ->
3794   //   (rotr x, y) or (rotl x, (sub 32, y))
3795   EVT VT = Shifted.getValueType();
3796   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3797     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3798     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3799                        HasPos ? Pos : Neg).getNode();
3800   }
3801
3802   return nullptr;
3803 }
3804
3805 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3806 // idioms for rotate, and if the target supports rotation instructions, generate
3807 // a rot[lr].
3808 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3809   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3810   EVT VT = LHS.getValueType();
3811   if (!TLI.isTypeLegal(VT)) return nullptr;
3812
3813   // The target must have at least one rotate flavor.
3814   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3815   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3816   if (!HasROTL && !HasROTR) return nullptr;
3817
3818   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3819   SDValue LHSShift;   // The shift.
3820   SDValue LHSMask;    // AND value if any.
3821   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3822     return nullptr; // Not part of a rotate.
3823
3824   SDValue RHSShift;   // The shift.
3825   SDValue RHSMask;    // AND value if any.
3826   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3827     return nullptr; // Not part of a rotate.
3828
3829   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3830     return nullptr;   // Not shifting the same value.
3831
3832   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3833     return nullptr;   // Shifts must disagree.
3834
3835   // Canonicalize shl to left side in a shl/srl pair.
3836   if (RHSShift.getOpcode() == ISD::SHL) {
3837     std::swap(LHS, RHS);
3838     std::swap(LHSShift, RHSShift);
3839     std::swap(LHSMask , RHSMask );
3840   }
3841
3842   unsigned OpSizeInBits = VT.getSizeInBits();
3843   SDValue LHSShiftArg = LHSShift.getOperand(0);
3844   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3845   SDValue RHSShiftArg = RHSShift.getOperand(0);
3846   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3847
3848   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3849   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3850   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3851       RHSShiftAmt.getOpcode() == ISD::Constant) {
3852     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3853     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3854     if ((LShVal + RShVal) != OpSizeInBits)
3855       return nullptr;
3856
3857     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3858                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3859
3860     // If there is an AND of either shifted operand, apply it to the result.
3861     if (LHSMask.getNode() || RHSMask.getNode()) {
3862       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3863
3864       if (LHSMask.getNode()) {
3865         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3866         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3867       }
3868       if (RHSMask.getNode()) {
3869         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3870         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3871       }
3872
3873       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3874     }
3875
3876     return Rot.getNode();
3877   }
3878
3879   // If there is a mask here, and we have a variable shift, we can't be sure
3880   // that we're masking out the right stuff.
3881   if (LHSMask.getNode() || RHSMask.getNode())
3882     return nullptr;
3883
3884   // If the shift amount is sign/zext/any-extended just peel it off.
3885   SDValue LExtOp0 = LHSShiftAmt;
3886   SDValue RExtOp0 = RHSShiftAmt;
3887   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3888        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3889        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3890        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3891       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3892        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3893        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3894        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3895     LExtOp0 = LHSShiftAmt.getOperand(0);
3896     RExtOp0 = RHSShiftAmt.getOperand(0);
3897   }
3898
3899   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3900                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3901   if (TryL)
3902     return TryL;
3903
3904   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3905                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3906   if (TryR)
3907     return TryR;
3908
3909   return nullptr;
3910 }
3911
3912 SDValue DAGCombiner::visitXOR(SDNode *N) {
3913   SDValue N0 = N->getOperand(0);
3914   SDValue N1 = N->getOperand(1);
3915   EVT VT = N0.getValueType();
3916
3917   // fold vector ops
3918   if (VT.isVector()) {
3919     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3920       return FoldedVOp;
3921
3922     // fold (xor x, 0) -> x, vector edition
3923     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3924       return N1;
3925     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3926       return N0;
3927   }
3928
3929   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3930   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3931     return DAG.getConstant(0, SDLoc(N), VT);
3932   // fold (xor x, undef) -> undef
3933   if (N0.getOpcode() == ISD::UNDEF)
3934     return N0;
3935   if (N1.getOpcode() == ISD::UNDEF)
3936     return N1;
3937   // fold (xor c1, c2) -> c1^c2
3938   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3939   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3940   if (N0C && N1C)
3941     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3942   // canonicalize constant to RHS
3943   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3944      !isConstantIntBuildVectorOrConstantInt(N1))
3945     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3946   // fold (xor x, 0) -> x
3947   if (N1C && N1C->isNullValue())
3948     return N0;
3949   // reassociate xor
3950   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3951     return RXOR;
3952
3953   // fold !(x cc y) -> (x !cc y)
3954   SDValue LHS, RHS, CC;
3955   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3956     bool isInt = LHS.getValueType().isInteger();
3957     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3958                                                isInt);
3959
3960     if (!LegalOperations ||
3961         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3962       switch (N0.getOpcode()) {
3963       default:
3964         llvm_unreachable("Unhandled SetCC Equivalent!");
3965       case ISD::SETCC:
3966         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3967       case ISD::SELECT_CC:
3968         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3969                                N0.getOperand(3), NotCC);
3970       }
3971     }
3972   }
3973
3974   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3975   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3976       N0.getNode()->hasOneUse() &&
3977       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3978     SDValue V = N0.getOperand(0);
3979     SDLoc DL(N0);
3980     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3981                     DAG.getConstant(1, DL, V.getValueType()));
3982     AddToWorklist(V.getNode());
3983     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3984   }
3985
3986   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3987   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3988       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3989     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3990     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3991       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3992       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3993       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3994       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3995       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3996     }
3997   }
3998   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3999   if (N1C && N1C->isAllOnesValue() &&
4000       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4001     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4002     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4003       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4004       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4005       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4006       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4007       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4008     }
4009   }
4010   // fold (xor (and x, y), y) -> (and (not x), y)
4011   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4012       N0->getOperand(1) == N1) {
4013     SDValue X = N0->getOperand(0);
4014     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4015     AddToWorklist(NotX.getNode());
4016     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4017   }
4018   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4019   if (N1C && N0.getOpcode() == ISD::XOR) {
4020     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4021     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4022     if (N00C) {
4023       SDLoc DL(N);
4024       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4025                          DAG.getConstant(N1C->getAPIntValue() ^
4026                                          N00C->getAPIntValue(), DL, VT));
4027     }
4028     if (N01C) {
4029       SDLoc DL(N);
4030       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4031                          DAG.getConstant(N1C->getAPIntValue() ^
4032                                          N01C->getAPIntValue(), DL, VT));
4033     }
4034   }
4035   // fold (xor x, x) -> 0
4036   if (N0 == N1)
4037     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4038
4039   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4040   // Here is a concrete example of this equivalence:
4041   // i16   x ==  14
4042   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4043   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4044   //
4045   // =>
4046   //
4047   // i16     ~1      == 0b1111111111111110
4048   // i16 rol(~1, 14) == 0b1011111111111111
4049   //
4050   // Some additional tips to help conceptualize this transform:
4051   // - Try to see the operation as placing a single zero in a value of all ones.
4052   // - There exists no value for x which would allow the result to contain zero.
4053   // - Values of x larger than the bitwidth are undefined and do not require a
4054   //   consistent result.
4055   // - Pushing the zero left requires shifting one bits in from the right.
4056   // A rotate left of ~1 is a nice way of achieving the desired result.
4057   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4058     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4059       if (N0.getOpcode() == ISD::SHL)
4060         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4061           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4062             SDLoc DL(N);
4063             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4064                                N0.getOperand(1));
4065           }
4066
4067   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4068   if (N0.getOpcode() == N1.getOpcode()) {
4069     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4070     if (Tmp.getNode()) return Tmp;
4071   }
4072
4073   // Simplify the expression using non-local knowledge.
4074   if (!VT.isVector() &&
4075       SimplifyDemandedBits(SDValue(N, 0)))
4076     return SDValue(N, 0);
4077
4078   return SDValue();
4079 }
4080
4081 /// Handle transforms common to the three shifts, when the shift amount is a
4082 /// constant.
4083 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4084   // We can't and shouldn't fold opaque constants.
4085   if (Amt->isOpaque())
4086     return SDValue();
4087
4088   SDNode *LHS = N->getOperand(0).getNode();
4089   if (!LHS->hasOneUse()) return SDValue();
4090
4091   // We want to pull some binops through shifts, so that we have (and (shift))
4092   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4093   // thing happens with address calculations, so it's important to canonicalize
4094   // it.
4095   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4096
4097   switch (LHS->getOpcode()) {
4098   default: return SDValue();
4099   case ISD::OR:
4100   case ISD::XOR:
4101     HighBitSet = false; // We can only transform sra if the high bit is clear.
4102     break;
4103   case ISD::AND:
4104     HighBitSet = true;  // We can only transform sra if the high bit is set.
4105     break;
4106   case ISD::ADD:
4107     if (N->getOpcode() != ISD::SHL)
4108       return SDValue(); // only shl(add) not sr[al](add).
4109     HighBitSet = false; // We can only transform sra if the high bit is clear.
4110     break;
4111   }
4112
4113   // We require the RHS of the binop to be a constant and not opaque as well.
4114   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4115   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4116
4117   // FIXME: disable this unless the input to the binop is a shift by a constant.
4118   // If it is not a shift, it pessimizes some common cases like:
4119   //
4120   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4121   //    int bar(int *X, int i) { return X[i & 255]; }
4122   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4123   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4124        BinOpLHSVal->getOpcode() != ISD::SRA &&
4125        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4126       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4127     return SDValue();
4128
4129   EVT VT = N->getValueType(0);
4130
4131   // If this is a signed shift right, and the high bit is modified by the
4132   // logical operation, do not perform the transformation. The highBitSet
4133   // boolean indicates the value of the high bit of the constant which would
4134   // cause it to be modified for this operation.
4135   if (N->getOpcode() == ISD::SRA) {
4136     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4137     if (BinOpRHSSignSet != HighBitSet)
4138       return SDValue();
4139   }
4140
4141   if (!TLI.isDesirableToCommuteWithShift(LHS))
4142     return SDValue();
4143
4144   // Fold the constants, shifting the binop RHS by the shift amount.
4145   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4146                                N->getValueType(0),
4147                                LHS->getOperand(1), N->getOperand(1));
4148   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4149
4150   // Create the new shift.
4151   SDValue NewShift = DAG.getNode(N->getOpcode(),
4152                                  SDLoc(LHS->getOperand(0)),
4153                                  VT, LHS->getOperand(0), N->getOperand(1));
4154
4155   // Create the new binop.
4156   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4157 }
4158
4159 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4160   assert(N->getOpcode() == ISD::TRUNCATE);
4161   assert(N->getOperand(0).getOpcode() == ISD::AND);
4162
4163   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4164   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4165     SDValue N01 = N->getOperand(0).getOperand(1);
4166
4167     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4168       EVT TruncVT = N->getValueType(0);
4169       SDValue N00 = N->getOperand(0).getOperand(0);
4170       APInt TruncC = N01C->getAPIntValue();
4171       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4172       SDLoc DL(N);
4173
4174       return DAG.getNode(ISD::AND, DL, TruncVT,
4175                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4176                          DAG.getConstant(TruncC, DL, TruncVT));
4177     }
4178   }
4179
4180   return SDValue();
4181 }
4182
4183 SDValue DAGCombiner::visitRotate(SDNode *N) {
4184   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4185   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4186       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4187     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4188     if (NewOp1.getNode())
4189       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4190                          N->getOperand(0), NewOp1);
4191   }
4192   return SDValue();
4193 }
4194
4195 SDValue DAGCombiner::visitSHL(SDNode *N) {
4196   SDValue N0 = N->getOperand(0);
4197   SDValue N1 = N->getOperand(1);
4198   EVT VT = N0.getValueType();
4199   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4200
4201   // fold vector ops
4202   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4203   if (VT.isVector()) {
4204     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4205       return FoldedVOp;
4206
4207     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4208     // If setcc produces all-one true value then:
4209     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4210     if (N1CV && N1CV->isConstant()) {
4211       if (N0.getOpcode() == ISD::AND) {
4212         SDValue N00 = N0->getOperand(0);
4213         SDValue N01 = N0->getOperand(1);
4214         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4215
4216         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4217             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4218                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4219           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4220                                                      N01CV, N1CV))
4221             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4222         }
4223       } else {
4224         N1C = isConstOrConstSplat(N1);
4225       }
4226     }
4227   }
4228
4229   // fold (shl c1, c2) -> c1<<c2
4230   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4231   if (N0C && N1C)
4232     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4233   // fold (shl 0, x) -> 0
4234   if (N0C && N0C->isNullValue())
4235     return N0;
4236   // fold (shl x, c >= size(x)) -> undef
4237   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4238     return DAG.getUNDEF(VT);
4239   // fold (shl x, 0) -> x
4240   if (N1C && N1C->isNullValue())
4241     return N0;
4242   // fold (shl undef, x) -> 0
4243   if (N0.getOpcode() == ISD::UNDEF)
4244     return DAG.getConstant(0, SDLoc(N), VT);
4245   // if (shl x, c) is known to be zero, return 0
4246   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4247                             APInt::getAllOnesValue(OpSizeInBits)))
4248     return DAG.getConstant(0, SDLoc(N), VT);
4249   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4250   if (N1.getOpcode() == ISD::TRUNCATE &&
4251       N1.getOperand(0).getOpcode() == ISD::AND) {
4252     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4253     if (NewOp1.getNode())
4254       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4255   }
4256
4257   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4258     return SDValue(N, 0);
4259
4260   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4261   if (N1C && N0.getOpcode() == ISD::SHL) {
4262     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4263       uint64_t c1 = N0C1->getZExtValue();
4264       uint64_t c2 = N1C->getZExtValue();
4265       SDLoc DL(N);
4266       if (c1 + c2 >= OpSizeInBits)
4267         return DAG.getConstant(0, DL, VT);
4268       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4269                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4270     }
4271   }
4272
4273   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4274   // For this to be valid, the second form must not preserve any of the bits
4275   // that are shifted out by the inner shift in the first form.  This means
4276   // the outer shift size must be >= the number of bits added by the ext.
4277   // As a corollary, we don't care what kind of ext it is.
4278   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4279               N0.getOpcode() == ISD::ANY_EXTEND ||
4280               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4281       N0.getOperand(0).getOpcode() == ISD::SHL) {
4282     SDValue N0Op0 = N0.getOperand(0);
4283     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4284       uint64_t c1 = N0Op0C1->getZExtValue();
4285       uint64_t c2 = N1C->getZExtValue();
4286       EVT InnerShiftVT = N0Op0.getValueType();
4287       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4288       if (c2 >= OpSizeInBits - InnerShiftSize) {
4289         SDLoc DL(N0);
4290         if (c1 + c2 >= OpSizeInBits)
4291           return DAG.getConstant(0, DL, VT);
4292         return DAG.getNode(ISD::SHL, DL, VT,
4293                            DAG.getNode(N0.getOpcode(), DL, VT,
4294                                        N0Op0->getOperand(0)),
4295                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4296       }
4297     }
4298   }
4299
4300   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4301   // Only fold this if the inner zext has no other uses to avoid increasing
4302   // the total number of instructions.
4303   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4304       N0.getOperand(0).getOpcode() == ISD::SRL) {
4305     SDValue N0Op0 = N0.getOperand(0);
4306     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4307       uint64_t c1 = N0Op0C1->getZExtValue();
4308       if (c1 < VT.getScalarSizeInBits()) {
4309         uint64_t c2 = N1C->getZExtValue();
4310         if (c1 == c2) {
4311           SDValue NewOp0 = N0.getOperand(0);
4312           EVT CountVT = NewOp0.getOperand(1).getValueType();
4313           SDLoc DL(N);
4314           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4315                                        NewOp0,
4316                                        DAG.getConstant(c2, DL, CountVT));
4317           AddToWorklist(NewSHL.getNode());
4318           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4319         }
4320       }
4321     }
4322   }
4323
4324   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4325   //                               (and (srl x, (sub c1, c2), MASK)
4326   // Only fold this if the inner shift has no other uses -- if it does, folding
4327   // this will increase the total number of instructions.
4328   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4329     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4330       uint64_t c1 = N0C1->getZExtValue();
4331       if (c1 < OpSizeInBits) {
4332         uint64_t c2 = N1C->getZExtValue();
4333         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4334         SDValue Shift;
4335         if (c2 > c1) {
4336           Mask = Mask.shl(c2 - c1);
4337           SDLoc DL(N);
4338           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4339                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4340         } else {
4341           Mask = Mask.lshr(c1 - c2);
4342           SDLoc DL(N);
4343           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4344                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4345         }
4346         SDLoc DL(N0);
4347         return DAG.getNode(ISD::AND, DL, VT, Shift,
4348                            DAG.getConstant(Mask, DL, VT));
4349       }
4350     }
4351   }
4352   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4353   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4354     unsigned BitSize = VT.getScalarSizeInBits();
4355     SDLoc DL(N);
4356     SDValue HiBitsMask =
4357       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4358                                             BitSize - N1C->getZExtValue()),
4359                       DL, VT);
4360     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4361                        HiBitsMask);
4362   }
4363
4364   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4365   // Variant of version done on multiply, except mul by a power of 2 is turned
4366   // into a shift.
4367   APInt Val;
4368   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4369       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4370        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4371     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4372     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4373     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4374   }
4375
4376   if (N1C) {
4377     SDValue NewSHL = visitShiftByConstant(N, N1C);
4378     if (NewSHL.getNode())
4379       return NewSHL;
4380   }
4381
4382   return SDValue();
4383 }
4384
4385 SDValue DAGCombiner::visitSRA(SDNode *N) {
4386   SDValue N0 = N->getOperand(0);
4387   SDValue N1 = N->getOperand(1);
4388   EVT VT = N0.getValueType();
4389   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4390
4391   // fold vector ops
4392   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4393   if (VT.isVector()) {
4394     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4395       return FoldedVOp;
4396
4397     N1C = isConstOrConstSplat(N1);
4398   }
4399
4400   // fold (sra c1, c2) -> (sra c1, c2)
4401   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4402   if (N0C && N1C)
4403     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4404   // fold (sra 0, x) -> 0
4405   if (N0C && N0C->isNullValue())
4406     return N0;
4407   // fold (sra -1, x) -> -1
4408   if (N0C && N0C->isAllOnesValue())
4409     return N0;
4410   // fold (sra x, (setge c, size(x))) -> undef
4411   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4412     return DAG.getUNDEF(VT);
4413   // fold (sra x, 0) -> x
4414   if (N1C && N1C->isNullValue())
4415     return N0;
4416   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4417   // sext_inreg.
4418   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4419     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4420     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4421     if (VT.isVector())
4422       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4423                                ExtVT, VT.getVectorNumElements());
4424     if ((!LegalOperations ||
4425          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4426       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4427                          N0.getOperand(0), DAG.getValueType(ExtVT));
4428   }
4429
4430   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4431   if (N1C && N0.getOpcode() == ISD::SRA) {
4432     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4433       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4434       if (Sum >= OpSizeInBits)
4435         Sum = OpSizeInBits - 1;
4436       SDLoc DL(N);
4437       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4438                          DAG.getConstant(Sum, DL, N1.getValueType()));
4439     }
4440   }
4441
4442   // fold (sra (shl X, m), (sub result_size, n))
4443   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4444   // result_size - n != m.
4445   // If truncate is free for the target sext(shl) is likely to result in better
4446   // code.
4447   if (N0.getOpcode() == ISD::SHL && N1C) {
4448     // Get the two constanst of the shifts, CN0 = m, CN = n.
4449     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4450     if (N01C) {
4451       LLVMContext &Ctx = *DAG.getContext();
4452       // Determine what the truncate's result bitsize and type would be.
4453       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4454
4455       if (VT.isVector())
4456         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4457
4458       // Determine the residual right-shift amount.
4459       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4460
4461       // If the shift is not a no-op (in which case this should be just a sign
4462       // extend already), the truncated to type is legal, sign_extend is legal
4463       // on that type, and the truncate to that type is both legal and free,
4464       // perform the transform.
4465       if ((ShiftAmt > 0) &&
4466           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4467           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4468           TLI.isTruncateFree(VT, TruncVT)) {
4469
4470         SDLoc DL(N);
4471         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4472             getShiftAmountTy(N0.getOperand(0).getValueType()));
4473         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4474                                     N0.getOperand(0), Amt);
4475         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4476                                     Shift);
4477         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4478                            N->getValueType(0), Trunc);
4479       }
4480     }
4481   }
4482
4483   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4484   if (N1.getOpcode() == ISD::TRUNCATE &&
4485       N1.getOperand(0).getOpcode() == ISD::AND) {
4486     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4487     if (NewOp1.getNode())
4488       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4489   }
4490
4491   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4492   //      if c1 is equal to the number of bits the trunc removes
4493   if (N0.getOpcode() == ISD::TRUNCATE &&
4494       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4495        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4496       N0.getOperand(0).hasOneUse() &&
4497       N0.getOperand(0).getOperand(1).hasOneUse() &&
4498       N1C) {
4499     SDValue N0Op0 = N0.getOperand(0);
4500     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4501       unsigned LargeShiftVal = LargeShift->getZExtValue();
4502       EVT LargeVT = N0Op0.getValueType();
4503
4504       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4505         SDLoc DL(N);
4506         SDValue Amt =
4507           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4508                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4509         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4510                                   N0Op0.getOperand(0), Amt);
4511         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4512       }
4513     }
4514   }
4515
4516   // Simplify, based on bits shifted out of the LHS.
4517   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4518     return SDValue(N, 0);
4519
4520
4521   // If the sign bit is known to be zero, switch this to a SRL.
4522   if (DAG.SignBitIsZero(N0))
4523     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4524
4525   if (N1C) {
4526     SDValue NewSRA = visitShiftByConstant(N, N1C);
4527     if (NewSRA.getNode())
4528       return NewSRA;
4529   }
4530
4531   return SDValue();
4532 }
4533
4534 SDValue DAGCombiner::visitSRL(SDNode *N) {
4535   SDValue N0 = N->getOperand(0);
4536   SDValue N1 = N->getOperand(1);
4537   EVT VT = N0.getValueType();
4538   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4539
4540   // fold vector ops
4541   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4542   if (VT.isVector()) {
4543     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4544       return FoldedVOp;
4545
4546     N1C = isConstOrConstSplat(N1);
4547   }
4548
4549   // fold (srl c1, c2) -> c1 >>u c2
4550   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4551   if (N0C && N1C)
4552     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4553   // fold (srl 0, x) -> 0
4554   if (N0C && N0C->isNullValue())
4555     return N0;
4556   // fold (srl x, c >= size(x)) -> undef
4557   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4558     return DAG.getUNDEF(VT);
4559   // fold (srl x, 0) -> x
4560   if (N1C && N1C->isNullValue())
4561     return N0;
4562   // if (srl x, c) is known to be zero, return 0
4563   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4564                                    APInt::getAllOnesValue(OpSizeInBits)))
4565     return DAG.getConstant(0, SDLoc(N), VT);
4566
4567   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4568   if (N1C && N0.getOpcode() == ISD::SRL) {
4569     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4570       uint64_t c1 = N01C->getZExtValue();
4571       uint64_t c2 = N1C->getZExtValue();
4572       SDLoc DL(N);
4573       if (c1 + c2 >= OpSizeInBits)
4574         return DAG.getConstant(0, DL, VT);
4575       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4576                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4577     }
4578   }
4579
4580   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4581   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4582       N0.getOperand(0).getOpcode() == ISD::SRL &&
4583       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4584     uint64_t c1 =
4585       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4586     uint64_t c2 = N1C->getZExtValue();
4587     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4588     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4589     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4590     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4591     if (c1 + OpSizeInBits == InnerShiftSize) {
4592       SDLoc DL(N0);
4593       if (c1 + c2 >= InnerShiftSize)
4594         return DAG.getConstant(0, DL, VT);
4595       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4596                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4597                                      N0.getOperand(0)->getOperand(0),
4598                                      DAG.getConstant(c1 + c2, DL,
4599                                                      ShiftCountVT)));
4600     }
4601   }
4602
4603   // fold (srl (shl x, c), c) -> (and x, cst2)
4604   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4605     unsigned BitSize = N0.getScalarValueSizeInBits();
4606     if (BitSize <= 64) {
4607       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4608       SDLoc DL(N);
4609       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4610                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4611     }
4612   }
4613
4614   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4615   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4616     // Shifting in all undef bits?
4617     EVT SmallVT = N0.getOperand(0).getValueType();
4618     unsigned BitSize = SmallVT.getScalarSizeInBits();
4619     if (N1C->getZExtValue() >= BitSize)
4620       return DAG.getUNDEF(VT);
4621
4622     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4623       uint64_t ShiftAmt = N1C->getZExtValue();
4624       SDLoc DL0(N0);
4625       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4626                                        N0.getOperand(0),
4627                           DAG.getConstant(ShiftAmt, DL0,
4628                                           getShiftAmountTy(SmallVT)));
4629       AddToWorklist(SmallShift.getNode());
4630       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4631       SDLoc DL(N);
4632       return DAG.getNode(ISD::AND, DL, VT,
4633                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4634                          DAG.getConstant(Mask, DL, VT));
4635     }
4636   }
4637
4638   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4639   // bit, which is unmodified by sra.
4640   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4641     if (N0.getOpcode() == ISD::SRA)
4642       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4643   }
4644
4645   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4646   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4647       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4648     APInt KnownZero, KnownOne;
4649     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4650
4651     // If any of the input bits are KnownOne, then the input couldn't be all
4652     // zeros, thus the result of the srl will always be zero.
4653     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4654
4655     // If all of the bits input the to ctlz node are known to be zero, then
4656     // the result of the ctlz is "32" and the result of the shift is one.
4657     APInt UnknownBits = ~KnownZero;
4658     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4659
4660     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4661     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4662       // Okay, we know that only that the single bit specified by UnknownBits
4663       // could be set on input to the CTLZ node. If this bit is set, the SRL
4664       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4665       // to an SRL/XOR pair, which is likely to simplify more.
4666       unsigned ShAmt = UnknownBits.countTrailingZeros();
4667       SDValue Op = N0.getOperand(0);
4668
4669       if (ShAmt) {
4670         SDLoc DL(N0);
4671         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4672                   DAG.getConstant(ShAmt, DL,
4673                                   getShiftAmountTy(Op.getValueType())));
4674         AddToWorklist(Op.getNode());
4675       }
4676
4677       SDLoc DL(N);
4678       return DAG.getNode(ISD::XOR, DL, VT,
4679                          Op, DAG.getConstant(1, DL, VT));
4680     }
4681   }
4682
4683   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4684   if (N1.getOpcode() == ISD::TRUNCATE &&
4685       N1.getOperand(0).getOpcode() == ISD::AND) {
4686     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4687     if (NewOp1.getNode())
4688       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4689   }
4690
4691   // fold operands of srl based on knowledge that the low bits are not
4692   // demanded.
4693   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4694     return SDValue(N, 0);
4695
4696   if (N1C) {
4697     SDValue NewSRL = visitShiftByConstant(N, N1C);
4698     if (NewSRL.getNode())
4699       return NewSRL;
4700   }
4701
4702   // Attempt to convert a srl of a load into a narrower zero-extending load.
4703   SDValue NarrowLoad = ReduceLoadWidth(N);
4704   if (NarrowLoad.getNode())
4705     return NarrowLoad;
4706
4707   // Here is a common situation. We want to optimize:
4708   //
4709   //   %a = ...
4710   //   %b = and i32 %a, 2
4711   //   %c = srl i32 %b, 1
4712   //   brcond i32 %c ...
4713   //
4714   // into
4715   //
4716   //   %a = ...
4717   //   %b = and %a, 2
4718   //   %c = setcc eq %b, 0
4719   //   brcond %c ...
4720   //
4721   // However when after the source operand of SRL is optimized into AND, the SRL
4722   // itself may not be optimized further. Look for it and add the BRCOND into
4723   // the worklist.
4724   if (N->hasOneUse()) {
4725     SDNode *Use = *N->use_begin();
4726     if (Use->getOpcode() == ISD::BRCOND)
4727       AddToWorklist(Use);
4728     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4729       // Also look pass the truncate.
4730       Use = *Use->use_begin();
4731       if (Use->getOpcode() == ISD::BRCOND)
4732         AddToWorklist(Use);
4733     }
4734   }
4735
4736   return SDValue();
4737 }
4738
4739 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4740   SDValue N0 = N->getOperand(0);
4741   EVT VT = N->getValueType(0);
4742
4743   // fold (ctlz c1) -> c2
4744   if (isa<ConstantSDNode>(N0))
4745     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4746   return SDValue();
4747 }
4748
4749 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4750   SDValue N0 = N->getOperand(0);
4751   EVT VT = N->getValueType(0);
4752
4753   // fold (ctlz_zero_undef c1) -> c2
4754   if (isa<ConstantSDNode>(N0))
4755     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4756   return SDValue();
4757 }
4758
4759 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4760   SDValue N0 = N->getOperand(0);
4761   EVT VT = N->getValueType(0);
4762
4763   // fold (cttz c1) -> c2
4764   if (isa<ConstantSDNode>(N0))
4765     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4766   return SDValue();
4767 }
4768
4769 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4770   SDValue N0 = N->getOperand(0);
4771   EVT VT = N->getValueType(0);
4772
4773   // fold (cttz_zero_undef c1) -> c2
4774   if (isa<ConstantSDNode>(N0))
4775     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4776   return SDValue();
4777 }
4778
4779 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4780   SDValue N0 = N->getOperand(0);
4781   EVT VT = N->getValueType(0);
4782
4783   // fold (ctpop c1) -> c2
4784   if (isa<ConstantSDNode>(N0))
4785     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4786   return SDValue();
4787 }
4788
4789
4790 /// \brief Generate Min/Max node
4791 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4792                                    SDValue True, SDValue False,
4793                                    ISD::CondCode CC, const TargetLowering &TLI,
4794                                    SelectionDAG &DAG) {
4795   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4796     return SDValue();
4797
4798   switch (CC) {
4799   case ISD::SETOLT:
4800   case ISD::SETOLE:
4801   case ISD::SETLT:
4802   case ISD::SETLE:
4803   case ISD::SETULT:
4804   case ISD::SETULE: {
4805     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4806     if (TLI.isOperationLegal(Opcode, VT))
4807       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4808     return SDValue();
4809   }
4810   case ISD::SETOGT:
4811   case ISD::SETOGE:
4812   case ISD::SETGT:
4813   case ISD::SETGE:
4814   case ISD::SETUGT:
4815   case ISD::SETUGE: {
4816     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4817     if (TLI.isOperationLegal(Opcode, VT))
4818       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4819     return SDValue();
4820   }
4821   default:
4822     return SDValue();
4823   }
4824 }
4825
4826 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4827   SDValue N0 = N->getOperand(0);
4828   SDValue N1 = N->getOperand(1);
4829   SDValue N2 = N->getOperand(2);
4830   EVT VT = N->getValueType(0);
4831   EVT VT0 = N0.getValueType();
4832
4833   // fold (select C, X, X) -> X
4834   if (N1 == N2)
4835     return N1;
4836   // fold (select true, X, Y) -> X
4837   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4838   if (N0C && !N0C->isNullValue())
4839     return N1;
4840   // fold (select false, X, Y) -> Y
4841   if (N0C && N0C->isNullValue())
4842     return N2;
4843   // fold (select C, 1, X) -> (or C, X)
4844   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4845   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4846     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4847   // fold (select C, 0, 1) -> (xor C, 1)
4848   // We can't do this reliably if integer based booleans have different contents
4849   // to floating point based booleans. This is because we can't tell whether we
4850   // have an integer-based boolean or a floating-point-based boolean unless we
4851   // can find the SETCC that produced it and inspect its operands. This is
4852   // fairly easy if C is the SETCC node, but it can potentially be
4853   // undiscoverable (or not reasonably discoverable). For example, it could be
4854   // in another basic block or it could require searching a complicated
4855   // expression.
4856   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4857   if (VT.isInteger() &&
4858       (VT0 == MVT::i1 || (VT0.isInteger() &&
4859                           TLI.getBooleanContents(false, false) ==
4860                               TLI.getBooleanContents(false, true) &&
4861                           TLI.getBooleanContents(false, false) ==
4862                               TargetLowering::ZeroOrOneBooleanContent)) &&
4863       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4864     SDValue XORNode;
4865     if (VT == VT0) {
4866       SDLoc DL(N);
4867       return DAG.getNode(ISD::XOR, DL, VT0,
4868                          N0, DAG.getConstant(1, DL, VT0));
4869     }
4870     SDLoc DL0(N0);
4871     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4872                           N0, DAG.getConstant(1, DL0, VT0));
4873     AddToWorklist(XORNode.getNode());
4874     if (VT.bitsGT(VT0))
4875       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4876     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4877   }
4878   // fold (select C, 0, X) -> (and (not C), X)
4879   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4880     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4881     AddToWorklist(NOTNode.getNode());
4882     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4883   }
4884   // fold (select C, X, 1) -> (or (not C), X)
4885   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4886     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4887     AddToWorklist(NOTNode.getNode());
4888     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4889   }
4890   // fold (select C, X, 0) -> (and C, X)
4891   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4892     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4893   // fold (select X, X, Y) -> (or X, Y)
4894   // fold (select X, 1, Y) -> (or X, Y)
4895   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4896     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4897   // fold (select X, Y, X) -> (and X, Y)
4898   // fold (select X, Y, 0) -> (and X, Y)
4899   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4900     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4901
4902   // If we can fold this based on the true/false value, do so.
4903   if (SimplifySelectOps(N, N1, N2))
4904     return SDValue(N, 0);  // Don't revisit N.
4905
4906   // fold selects based on a setcc into other things, such as min/max/abs
4907   if (N0.getOpcode() == ISD::SETCC) {
4908     // select x, y (fcmp lt x, y) -> fminnum x, y
4909     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4910     //
4911     // This is OK if we don't care about what happens if either operand is a
4912     // NaN.
4913     //
4914
4915     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4916     // no signed zeros as well as no nans.
4917     const TargetOptions &Options = DAG.getTarget().Options;
4918     if (Options.UnsafeFPMath &&
4919         VT.isFloatingPoint() && N0.hasOneUse() &&
4920         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4921       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4922
4923       SDValue FMinMax =
4924           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4925                               N1, N2, CC, TLI, DAG);
4926       if (FMinMax)
4927         return FMinMax;
4928     }
4929
4930     if ((!LegalOperations &&
4931          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4932         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4933       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4934                          N0.getOperand(0), N0.getOperand(1),
4935                          N1, N2, N0.getOperand(2));
4936     return SimplifySelect(SDLoc(N), N0, N1, N2);
4937   }
4938
4939   if (VT0 == MVT::i1) {
4940     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4941       // select (and Cond0, Cond1), X, Y
4942       //   -> select Cond0, (select Cond1, X, Y), Y
4943       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4944         SDValue Cond0 = N0->getOperand(0);
4945         SDValue Cond1 = N0->getOperand(1);
4946         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4947                                           N1.getValueType(), Cond1, N1, N2);
4948         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4949                            InnerSelect, N2);
4950       }
4951       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4952       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4953         SDValue Cond0 = N0->getOperand(0);
4954         SDValue Cond1 = N0->getOperand(1);
4955         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4956                                           N1.getValueType(), Cond1, N1, N2);
4957         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4958                            InnerSelect);
4959       }
4960     }
4961
4962     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4963     if (N1->getOpcode() == ISD::SELECT) {
4964       SDValue N1_0 = N1->getOperand(0);
4965       SDValue N1_1 = N1->getOperand(1);
4966       SDValue N1_2 = N1->getOperand(2);
4967       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4968         // Create the actual and node if we can generate good code for it.
4969         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4970           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4971                                     N0, N1_0);
4972           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4973                              N1_1, N2);
4974         }
4975         // Otherwise see if we can optimize the "and" to a better pattern.
4976         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4977           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4978                              N1_1, N2);
4979       }
4980     }
4981     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4982     if (N2->getOpcode() == ISD::SELECT) {
4983       SDValue N2_0 = N2->getOperand(0);
4984       SDValue N2_1 = N2->getOperand(1);
4985       SDValue N2_2 = N2->getOperand(2);
4986       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4987         // Create the actual or node if we can generate good code for it.
4988         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4989           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4990                                    N0, N2_0);
4991           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4992                              N1, N2_2);
4993         }
4994         // Otherwise see if we can optimize to a better pattern.
4995         if (SDValue Combined = visitORLike(N0, N2_0, N))
4996           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4997                              N1, N2_2);
4998       }
4999     }
5000   }
5001
5002   return SDValue();
5003 }
5004
5005 static
5006 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5007   SDLoc DL(N);
5008   EVT LoVT, HiVT;
5009   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5010
5011   // Split the inputs.
5012   SDValue Lo, Hi, LL, LH, RL, RH;
5013   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5014   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5015
5016   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5017   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5018
5019   return std::make_pair(Lo, Hi);
5020 }
5021
5022 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5023 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5024 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5025   SDLoc dl(N);
5026   SDValue Cond = N->getOperand(0);
5027   SDValue LHS = N->getOperand(1);
5028   SDValue RHS = N->getOperand(2);
5029   EVT VT = N->getValueType(0);
5030   int NumElems = VT.getVectorNumElements();
5031   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5032          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5033          Cond.getOpcode() == ISD::BUILD_VECTOR);
5034
5035   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5036   // binary ones here.
5037   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5038     return SDValue();
5039
5040   // We're sure we have an even number of elements due to the
5041   // concat_vectors we have as arguments to vselect.
5042   // Skip BV elements until we find one that's not an UNDEF
5043   // After we find an UNDEF element, keep looping until we get to half the
5044   // length of the BV and see if all the non-undef nodes are the same.
5045   ConstantSDNode *BottomHalf = nullptr;
5046   for (int i = 0; i < NumElems / 2; ++i) {
5047     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5048       continue;
5049
5050     if (BottomHalf == nullptr)
5051       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5052     else if (Cond->getOperand(i).getNode() != BottomHalf)
5053       return SDValue();
5054   }
5055
5056   // Do the same for the second half of the BuildVector
5057   ConstantSDNode *TopHalf = nullptr;
5058   for (int i = NumElems / 2; i < NumElems; ++i) {
5059     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5060       continue;
5061
5062     if (TopHalf == nullptr)
5063       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5064     else if (Cond->getOperand(i).getNode() != TopHalf)
5065       return SDValue();
5066   }
5067
5068   assert(TopHalf && BottomHalf &&
5069          "One half of the selector was all UNDEFs and the other was all the "
5070          "same value. This should have been addressed before this function.");
5071   return DAG.getNode(
5072       ISD::CONCAT_VECTORS, dl, VT,
5073       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5074       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5075 }
5076
5077 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5078
5079   if (Level >= AfterLegalizeTypes)
5080     return SDValue();
5081
5082   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5083   SDValue Mask = MSC->getMask();
5084   SDValue Data  = MSC->getValue();
5085   SDLoc DL(N);
5086
5087   // If the MSCATTER data type requires splitting and the mask is provided by a
5088   // SETCC, then split both nodes and its operands before legalization. This
5089   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5090   // and enables future optimizations (e.g. min/max pattern matching on X86).
5091   if (Mask.getOpcode() != ISD::SETCC)
5092     return SDValue();
5093
5094   // Check if any splitting is required.
5095   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5096       TargetLowering::TypeSplitVector)
5097     return SDValue();
5098   SDValue MaskLo, MaskHi, Lo, Hi;
5099   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5100
5101   EVT LoVT, HiVT;
5102   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5103
5104   SDValue Chain = MSC->getChain();
5105
5106   EVT MemoryVT = MSC->getMemoryVT();
5107   unsigned Alignment = MSC->getOriginalAlignment();
5108
5109   EVT LoMemVT, HiMemVT;
5110   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5111
5112   SDValue DataLo, DataHi;
5113   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5114
5115   SDValue BasePtr = MSC->getBasePtr();
5116   SDValue IndexLo, IndexHi;
5117   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5118
5119   MachineMemOperand *MMO = DAG.getMachineFunction().
5120     getMachineMemOperand(MSC->getPointerInfo(), 
5121                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5122                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5123
5124   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5125   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5126                             DL, OpsLo, MMO);
5127
5128   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5129   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5130                             DL, OpsHi, MMO);
5131
5132   AddToWorklist(Lo.getNode());
5133   AddToWorklist(Hi.getNode());
5134
5135   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5136 }
5137
5138 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5139
5140   if (Level >= AfterLegalizeTypes)
5141     return SDValue();
5142
5143   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5144   SDValue Mask = MST->getMask();
5145   SDValue Data  = MST->getValue();
5146   SDLoc DL(N);
5147
5148   // If the MSTORE data type requires splitting and the mask is provided by a
5149   // SETCC, then split both nodes and its operands before legalization. This
5150   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5151   // and enables future optimizations (e.g. min/max pattern matching on X86).
5152   if (Mask.getOpcode() == ISD::SETCC) {
5153
5154     // Check if any splitting is required.
5155     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5156         TargetLowering::TypeSplitVector)
5157       return SDValue();
5158
5159     SDValue MaskLo, MaskHi, Lo, Hi;
5160     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5161
5162     EVT LoVT, HiVT;
5163     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5164
5165     SDValue Chain = MST->getChain();
5166     SDValue Ptr   = MST->getBasePtr();
5167
5168     EVT MemoryVT = MST->getMemoryVT();
5169     unsigned Alignment = MST->getOriginalAlignment();
5170
5171     // if Alignment is equal to the vector size,
5172     // take the half of it for the second part
5173     unsigned SecondHalfAlignment =
5174       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5175          Alignment/2 : Alignment;
5176
5177     EVT LoMemVT, HiMemVT;
5178     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5179
5180     SDValue DataLo, DataHi;
5181     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5182
5183     MachineMemOperand *MMO = DAG.getMachineFunction().
5184       getMachineMemOperand(MST->getPointerInfo(),
5185                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5186                            Alignment, MST->getAAInfo(), MST->getRanges());
5187
5188     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5189                             MST->isTruncatingStore());
5190
5191     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5192     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5193                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5194
5195     MMO = DAG.getMachineFunction().
5196       getMachineMemOperand(MST->getPointerInfo(),
5197                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5198                            SecondHalfAlignment, MST->getAAInfo(),
5199                            MST->getRanges());
5200
5201     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5202                             MST->isTruncatingStore());
5203
5204     AddToWorklist(Lo.getNode());
5205     AddToWorklist(Hi.getNode());
5206
5207     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5208   }
5209   return SDValue();
5210 }
5211
5212 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5213
5214   if (Level >= AfterLegalizeTypes)
5215     return SDValue();
5216
5217   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5218   SDValue Mask = MGT->getMask();
5219   SDLoc DL(N);
5220
5221   // If the MGATHER result requires splitting and the mask is provided by a
5222   // SETCC, then split both nodes and its operands before legalization. This
5223   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5224   // and enables future optimizations (e.g. min/max pattern matching on X86).
5225
5226   if (Mask.getOpcode() != ISD::SETCC)
5227     return SDValue();
5228
5229   EVT VT = N->getValueType(0);
5230
5231   // Check if any splitting is required.
5232   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5233       TargetLowering::TypeSplitVector)
5234     return SDValue();
5235
5236   SDValue MaskLo, MaskHi, Lo, Hi;
5237   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5238
5239   SDValue Src0 = MGT->getValue();
5240   SDValue Src0Lo, Src0Hi;
5241   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5242
5243   EVT LoVT, HiVT;
5244   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5245
5246   SDValue Chain = MGT->getChain();
5247   EVT MemoryVT = MGT->getMemoryVT();
5248   unsigned Alignment = MGT->getOriginalAlignment();
5249
5250   EVT LoMemVT, HiMemVT;
5251   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5252
5253   SDValue BasePtr = MGT->getBasePtr();
5254   SDValue Index = MGT->getIndex();
5255   SDValue IndexLo, IndexHi;
5256   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5257
5258   MachineMemOperand *MMO = DAG.getMachineFunction().
5259     getMachineMemOperand(MGT->getPointerInfo(), 
5260                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5261                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5262
5263   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5264   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5265                             MMO);
5266
5267   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5268   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5269                             MMO);
5270
5271   AddToWorklist(Lo.getNode());
5272   AddToWorklist(Hi.getNode());
5273
5274   // Build a factor node to remember that this load is independent of the
5275   // other one.
5276   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5277                       Hi.getValue(1));
5278
5279   // Legalized the chain result - switch anything that used the old chain to
5280   // use the new one.
5281   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5282
5283   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5284
5285   SDValue RetOps[] = { GatherRes, Chain };
5286   return DAG.getMergeValues(RetOps, DL);
5287 }
5288
5289 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5290
5291   if (Level >= AfterLegalizeTypes)
5292     return SDValue();
5293
5294   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5295   SDValue Mask = MLD->getMask();
5296   SDLoc DL(N);
5297
5298   // If the MLOAD result requires splitting and the mask is provided by a
5299   // SETCC, then split both nodes and its operands before legalization. This
5300   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5301   // and enables future optimizations (e.g. min/max pattern matching on X86).
5302
5303   if (Mask.getOpcode() == ISD::SETCC) {
5304     EVT VT = N->getValueType(0);
5305
5306     // Check if any splitting is required.
5307     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5308         TargetLowering::TypeSplitVector)
5309       return SDValue();
5310
5311     SDValue MaskLo, MaskHi, Lo, Hi;
5312     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5313
5314     SDValue Src0 = MLD->getSrc0();
5315     SDValue Src0Lo, Src0Hi;
5316     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5317
5318     EVT LoVT, HiVT;
5319     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5320
5321     SDValue Chain = MLD->getChain();
5322     SDValue Ptr   = MLD->getBasePtr();
5323     EVT MemoryVT = MLD->getMemoryVT();
5324     unsigned Alignment = MLD->getOriginalAlignment();
5325
5326     // if Alignment is equal to the vector size,
5327     // take the half of it for the second part
5328     unsigned SecondHalfAlignment =
5329       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5330          Alignment/2 : Alignment;
5331
5332     EVT LoMemVT, HiMemVT;
5333     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5334
5335     MachineMemOperand *MMO = DAG.getMachineFunction().
5336     getMachineMemOperand(MLD->getPointerInfo(),
5337                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5338                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5339
5340     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5341                            ISD::NON_EXTLOAD);
5342
5343     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5344     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5345                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5346
5347     MMO = DAG.getMachineFunction().
5348     getMachineMemOperand(MLD->getPointerInfo(),
5349                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5350                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5351
5352     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5353                            ISD::NON_EXTLOAD);
5354
5355     AddToWorklist(Lo.getNode());
5356     AddToWorklist(Hi.getNode());
5357
5358     // Build a factor node to remember that this load is independent of the
5359     // other one.
5360     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5361                         Hi.getValue(1));
5362
5363     // Legalized the chain result - switch anything that used the old chain to
5364     // use the new one.
5365     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5366
5367     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5368
5369     SDValue RetOps[] = { LoadRes, Chain };
5370     return DAG.getMergeValues(RetOps, DL);
5371   }
5372   return SDValue();
5373 }
5374
5375 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5376   SDValue N0 = N->getOperand(0);
5377   SDValue N1 = N->getOperand(1);
5378   SDValue N2 = N->getOperand(2);
5379   SDLoc DL(N);
5380
5381   // Canonicalize integer abs.
5382   // vselect (setg[te] X,  0),  X, -X ->
5383   // vselect (setgt    X, -1),  X, -X ->
5384   // vselect (setl[te] X,  0), -X,  X ->
5385   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5386   if (N0.getOpcode() == ISD::SETCC) {
5387     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5388     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5389     bool isAbs = false;
5390     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5391
5392     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5393          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5394         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5395       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5396     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5397              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5398       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5399
5400     if (isAbs) {
5401       EVT VT = LHS.getValueType();
5402       SDValue Shift = DAG.getNode(
5403           ISD::SRA, DL, VT, LHS,
5404           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5405       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5406       AddToWorklist(Shift.getNode());
5407       AddToWorklist(Add.getNode());
5408       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5409     }
5410   }
5411
5412   if (SimplifySelectOps(N, N1, N2))
5413     return SDValue(N, 0);  // Don't revisit N.
5414
5415   // If the VSELECT result requires splitting and the mask is provided by a
5416   // SETCC, then split both nodes and its operands before legalization. This
5417   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5418   // and enables future optimizations (e.g. min/max pattern matching on X86).
5419   if (N0.getOpcode() == ISD::SETCC) {
5420     EVT VT = N->getValueType(0);
5421
5422     // Check if any splitting is required.
5423     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5424         TargetLowering::TypeSplitVector)
5425       return SDValue();
5426
5427     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5428     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5429     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5430     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5431
5432     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5433     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5434
5435     // Add the new VSELECT nodes to the work list in case they need to be split
5436     // again.
5437     AddToWorklist(Lo.getNode());
5438     AddToWorklist(Hi.getNode());
5439
5440     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5441   }
5442
5443   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5444   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5445     return N1;
5446   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5447   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5448     return N2;
5449
5450   // The ConvertSelectToConcatVector function is assuming both the above
5451   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5452   // and addressed.
5453   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5454       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5455       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5456     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5457     if (CV.getNode())
5458       return CV;
5459   }
5460
5461   return SDValue();
5462 }
5463
5464 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5465   SDValue N0 = N->getOperand(0);
5466   SDValue N1 = N->getOperand(1);
5467   SDValue N2 = N->getOperand(2);
5468   SDValue N3 = N->getOperand(3);
5469   SDValue N4 = N->getOperand(4);
5470   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5471
5472   // fold select_cc lhs, rhs, x, x, cc -> x
5473   if (N2 == N3)
5474     return N2;
5475
5476   // Determine if the condition we're dealing with is constant
5477   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5478                               N0, N1, CC, SDLoc(N), false);
5479   if (SCC.getNode()) {
5480     AddToWorklist(SCC.getNode());
5481
5482     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5483       if (!SCCC->isNullValue())
5484         return N2;    // cond always true -> true val
5485       else
5486         return N3;    // cond always false -> false val
5487     } else if (SCC->getOpcode() == ISD::UNDEF) {
5488       // When the condition is UNDEF, just return the first operand. This is
5489       // coherent the DAG creation, no setcc node is created in this case
5490       return N2;
5491     } else if (SCC.getOpcode() == ISD::SETCC) {
5492       // Fold to a simpler select_cc
5493       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5494                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5495                          SCC.getOperand(2));
5496     }
5497   }
5498
5499   // If we can fold this based on the true/false value, do so.
5500   if (SimplifySelectOps(N, N2, N3))
5501     return SDValue(N, 0);  // Don't revisit N.
5502
5503   // fold select_cc into other things, such as min/max/abs
5504   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5505 }
5506
5507 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5508   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5509                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5510                        SDLoc(N));
5511 }
5512
5513 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5514 // dag node into a ConstantSDNode or a build_vector of constants.
5515 // This function is called by the DAGCombiner when visiting sext/zext/aext
5516 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5517 // Vector extends are not folded if operations are legal; this is to
5518 // avoid introducing illegal build_vector dag nodes.
5519 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5520                                          SelectionDAG &DAG, bool LegalTypes,
5521                                          bool LegalOperations) {
5522   unsigned Opcode = N->getOpcode();
5523   SDValue N0 = N->getOperand(0);
5524   EVT VT = N->getValueType(0);
5525
5526   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5527          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5528
5529   // fold (sext c1) -> c1
5530   // fold (zext c1) -> c1
5531   // fold (aext c1) -> c1
5532   if (isa<ConstantSDNode>(N0))
5533     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5534
5535   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5536   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5537   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5538   EVT SVT = VT.getScalarType();
5539   if (!(VT.isVector() &&
5540       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5541       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5542     return nullptr;
5543
5544   // We can fold this node into a build_vector.
5545   unsigned VTBits = SVT.getSizeInBits();
5546   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5547   unsigned ShAmt = VTBits - EVTBits;
5548   SmallVector<SDValue, 8> Elts;
5549   unsigned NumElts = N0->getNumOperands();
5550   SDLoc DL(N);
5551
5552   for (unsigned i=0; i != NumElts; ++i) {
5553     SDValue Op = N0->getOperand(i);
5554     if (Op->getOpcode() == ISD::UNDEF) {
5555       Elts.push_back(DAG.getUNDEF(SVT));
5556       continue;
5557     }
5558
5559     SDLoc DL(Op);
5560     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5561     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5562     if (Opcode == ISD::SIGN_EXTEND)
5563       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5564                                      DL, SVT));
5565     else
5566       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5567                                      DL, SVT));
5568   }
5569
5570   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5571 }
5572
5573 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5574 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5575 // transformation. Returns true if extension are possible and the above
5576 // mentioned transformation is profitable.
5577 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5578                                     unsigned ExtOpc,
5579                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5580                                     const TargetLowering &TLI) {
5581   bool HasCopyToRegUses = false;
5582   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5583   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5584                             UE = N0.getNode()->use_end();
5585        UI != UE; ++UI) {
5586     SDNode *User = *UI;
5587     if (User == N)
5588       continue;
5589     if (UI.getUse().getResNo() != N0.getResNo())
5590       continue;
5591     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5592     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5593       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5594       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5595         // Sign bits will be lost after a zext.
5596         return false;
5597       bool Add = false;
5598       for (unsigned i = 0; i != 2; ++i) {
5599         SDValue UseOp = User->getOperand(i);
5600         if (UseOp == N0)
5601           continue;
5602         if (!isa<ConstantSDNode>(UseOp))
5603           return false;
5604         Add = true;
5605       }
5606       if (Add)
5607         ExtendNodes.push_back(User);
5608       continue;
5609     }
5610     // If truncates aren't free and there are users we can't
5611     // extend, it isn't worthwhile.
5612     if (!isTruncFree)
5613       return false;
5614     // Remember if this value is live-out.
5615     if (User->getOpcode() == ISD::CopyToReg)
5616       HasCopyToRegUses = true;
5617   }
5618
5619   if (HasCopyToRegUses) {
5620     bool BothLiveOut = false;
5621     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5622          UI != UE; ++UI) {
5623       SDUse &Use = UI.getUse();
5624       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5625         BothLiveOut = true;
5626         break;
5627       }
5628     }
5629     if (BothLiveOut)
5630       // Both unextended and extended values are live out. There had better be
5631       // a good reason for the transformation.
5632       return ExtendNodes.size();
5633   }
5634   return true;
5635 }
5636
5637 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5638                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5639                                   ISD::NodeType ExtType) {
5640   // Extend SetCC uses if necessary.
5641   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5642     SDNode *SetCC = SetCCs[i];
5643     SmallVector<SDValue, 4> Ops;
5644
5645     for (unsigned j = 0; j != 2; ++j) {
5646       SDValue SOp = SetCC->getOperand(j);
5647       if (SOp == Trunc)
5648         Ops.push_back(ExtLoad);
5649       else
5650         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5651     }
5652
5653     Ops.push_back(SetCC->getOperand(2));
5654     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5655   }
5656 }
5657
5658 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5659 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5660   SDValue N0 = N->getOperand(0);
5661   EVT DstVT = N->getValueType(0);
5662   EVT SrcVT = N0.getValueType();
5663
5664   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5665           N->getOpcode() == ISD::ZERO_EXTEND) &&
5666          "Unexpected node type (not an extend)!");
5667
5668   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5669   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5670   //   (v8i32 (sext (v8i16 (load x))))
5671   // into:
5672   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5673   //                          (v4i32 (sextload (x + 16)))))
5674   // Where uses of the original load, i.e.:
5675   //   (v8i16 (load x))
5676   // are replaced with:
5677   //   (v8i16 (truncate
5678   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5679   //                            (v4i32 (sextload (x + 16)))))))
5680   //
5681   // This combine is only applicable to illegal, but splittable, vectors.
5682   // All legal types, and illegal non-vector types, are handled elsewhere.
5683   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5684   //
5685   if (N0->getOpcode() != ISD::LOAD)
5686     return SDValue();
5687
5688   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5689
5690   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5691       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5692       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5693     return SDValue();
5694
5695   SmallVector<SDNode *, 4> SetCCs;
5696   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5697     return SDValue();
5698
5699   ISD::LoadExtType ExtType =
5700       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5701
5702   // Try to split the vector types to get down to legal types.
5703   EVT SplitSrcVT = SrcVT;
5704   EVT SplitDstVT = DstVT;
5705   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5706          SplitSrcVT.getVectorNumElements() > 1) {
5707     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5708     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5709   }
5710
5711   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5712     return SDValue();
5713
5714   SDLoc DL(N);
5715   const unsigned NumSplits =
5716       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5717   const unsigned Stride = SplitSrcVT.getStoreSize();
5718   SmallVector<SDValue, 4> Loads;
5719   SmallVector<SDValue, 4> Chains;
5720
5721   SDValue BasePtr = LN0->getBasePtr();
5722   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5723     const unsigned Offset = Idx * Stride;
5724     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5725
5726     SDValue SplitLoad = DAG.getExtLoad(
5727         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5728         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5729         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5730         Align, LN0->getAAInfo());
5731
5732     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5733                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5734
5735     Loads.push_back(SplitLoad.getValue(0));
5736     Chains.push_back(SplitLoad.getValue(1));
5737   }
5738
5739   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5740   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5741
5742   CombineTo(N, NewValue);
5743
5744   // Replace uses of the original load (before extension)
5745   // with a truncate of the concatenated sextloaded vectors.
5746   SDValue Trunc =
5747       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5748   CombineTo(N0.getNode(), Trunc, NewChain);
5749   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5750                   (ISD::NodeType)N->getOpcode());
5751   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5752 }
5753
5754 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5755   SDValue N0 = N->getOperand(0);
5756   EVT VT = N->getValueType(0);
5757
5758   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5759                                               LegalOperations))
5760     return SDValue(Res, 0);
5761
5762   // fold (sext (sext x)) -> (sext x)
5763   // fold (sext (aext x)) -> (sext x)
5764   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5765     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5766                        N0.getOperand(0));
5767
5768   if (N0.getOpcode() == ISD::TRUNCATE) {
5769     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5770     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5771     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5772     if (NarrowLoad.getNode()) {
5773       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5774       if (NarrowLoad.getNode() != N0.getNode()) {
5775         CombineTo(N0.getNode(), NarrowLoad);
5776         // CombineTo deleted the truncate, if needed, but not what's under it.
5777         AddToWorklist(oye);
5778       }
5779       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5780     }
5781
5782     // See if the value being truncated is already sign extended.  If so, just
5783     // eliminate the trunc/sext pair.
5784     SDValue Op = N0.getOperand(0);
5785     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5786     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5787     unsigned DestBits = VT.getScalarType().getSizeInBits();
5788     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5789
5790     if (OpBits == DestBits) {
5791       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5792       // bits, it is already ready.
5793       if (NumSignBits > DestBits-MidBits)
5794         return Op;
5795     } else if (OpBits < DestBits) {
5796       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5797       // bits, just sext from i32.
5798       if (NumSignBits > OpBits-MidBits)
5799         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5800     } else {
5801       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5802       // bits, just truncate to i32.
5803       if (NumSignBits > OpBits-MidBits)
5804         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5805     }
5806
5807     // fold (sext (truncate x)) -> (sextinreg x).
5808     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5809                                                  N0.getValueType())) {
5810       if (OpBits < DestBits)
5811         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5812       else if (OpBits > DestBits)
5813         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5814       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5815                          DAG.getValueType(N0.getValueType()));
5816     }
5817   }
5818
5819   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5820   // Only generate vector extloads when 1) they're legal, and 2) they are
5821   // deemed desirable by the target.
5822   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5823       ((!LegalOperations && !VT.isVector() &&
5824         !cast<LoadSDNode>(N0)->isVolatile()) ||
5825        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5826     bool DoXform = true;
5827     SmallVector<SDNode*, 4> SetCCs;
5828     if (!N0.hasOneUse())
5829       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5830     if (VT.isVector())
5831       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5832     if (DoXform) {
5833       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5834       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5835                                        LN0->getChain(),
5836                                        LN0->getBasePtr(), N0.getValueType(),
5837                                        LN0->getMemOperand());
5838       CombineTo(N, ExtLoad);
5839       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5840                                   N0.getValueType(), ExtLoad);
5841       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5842       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5843                       ISD::SIGN_EXTEND);
5844       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5845     }
5846   }
5847
5848   // fold (sext (load x)) to multiple smaller sextloads.
5849   // Only on illegal but splittable vectors.
5850   if (SDValue ExtLoad = CombineExtLoad(N))
5851     return ExtLoad;
5852
5853   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5854   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5855   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5856       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5857     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5858     EVT MemVT = LN0->getMemoryVT();
5859     if ((!LegalOperations && !LN0->isVolatile()) ||
5860         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5861       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5862                                        LN0->getChain(),
5863                                        LN0->getBasePtr(), MemVT,
5864                                        LN0->getMemOperand());
5865       CombineTo(N, ExtLoad);
5866       CombineTo(N0.getNode(),
5867                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5868                             N0.getValueType(), ExtLoad),
5869                 ExtLoad.getValue(1));
5870       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5871     }
5872   }
5873
5874   // fold (sext (and/or/xor (load x), cst)) ->
5875   //      (and/or/xor (sextload x), (sext cst))
5876   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5877        N0.getOpcode() == ISD::XOR) &&
5878       isa<LoadSDNode>(N0.getOperand(0)) &&
5879       N0.getOperand(1).getOpcode() == ISD::Constant &&
5880       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5881       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5882     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5883     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5884       bool DoXform = true;
5885       SmallVector<SDNode*, 4> SetCCs;
5886       if (!N0.hasOneUse())
5887         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5888                                           SetCCs, TLI);
5889       if (DoXform) {
5890         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5891                                          LN0->getChain(), LN0->getBasePtr(),
5892                                          LN0->getMemoryVT(),
5893                                          LN0->getMemOperand());
5894         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5895         Mask = Mask.sext(VT.getSizeInBits());
5896         SDLoc DL(N);
5897         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5898                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5899         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5900                                     SDLoc(N0.getOperand(0)),
5901                                     N0.getOperand(0).getValueType(), ExtLoad);
5902         CombineTo(N, And);
5903         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5904         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5905                         ISD::SIGN_EXTEND);
5906         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5907       }
5908     }
5909   }
5910
5911   if (N0.getOpcode() == ISD::SETCC) {
5912     EVT N0VT = N0.getOperand(0).getValueType();
5913     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5914     // Only do this before legalize for now.
5915     if (VT.isVector() && !LegalOperations &&
5916         TLI.getBooleanContents(N0VT) ==
5917             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5918       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5919       // of the same size as the compared operands. Only optimize sext(setcc())
5920       // if this is the case.
5921       EVT SVT = getSetCCResultType(N0VT);
5922
5923       // We know that the # elements of the results is the same as the
5924       // # elements of the compare (and the # elements of the compare result
5925       // for that matter).  Check to see that they are the same size.  If so,
5926       // we know that the element size of the sext'd result matches the
5927       // element size of the compare operands.
5928       if (VT.getSizeInBits() == SVT.getSizeInBits())
5929         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5930                              N0.getOperand(1),
5931                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5932
5933       // If the desired elements are smaller or larger than the source
5934       // elements we can use a matching integer vector type and then
5935       // truncate/sign extend
5936       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5937       if (SVT == MatchingVectorType) {
5938         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5939                                N0.getOperand(0), N0.getOperand(1),
5940                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5941         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5942       }
5943     }
5944
5945     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5946     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5947     SDLoc DL(N);
5948     SDValue NegOne =
5949       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5950     SDValue SCC =
5951       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5952                        NegOne, DAG.getConstant(0, DL, VT),
5953                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5954     if (SCC.getNode()) return SCC;
5955
5956     if (!VT.isVector()) {
5957       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5958       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5959         SDLoc DL(N);
5960         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5961         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5962                                      N0.getOperand(0), N0.getOperand(1), CC);
5963         return DAG.getSelect(DL, VT, SetCC,
5964                              NegOne, DAG.getConstant(0, DL, VT));
5965       }
5966     }
5967   }
5968
5969   // fold (sext x) -> (zext x) if the sign bit is known zero.
5970   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5971       DAG.SignBitIsZero(N0))
5972     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5973
5974   return SDValue();
5975 }
5976
5977 // isTruncateOf - If N is a truncate of some other value, return true, record
5978 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5979 // This function computes KnownZero to avoid a duplicated call to
5980 // computeKnownBits in the caller.
5981 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5982                          APInt &KnownZero) {
5983   APInt KnownOne;
5984   if (N->getOpcode() == ISD::TRUNCATE) {
5985     Op = N->getOperand(0);
5986     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5987     return true;
5988   }
5989
5990   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5991       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5992     return false;
5993
5994   SDValue Op0 = N->getOperand(0);
5995   SDValue Op1 = N->getOperand(1);
5996   assert(Op0.getValueType() == Op1.getValueType());
5997
5998   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5999   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
6000   if (COp0 && COp0->isNullValue())
6001     Op = Op1;
6002   else if (COp1 && COp1->isNullValue())
6003     Op = Op0;
6004   else
6005     return false;
6006
6007   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6008
6009   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6010     return false;
6011
6012   return true;
6013 }
6014
6015 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6016   SDValue N0 = N->getOperand(0);
6017   EVT VT = N->getValueType(0);
6018
6019   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6020                                               LegalOperations))
6021     return SDValue(Res, 0);
6022
6023   // fold (zext (zext x)) -> (zext x)
6024   // fold (zext (aext x)) -> (zext x)
6025   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6026     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6027                        N0.getOperand(0));
6028
6029   // fold (zext (truncate x)) -> (zext x) or
6030   //      (zext (truncate x)) -> (truncate x)
6031   // This is valid when the truncated bits of x are already zero.
6032   // FIXME: We should extend this to work for vectors too.
6033   SDValue Op;
6034   APInt KnownZero;
6035   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6036     APInt TruncatedBits =
6037       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6038       APInt(Op.getValueSizeInBits(), 0) :
6039       APInt::getBitsSet(Op.getValueSizeInBits(),
6040                         N0.getValueSizeInBits(),
6041                         std::min(Op.getValueSizeInBits(),
6042                                  VT.getSizeInBits()));
6043     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6044       if (VT.bitsGT(Op.getValueType()))
6045         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6046       if (VT.bitsLT(Op.getValueType()))
6047         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6048
6049       return Op;
6050     }
6051   }
6052
6053   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6054   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6055   if (N0.getOpcode() == ISD::TRUNCATE) {
6056     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6057     if (NarrowLoad.getNode()) {
6058       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6059       if (NarrowLoad.getNode() != N0.getNode()) {
6060         CombineTo(N0.getNode(), NarrowLoad);
6061         // CombineTo deleted the truncate, if needed, but not what's under it.
6062         AddToWorklist(oye);
6063       }
6064       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6065     }
6066   }
6067
6068   // fold (zext (truncate x)) -> (and x, mask)
6069   if (N0.getOpcode() == ISD::TRUNCATE &&
6070       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6071
6072     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6073     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6074     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6075     if (NarrowLoad.getNode()) {
6076       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6077       if (NarrowLoad.getNode() != N0.getNode()) {
6078         CombineTo(N0.getNode(), NarrowLoad);
6079         // CombineTo deleted the truncate, if needed, but not what's under it.
6080         AddToWorklist(oye);
6081       }
6082       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6083     }
6084
6085     SDValue Op = N0.getOperand(0);
6086     if (Op.getValueType().bitsLT(VT)) {
6087       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6088       AddToWorklist(Op.getNode());
6089     } else if (Op.getValueType().bitsGT(VT)) {
6090       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6091       AddToWorklist(Op.getNode());
6092     }
6093     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6094                                   N0.getValueType().getScalarType());
6095   }
6096
6097   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6098   // if either of the casts is not free.
6099   if (N0.getOpcode() == ISD::AND &&
6100       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6101       N0.getOperand(1).getOpcode() == ISD::Constant &&
6102       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6103                            N0.getValueType()) ||
6104        !TLI.isZExtFree(N0.getValueType(), VT))) {
6105     SDValue X = N0.getOperand(0).getOperand(0);
6106     if (X.getValueType().bitsLT(VT)) {
6107       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6108     } else if (X.getValueType().bitsGT(VT)) {
6109       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6110     }
6111     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6112     Mask = Mask.zext(VT.getSizeInBits());
6113     SDLoc DL(N);
6114     return DAG.getNode(ISD::AND, DL, VT,
6115                        X, DAG.getConstant(Mask, DL, VT));
6116   }
6117
6118   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6119   // Only generate vector extloads when 1) they're legal, and 2) they are
6120   // deemed desirable by the target.
6121   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6122       ((!LegalOperations && !VT.isVector() &&
6123         !cast<LoadSDNode>(N0)->isVolatile()) ||
6124        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6125     bool DoXform = true;
6126     SmallVector<SDNode*, 4> SetCCs;
6127     if (!N0.hasOneUse())
6128       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6129     if (VT.isVector())
6130       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6131     if (DoXform) {
6132       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6133       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6134                                        LN0->getChain(),
6135                                        LN0->getBasePtr(), N0.getValueType(),
6136                                        LN0->getMemOperand());
6137       CombineTo(N, ExtLoad);
6138       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6139                                   N0.getValueType(), ExtLoad);
6140       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6141
6142       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6143                       ISD::ZERO_EXTEND);
6144       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6145     }
6146   }
6147
6148   // fold (zext (load x)) to multiple smaller zextloads.
6149   // Only on illegal but splittable vectors.
6150   if (SDValue ExtLoad = CombineExtLoad(N))
6151     return ExtLoad;
6152
6153   // fold (zext (and/or/xor (load x), cst)) ->
6154   //      (and/or/xor (zextload x), (zext cst))
6155   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6156        N0.getOpcode() == ISD::XOR) &&
6157       isa<LoadSDNode>(N0.getOperand(0)) &&
6158       N0.getOperand(1).getOpcode() == ISD::Constant &&
6159       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6160       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6161     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6162     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6163       bool DoXform = true;
6164       SmallVector<SDNode*, 4> SetCCs;
6165       if (!N0.hasOneUse())
6166         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6167                                           SetCCs, TLI);
6168       if (DoXform) {
6169         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6170                                          LN0->getChain(), LN0->getBasePtr(),
6171                                          LN0->getMemoryVT(),
6172                                          LN0->getMemOperand());
6173         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6174         Mask = Mask.zext(VT.getSizeInBits());
6175         SDLoc DL(N);
6176         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6177                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6178         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6179                                     SDLoc(N0.getOperand(0)),
6180                                     N0.getOperand(0).getValueType(), ExtLoad);
6181         CombineTo(N, And);
6182         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6183         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6184                         ISD::ZERO_EXTEND);
6185         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6186       }
6187     }
6188   }
6189
6190   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6191   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6192   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6193       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6194     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6195     EVT MemVT = LN0->getMemoryVT();
6196     if ((!LegalOperations && !LN0->isVolatile()) ||
6197         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6198       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6199                                        LN0->getChain(),
6200                                        LN0->getBasePtr(), MemVT,
6201                                        LN0->getMemOperand());
6202       CombineTo(N, ExtLoad);
6203       CombineTo(N0.getNode(),
6204                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6205                             ExtLoad),
6206                 ExtLoad.getValue(1));
6207       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6208     }
6209   }
6210
6211   if (N0.getOpcode() == ISD::SETCC) {
6212     if (!LegalOperations && VT.isVector() &&
6213         N0.getValueType().getVectorElementType() == MVT::i1) {
6214       EVT N0VT = N0.getOperand(0).getValueType();
6215       if (getSetCCResultType(N0VT) == N0.getValueType())
6216         return SDValue();
6217
6218       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6219       // Only do this before legalize for now.
6220       EVT EltVT = VT.getVectorElementType();
6221       SDLoc DL(N);
6222       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6223                                     DAG.getConstant(1, DL, EltVT));
6224       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6225         // We know that the # elements of the results is the same as the
6226         // # elements of the compare (and the # elements of the compare result
6227         // for that matter).  Check to see that they are the same size.  If so,
6228         // we know that the element size of the sext'd result matches the
6229         // element size of the compare operands.
6230         return DAG.getNode(ISD::AND, DL, VT,
6231                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6232                                          N0.getOperand(1),
6233                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6234                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6235                                        OneOps));
6236
6237       // If the desired elements are smaller or larger than the source
6238       // elements we can use a matching integer vector type and then
6239       // truncate/sign extend
6240       EVT MatchingElementType =
6241         EVT::getIntegerVT(*DAG.getContext(),
6242                           N0VT.getScalarType().getSizeInBits());
6243       EVT MatchingVectorType =
6244         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6245                          N0VT.getVectorNumElements());
6246       SDValue VsetCC =
6247         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6248                       N0.getOperand(1),
6249                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6250       return DAG.getNode(ISD::AND, DL, VT,
6251                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6252                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6253     }
6254
6255     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6256     SDLoc DL(N);
6257     SDValue SCC =
6258       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6259                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6260                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6261     if (SCC.getNode()) return SCC;
6262   }
6263
6264   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6265   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6266       isa<ConstantSDNode>(N0.getOperand(1)) &&
6267       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6268       N0.hasOneUse()) {
6269     SDValue ShAmt = N0.getOperand(1);
6270     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6271     if (N0.getOpcode() == ISD::SHL) {
6272       SDValue InnerZExt = N0.getOperand(0);
6273       // If the original shl may be shifting out bits, do not perform this
6274       // transformation.
6275       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6276         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6277       if (ShAmtVal > KnownZeroBits)
6278         return SDValue();
6279     }
6280
6281     SDLoc DL(N);
6282
6283     // Ensure that the shift amount is wide enough for the shifted value.
6284     if (VT.getSizeInBits() >= 256)
6285       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6286
6287     return DAG.getNode(N0.getOpcode(), DL, VT,
6288                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6289                        ShAmt);
6290   }
6291
6292   return SDValue();
6293 }
6294
6295 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6296   SDValue N0 = N->getOperand(0);
6297   EVT VT = N->getValueType(0);
6298
6299   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6300                                               LegalOperations))
6301     return SDValue(Res, 0);
6302
6303   // fold (aext (aext x)) -> (aext x)
6304   // fold (aext (zext x)) -> (zext x)
6305   // fold (aext (sext x)) -> (sext x)
6306   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6307       N0.getOpcode() == ISD::ZERO_EXTEND ||
6308       N0.getOpcode() == ISD::SIGN_EXTEND)
6309     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6310
6311   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6312   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6313   if (N0.getOpcode() == ISD::TRUNCATE) {
6314     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6315     if (NarrowLoad.getNode()) {
6316       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6317       if (NarrowLoad.getNode() != N0.getNode()) {
6318         CombineTo(N0.getNode(), NarrowLoad);
6319         // CombineTo deleted the truncate, if needed, but not what's under it.
6320         AddToWorklist(oye);
6321       }
6322       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6323     }
6324   }
6325
6326   // fold (aext (truncate x))
6327   if (N0.getOpcode() == ISD::TRUNCATE) {
6328     SDValue TruncOp = N0.getOperand(0);
6329     if (TruncOp.getValueType() == VT)
6330       return TruncOp; // x iff x size == zext size.
6331     if (TruncOp.getValueType().bitsGT(VT))
6332       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6333     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6334   }
6335
6336   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6337   // if the trunc is not free.
6338   if (N0.getOpcode() == ISD::AND &&
6339       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6340       N0.getOperand(1).getOpcode() == ISD::Constant &&
6341       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6342                           N0.getValueType())) {
6343     SDValue X = N0.getOperand(0).getOperand(0);
6344     if (X.getValueType().bitsLT(VT)) {
6345       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6346     } else if (X.getValueType().bitsGT(VT)) {
6347       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6348     }
6349     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6350     Mask = Mask.zext(VT.getSizeInBits());
6351     SDLoc DL(N);
6352     return DAG.getNode(ISD::AND, DL, VT,
6353                        X, DAG.getConstant(Mask, DL, VT));
6354   }
6355
6356   // fold (aext (load x)) -> (aext (truncate (extload x)))
6357   // None of the supported targets knows how to perform load and any_ext
6358   // on vectors in one instruction.  We only perform this transformation on
6359   // scalars.
6360   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6361       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6362       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6363     bool DoXform = true;
6364     SmallVector<SDNode*, 4> SetCCs;
6365     if (!N0.hasOneUse())
6366       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6367     if (DoXform) {
6368       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6369       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6370                                        LN0->getChain(),
6371                                        LN0->getBasePtr(), N0.getValueType(),
6372                                        LN0->getMemOperand());
6373       CombineTo(N, ExtLoad);
6374       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6375                                   N0.getValueType(), ExtLoad);
6376       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6377       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6378                       ISD::ANY_EXTEND);
6379       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6380     }
6381   }
6382
6383   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6384   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6385   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6386   if (N0.getOpcode() == ISD::LOAD &&
6387       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6388       N0.hasOneUse()) {
6389     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6390     ISD::LoadExtType ExtType = LN0->getExtensionType();
6391     EVT MemVT = LN0->getMemoryVT();
6392     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6393       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6394                                        VT, LN0->getChain(), LN0->getBasePtr(),
6395                                        MemVT, LN0->getMemOperand());
6396       CombineTo(N, ExtLoad);
6397       CombineTo(N0.getNode(),
6398                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6399                             N0.getValueType(), ExtLoad),
6400                 ExtLoad.getValue(1));
6401       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6402     }
6403   }
6404
6405   if (N0.getOpcode() == ISD::SETCC) {
6406     // For vectors:
6407     // aext(setcc) -> vsetcc
6408     // aext(setcc) -> truncate(vsetcc)
6409     // aext(setcc) -> aext(vsetcc)
6410     // Only do this before legalize for now.
6411     if (VT.isVector() && !LegalOperations) {
6412       EVT N0VT = N0.getOperand(0).getValueType();
6413         // We know that the # elements of the results is the same as the
6414         // # elements of the compare (and the # elements of the compare result
6415         // for that matter).  Check to see that they are the same size.  If so,
6416         // we know that the element size of the sext'd result matches the
6417         // element size of the compare operands.
6418       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6419         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6420                              N0.getOperand(1),
6421                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6422       // If the desired elements are smaller or larger than the source
6423       // elements we can use a matching integer vector type and then
6424       // truncate/any extend
6425       else {
6426         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6427         SDValue VsetCC =
6428           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6429                         N0.getOperand(1),
6430                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6431         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6432       }
6433     }
6434
6435     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6436     SDLoc DL(N);
6437     SDValue SCC =
6438       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6439                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6440                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6441     if (SCC.getNode())
6442       return SCC;
6443   }
6444
6445   return SDValue();
6446 }
6447
6448 /// See if the specified operand can be simplified with the knowledge that only
6449 /// the bits specified by Mask are used.  If so, return the simpler operand,
6450 /// otherwise return a null SDValue.
6451 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6452   switch (V.getOpcode()) {
6453   default: break;
6454   case ISD::Constant: {
6455     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6456     assert(CV && "Const value should be ConstSDNode.");
6457     const APInt &CVal = CV->getAPIntValue();
6458     APInt NewVal = CVal & Mask;
6459     if (NewVal != CVal)
6460       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6461     break;
6462   }
6463   case ISD::OR:
6464   case ISD::XOR:
6465     // If the LHS or RHS don't contribute bits to the or, drop them.
6466     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6467       return V.getOperand(1);
6468     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6469       return V.getOperand(0);
6470     break;
6471   case ISD::SRL:
6472     // Only look at single-use SRLs.
6473     if (!V.getNode()->hasOneUse())
6474       break;
6475     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6476       // See if we can recursively simplify the LHS.
6477       unsigned Amt = RHSC->getZExtValue();
6478
6479       // Watch out for shift count overflow though.
6480       if (Amt >= Mask.getBitWidth()) break;
6481       APInt NewMask = Mask << Amt;
6482       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6483       if (SimplifyLHS.getNode())
6484         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6485                            SimplifyLHS, V.getOperand(1));
6486     }
6487   }
6488   return SDValue();
6489 }
6490
6491 /// If the result of a wider load is shifted to right of N  bits and then
6492 /// truncated to a narrower type and where N is a multiple of number of bits of
6493 /// the narrower type, transform it to a narrower load from address + N / num of
6494 /// bits of new type. If the result is to be extended, also fold the extension
6495 /// to form a extending load.
6496 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6497   unsigned Opc = N->getOpcode();
6498
6499   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6500   SDValue N0 = N->getOperand(0);
6501   EVT VT = N->getValueType(0);
6502   EVT ExtVT = VT;
6503
6504   // This transformation isn't valid for vector loads.
6505   if (VT.isVector())
6506     return SDValue();
6507
6508   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6509   // extended to VT.
6510   if (Opc == ISD::SIGN_EXTEND_INREG) {
6511     ExtType = ISD::SEXTLOAD;
6512     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6513   } else if (Opc == ISD::SRL) {
6514     // Another special-case: SRL is basically zero-extending a narrower value.
6515     ExtType = ISD::ZEXTLOAD;
6516     N0 = SDValue(N, 0);
6517     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6518     if (!N01) return SDValue();
6519     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6520                               VT.getSizeInBits() - N01->getZExtValue());
6521   }
6522   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6523     return SDValue();
6524
6525   unsigned EVTBits = ExtVT.getSizeInBits();
6526
6527   // Do not generate loads of non-round integer types since these can
6528   // be expensive (and would be wrong if the type is not byte sized).
6529   if (!ExtVT.isRound())
6530     return SDValue();
6531
6532   unsigned ShAmt = 0;
6533   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6534     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6535       ShAmt = N01->getZExtValue();
6536       // Is the shift amount a multiple of size of VT?
6537       if ((ShAmt & (EVTBits-1)) == 0) {
6538         N0 = N0.getOperand(0);
6539         // Is the load width a multiple of size of VT?
6540         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6541           return SDValue();
6542       }
6543
6544       // At this point, we must have a load or else we can't do the transform.
6545       if (!isa<LoadSDNode>(N0)) return SDValue();
6546
6547       // Because a SRL must be assumed to *need* to zero-extend the high bits
6548       // (as opposed to anyext the high bits), we can't combine the zextload
6549       // lowering of SRL and an sextload.
6550       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6551         return SDValue();
6552
6553       // If the shift amount is larger than the input type then we're not
6554       // accessing any of the loaded bytes.  If the load was a zextload/extload
6555       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6556       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6557         return SDValue();
6558     }
6559   }
6560
6561   // If the load is shifted left (and the result isn't shifted back right),
6562   // we can fold the truncate through the shift.
6563   unsigned ShLeftAmt = 0;
6564   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6565       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6566     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6567       ShLeftAmt = N01->getZExtValue();
6568       N0 = N0.getOperand(0);
6569     }
6570   }
6571
6572   // If we haven't found a load, we can't narrow it.  Don't transform one with
6573   // multiple uses, this would require adding a new load.
6574   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6575     return SDValue();
6576
6577   // Don't change the width of a volatile load.
6578   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6579   if (LN0->isVolatile())
6580     return SDValue();
6581
6582   // Verify that we are actually reducing a load width here.
6583   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6584     return SDValue();
6585
6586   // For the transform to be legal, the load must produce only two values
6587   // (the value loaded and the chain).  Don't transform a pre-increment
6588   // load, for example, which produces an extra value.  Otherwise the
6589   // transformation is not equivalent, and the downstream logic to replace
6590   // uses gets things wrong.
6591   if (LN0->getNumValues() > 2)
6592     return SDValue();
6593
6594   // If the load that we're shrinking is an extload and we're not just
6595   // discarding the extension we can't simply shrink the load. Bail.
6596   // TODO: It would be possible to merge the extensions in some cases.
6597   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6598       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6599     return SDValue();
6600
6601   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6602     return SDValue();
6603
6604   EVT PtrType = N0.getOperand(1).getValueType();
6605
6606   if (PtrType == MVT::Untyped || PtrType.isExtended())
6607     // It's not possible to generate a constant of extended or untyped type.
6608     return SDValue();
6609
6610   // For big endian targets, we need to adjust the offset to the pointer to
6611   // load the correct bytes.
6612   if (TLI.isBigEndian()) {
6613     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6614     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6615     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6616   }
6617
6618   uint64_t PtrOff = ShAmt / 8;
6619   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6620   SDLoc DL(LN0);
6621   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6622                                PtrType, LN0->getBasePtr(),
6623                                DAG.getConstant(PtrOff, DL, PtrType));
6624   AddToWorklist(NewPtr.getNode());
6625
6626   SDValue Load;
6627   if (ExtType == ISD::NON_EXTLOAD)
6628     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6629                         LN0->getPointerInfo().getWithOffset(PtrOff),
6630                         LN0->isVolatile(), LN0->isNonTemporal(),
6631                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6632   else
6633     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6634                           LN0->getPointerInfo().getWithOffset(PtrOff),
6635                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6636                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6637
6638   // Replace the old load's chain with the new load's chain.
6639   WorklistRemover DeadNodes(*this);
6640   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6641
6642   // Shift the result left, if we've swallowed a left shift.
6643   SDValue Result = Load;
6644   if (ShLeftAmt != 0) {
6645     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6646     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6647       ShImmTy = VT;
6648     // If the shift amount is as large as the result size (but, presumably,
6649     // no larger than the source) then the useful bits of the result are
6650     // zero; we can't simply return the shortened shift, because the result
6651     // of that operation is undefined.
6652     SDLoc DL(N0);
6653     if (ShLeftAmt >= VT.getSizeInBits())
6654       Result = DAG.getConstant(0, DL, VT);
6655     else
6656       Result = DAG.getNode(ISD::SHL, DL, VT,
6657                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6658   }
6659
6660   // Return the new loaded value.
6661   return Result;
6662 }
6663
6664 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6665   SDValue N0 = N->getOperand(0);
6666   SDValue N1 = N->getOperand(1);
6667   EVT VT = N->getValueType(0);
6668   EVT EVT = cast<VTSDNode>(N1)->getVT();
6669   unsigned VTBits = VT.getScalarType().getSizeInBits();
6670   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6671
6672   // fold (sext_in_reg c1) -> c1
6673   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6674     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6675
6676   // If the input is already sign extended, just drop the extension.
6677   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6678     return N0;
6679
6680   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6681   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6682       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6683     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6684                        N0.getOperand(0), N1);
6685
6686   // fold (sext_in_reg (sext x)) -> (sext x)
6687   // fold (sext_in_reg (aext x)) -> (sext x)
6688   // if x is small enough.
6689   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6690     SDValue N00 = N0.getOperand(0);
6691     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6692         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6693       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6694   }
6695
6696   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6697   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6698     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6699
6700   // fold operands of sext_in_reg based on knowledge that the top bits are not
6701   // demanded.
6702   if (SimplifyDemandedBits(SDValue(N, 0)))
6703     return SDValue(N, 0);
6704
6705   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6706   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6707   SDValue NarrowLoad = ReduceLoadWidth(N);
6708   if (NarrowLoad.getNode())
6709     return NarrowLoad;
6710
6711   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6712   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6713   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6714   if (N0.getOpcode() == ISD::SRL) {
6715     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6716       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6717         // We can turn this into an SRA iff the input to the SRL is already sign
6718         // extended enough.
6719         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6720         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6721           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6722                              N0.getOperand(0), N0.getOperand(1));
6723       }
6724   }
6725
6726   // fold (sext_inreg (extload x)) -> (sextload x)
6727   if (ISD::isEXTLoad(N0.getNode()) &&
6728       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6729       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6730       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6731        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6732     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6733     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6734                                      LN0->getChain(),
6735                                      LN0->getBasePtr(), EVT,
6736                                      LN0->getMemOperand());
6737     CombineTo(N, ExtLoad);
6738     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6739     AddToWorklist(ExtLoad.getNode());
6740     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6741   }
6742   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6743   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6744       N0.hasOneUse() &&
6745       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6746       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6747        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6748     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6749     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6750                                      LN0->getChain(),
6751                                      LN0->getBasePtr(), EVT,
6752                                      LN0->getMemOperand());
6753     CombineTo(N, ExtLoad);
6754     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6755     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6756   }
6757
6758   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6759   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6760     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6761                                        N0.getOperand(1), false);
6762     if (BSwap.getNode())
6763       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6764                          BSwap, N1);
6765   }
6766
6767   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6768   // into a build_vector.
6769   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6770     SmallVector<SDValue, 8> Elts;
6771     unsigned NumElts = N0->getNumOperands();
6772     unsigned ShAmt = VTBits - EVTBits;
6773
6774     for (unsigned i = 0; i != NumElts; ++i) {
6775       SDValue Op = N0->getOperand(i);
6776       if (Op->getOpcode() == ISD::UNDEF) {
6777         Elts.push_back(Op);
6778         continue;
6779       }
6780
6781       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6782       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6783       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6784                                      SDLoc(Op), Op.getValueType()));
6785     }
6786
6787     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6788   }
6789
6790   return SDValue();
6791 }
6792
6793 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6794   SDValue N0 = N->getOperand(0);
6795   EVT VT = N->getValueType(0);
6796   bool isLE = TLI.isLittleEndian();
6797
6798   // noop truncate
6799   if (N0.getValueType() == N->getValueType(0))
6800     return N0;
6801   // fold (truncate c1) -> c1
6802   if (isConstantIntBuildVectorOrConstantInt(N0))
6803     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6804   // fold (truncate (truncate x)) -> (truncate x)
6805   if (N0.getOpcode() == ISD::TRUNCATE)
6806     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6807   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6808   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6809       N0.getOpcode() == ISD::SIGN_EXTEND ||
6810       N0.getOpcode() == ISD::ANY_EXTEND) {
6811     if (N0.getOperand(0).getValueType().bitsLT(VT))
6812       // if the source is smaller than the dest, we still need an extend
6813       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6814                          N0.getOperand(0));
6815     if (N0.getOperand(0).getValueType().bitsGT(VT))
6816       // if the source is larger than the dest, than we just need the truncate
6817       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6818     // if the source and dest are the same type, we can drop both the extend
6819     // and the truncate.
6820     return N0.getOperand(0);
6821   }
6822
6823   // Fold extract-and-trunc into a narrow extract. For example:
6824   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6825   //   i32 y = TRUNCATE(i64 x)
6826   //        -- becomes --
6827   //   v16i8 b = BITCAST (v2i64 val)
6828   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6829   //
6830   // Note: We only run this optimization after type legalization (which often
6831   // creates this pattern) and before operation legalization after which
6832   // we need to be more careful about the vector instructions that we generate.
6833   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6834       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6835
6836     EVT VecTy = N0.getOperand(0).getValueType();
6837     EVT ExTy = N0.getValueType();
6838     EVT TrTy = N->getValueType(0);
6839
6840     unsigned NumElem = VecTy.getVectorNumElements();
6841     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6842
6843     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6844     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6845
6846     SDValue EltNo = N0->getOperand(1);
6847     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6848       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6849       EVT IndexTy = TLI.getVectorIdxTy();
6850       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6851
6852       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6853                               NVT, N0.getOperand(0));
6854
6855       SDLoc DL(N);
6856       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6857                          DL, TrTy, V,
6858                          DAG.getConstant(Index, DL, IndexTy));
6859     }
6860   }
6861
6862   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6863   if (N0.getOpcode() == ISD::SELECT) {
6864     EVT SrcVT = N0.getValueType();
6865     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6866         TLI.isTruncateFree(SrcVT, VT)) {
6867       SDLoc SL(N0);
6868       SDValue Cond = N0.getOperand(0);
6869       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6870       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6871       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6872     }
6873   }
6874
6875   // Fold a series of buildvector, bitcast, and truncate if possible.
6876   // For example fold
6877   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6878   //   (2xi32 (buildvector x, y)).
6879   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6880       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6881       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6882       N0.getOperand(0).hasOneUse()) {
6883
6884     SDValue BuildVect = N0.getOperand(0);
6885     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6886     EVT TruncVecEltTy = VT.getVectorElementType();
6887
6888     // Check that the element types match.
6889     if (BuildVectEltTy == TruncVecEltTy) {
6890       // Now we only need to compute the offset of the truncated elements.
6891       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6892       unsigned TruncVecNumElts = VT.getVectorNumElements();
6893       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6894
6895       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6896              "Invalid number of elements");
6897
6898       SmallVector<SDValue, 8> Opnds;
6899       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6900         Opnds.push_back(BuildVect.getOperand(i));
6901
6902       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6903     }
6904   }
6905
6906   // See if we can simplify the input to this truncate through knowledge that
6907   // only the low bits are being used.
6908   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6909   // Currently we only perform this optimization on scalars because vectors
6910   // may have different active low bits.
6911   if (!VT.isVector()) {
6912     SDValue Shorter =
6913       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6914                                                VT.getSizeInBits()));
6915     if (Shorter.getNode())
6916       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6917   }
6918   // fold (truncate (load x)) -> (smaller load x)
6919   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6920   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6921     SDValue Reduced = ReduceLoadWidth(N);
6922     if (Reduced.getNode())
6923       return Reduced;
6924     // Handle the case where the load remains an extending load even
6925     // after truncation.
6926     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6927       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6928       if (!LN0->isVolatile() &&
6929           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6930         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6931                                          VT, LN0->getChain(), LN0->getBasePtr(),
6932                                          LN0->getMemoryVT(),
6933                                          LN0->getMemOperand());
6934         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6935         return NewLoad;
6936       }
6937     }
6938   }
6939   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6940   // where ... are all 'undef'.
6941   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6942     SmallVector<EVT, 8> VTs;
6943     SDValue V;
6944     unsigned Idx = 0;
6945     unsigned NumDefs = 0;
6946
6947     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6948       SDValue X = N0.getOperand(i);
6949       if (X.getOpcode() != ISD::UNDEF) {
6950         V = X;
6951         Idx = i;
6952         NumDefs++;
6953       }
6954       // Stop if more than one members are non-undef.
6955       if (NumDefs > 1)
6956         break;
6957       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6958                                      VT.getVectorElementType(),
6959                                      X.getValueType().getVectorNumElements()));
6960     }
6961
6962     if (NumDefs == 0)
6963       return DAG.getUNDEF(VT);
6964
6965     if (NumDefs == 1) {
6966       assert(V.getNode() && "The single defined operand is empty!");
6967       SmallVector<SDValue, 8> Opnds;
6968       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6969         if (i != Idx) {
6970           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6971           continue;
6972         }
6973         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6974         AddToWorklist(NV.getNode());
6975         Opnds.push_back(NV);
6976       }
6977       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6978     }
6979   }
6980
6981   // Simplify the operands using demanded-bits information.
6982   if (!VT.isVector() &&
6983       SimplifyDemandedBits(SDValue(N, 0)))
6984     return SDValue(N, 0);
6985
6986   return SDValue();
6987 }
6988
6989 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6990   SDValue Elt = N->getOperand(i);
6991   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6992     return Elt.getNode();
6993   return Elt.getOperand(Elt.getResNo()).getNode();
6994 }
6995
6996 /// build_pair (load, load) -> load
6997 /// if load locations are consecutive.
6998 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6999   assert(N->getOpcode() == ISD::BUILD_PAIR);
7000
7001   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7002   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7003   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7004       LD1->getAddressSpace() != LD2->getAddressSpace())
7005     return SDValue();
7006   EVT LD1VT = LD1->getValueType(0);
7007
7008   if (ISD::isNON_EXTLoad(LD2) &&
7009       LD2->hasOneUse() &&
7010       // If both are volatile this would reduce the number of volatile loads.
7011       // If one is volatile it might be ok, but play conservative and bail out.
7012       !LD1->isVolatile() &&
7013       !LD2->isVolatile() &&
7014       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7015     unsigned Align = LD1->getAlignment();
7016     unsigned NewAlign = TLI.getDataLayout()->
7017       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7018
7019     if (NewAlign <= Align &&
7020         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7021       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7022                          LD1->getBasePtr(), LD1->getPointerInfo(),
7023                          false, false, false, Align);
7024   }
7025
7026   return SDValue();
7027 }
7028
7029 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7030   SDValue N0 = N->getOperand(0);
7031   EVT VT = N->getValueType(0);
7032
7033   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7034   // Only do this before legalize, since afterward the target may be depending
7035   // on the bitconvert.
7036   // First check to see if this is all constant.
7037   if (!LegalTypes &&
7038       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7039       VT.isVector()) {
7040     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7041
7042     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7043     assert(!DestEltVT.isVector() &&
7044            "Element type of vector ValueType must not be vector!");
7045     if (isSimple)
7046       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7047   }
7048
7049   // If the input is a constant, let getNode fold it.
7050   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7051     // If we can't allow illegal operations, we need to check that this is just
7052     // a fp -> int or int -> conversion and that the resulting operation will
7053     // be legal.
7054     if (!LegalOperations ||
7055         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7056          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7057         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7058          TLI.isOperationLegal(ISD::Constant, VT)))
7059       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7060   }
7061
7062   // (conv (conv x, t1), t2) -> (conv x, t2)
7063   if (N0.getOpcode() == ISD::BITCAST)
7064     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7065                        N0.getOperand(0));
7066
7067   // fold (conv (load x)) -> (load (conv*)x)
7068   // If the resultant load doesn't need a higher alignment than the original!
7069   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7070       // Do not change the width of a volatile load.
7071       !cast<LoadSDNode>(N0)->isVolatile() &&
7072       // Do not remove the cast if the types differ in endian layout.
7073       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7074       TLI.hasBigEndianPartOrdering(VT) &&
7075       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7076       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7077     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7078     unsigned Align = TLI.getDataLayout()->
7079       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7080     unsigned OrigAlign = LN0->getAlignment();
7081
7082     if (Align <= OrigAlign) {
7083       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7084                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7085                                  LN0->isVolatile(), LN0->isNonTemporal(),
7086                                  LN0->isInvariant(), OrigAlign,
7087                                  LN0->getAAInfo());
7088       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7089       return Load;
7090     }
7091   }
7092
7093   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7094   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7095   // This often reduces constant pool loads.
7096   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7097        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7098       N0.getNode()->hasOneUse() && VT.isInteger() &&
7099       !VT.isVector() && !N0.getValueType().isVector()) {
7100     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7101                                   N0.getOperand(0));
7102     AddToWorklist(NewConv.getNode());
7103
7104     SDLoc DL(N);
7105     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7106     if (N0.getOpcode() == ISD::FNEG)
7107       return DAG.getNode(ISD::XOR, DL, VT,
7108                          NewConv, DAG.getConstant(SignBit, DL, VT));
7109     assert(N0.getOpcode() == ISD::FABS);
7110     return DAG.getNode(ISD::AND, DL, VT,
7111                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7112   }
7113
7114   // fold (bitconvert (fcopysign cst, x)) ->
7115   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7116   // Note that we don't handle (copysign x, cst) because this can always be
7117   // folded to an fneg or fabs.
7118   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7119       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7120       VT.isInteger() && !VT.isVector()) {
7121     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7122     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7123     if (isTypeLegal(IntXVT)) {
7124       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7125                               IntXVT, N0.getOperand(1));
7126       AddToWorklist(X.getNode());
7127
7128       // If X has a different width than the result/lhs, sext it or truncate it.
7129       unsigned VTWidth = VT.getSizeInBits();
7130       if (OrigXWidth < VTWidth) {
7131         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7132         AddToWorklist(X.getNode());
7133       } else if (OrigXWidth > VTWidth) {
7134         // To get the sign bit in the right place, we have to shift it right
7135         // before truncating.
7136         SDLoc DL(X);
7137         X = DAG.getNode(ISD::SRL, DL,
7138                         X.getValueType(), X,
7139                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7140                                         X.getValueType()));
7141         AddToWorklist(X.getNode());
7142         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7143         AddToWorklist(X.getNode());
7144       }
7145
7146       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7147       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7148                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7149       AddToWorklist(X.getNode());
7150
7151       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7152                                 VT, N0.getOperand(0));
7153       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7154                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7155       AddToWorklist(Cst.getNode());
7156
7157       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7158     }
7159   }
7160
7161   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7162   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7163     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7164     if (CombineLD.getNode())
7165       return CombineLD;
7166   }
7167
7168   // Remove double bitcasts from shuffles - this is often a legacy of
7169   // XformToShuffleWithZero being used to combine bitmaskings (of
7170   // float vectors bitcast to integer vectors) into shuffles.
7171   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7172   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7173       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7174       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7175       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7176     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7177
7178     // If operands are a bitcast, peek through if it casts the original VT.
7179     // If operands are a UNDEF or constant, just bitcast back to original VT.
7180     auto PeekThroughBitcast = [&](SDValue Op) {
7181       if (Op.getOpcode() == ISD::BITCAST &&
7182           Op.getOperand(0)->getValueType(0) == VT)
7183         return SDValue(Op.getOperand(0));
7184       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7185           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7186         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7187       return SDValue();
7188     };
7189
7190     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7191     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7192     if (!(SV0 && SV1))
7193       return SDValue();
7194
7195     int MaskScale =
7196         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7197     SmallVector<int, 8> NewMask;
7198     for (int M : SVN->getMask())
7199       for (int i = 0; i != MaskScale; ++i)
7200         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7201
7202     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7203     if (!LegalMask) {
7204       std::swap(SV0, SV1);
7205       ShuffleVectorSDNode::commuteMask(NewMask);
7206       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7207     }
7208
7209     if (LegalMask)
7210       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7211   }
7212
7213   return SDValue();
7214 }
7215
7216 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7217   EVT VT = N->getValueType(0);
7218   return CombineConsecutiveLoads(N, VT);
7219 }
7220
7221 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7222 /// operands. DstEltVT indicates the destination element value type.
7223 SDValue DAGCombiner::
7224 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7225   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7226
7227   // If this is already the right type, we're done.
7228   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7229
7230   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7231   unsigned DstBitSize = DstEltVT.getSizeInBits();
7232
7233   // If this is a conversion of N elements of one type to N elements of another
7234   // type, convert each element.  This handles FP<->INT cases.
7235   if (SrcBitSize == DstBitSize) {
7236     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7237                               BV->getValueType(0).getVectorNumElements());
7238
7239     // Due to the FP element handling below calling this routine recursively,
7240     // we can end up with a scalar-to-vector node here.
7241     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7242       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7243                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7244                                      DstEltVT, BV->getOperand(0)));
7245
7246     SmallVector<SDValue, 8> Ops;
7247     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7248       SDValue Op = BV->getOperand(i);
7249       // If the vector element type is not legal, the BUILD_VECTOR operands
7250       // are promoted and implicitly truncated.  Make that explicit here.
7251       if (Op.getValueType() != SrcEltVT)
7252         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7253       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7254                                 DstEltVT, Op));
7255       AddToWorklist(Ops.back().getNode());
7256     }
7257     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7258   }
7259
7260   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7261   // handle annoying details of growing/shrinking FP values, we convert them to
7262   // int first.
7263   if (SrcEltVT.isFloatingPoint()) {
7264     // Convert the input float vector to a int vector where the elements are the
7265     // same sizes.
7266     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7267     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7268     SrcEltVT = IntVT;
7269   }
7270
7271   // Now we know the input is an integer vector.  If the output is a FP type,
7272   // convert to integer first, then to FP of the right size.
7273   if (DstEltVT.isFloatingPoint()) {
7274     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7275     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7276
7277     // Next, convert to FP elements of the same size.
7278     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7279   }
7280
7281   SDLoc DL(BV);
7282
7283   // Okay, we know the src/dst types are both integers of differing types.
7284   // Handling growing first.
7285   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7286   if (SrcBitSize < DstBitSize) {
7287     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7288
7289     SmallVector<SDValue, 8> Ops;
7290     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7291          i += NumInputsPerOutput) {
7292       bool isLE = TLI.isLittleEndian();
7293       APInt NewBits = APInt(DstBitSize, 0);
7294       bool EltIsUndef = true;
7295       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7296         // Shift the previously computed bits over.
7297         NewBits <<= SrcBitSize;
7298         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7299         if (Op.getOpcode() == ISD::UNDEF) continue;
7300         EltIsUndef = false;
7301
7302         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7303                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7304       }
7305
7306       if (EltIsUndef)
7307         Ops.push_back(DAG.getUNDEF(DstEltVT));
7308       else
7309         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7310     }
7311
7312     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7313     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7314   }
7315
7316   // Finally, this must be the case where we are shrinking elements: each input
7317   // turns into multiple outputs.
7318   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7319   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7320                             NumOutputsPerInput*BV->getNumOperands());
7321   SmallVector<SDValue, 8> Ops;
7322
7323   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7324     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7325       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7326       continue;
7327     }
7328
7329     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7330                   getAPIntValue().zextOrTrunc(SrcBitSize);
7331
7332     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7333       APInt ThisVal = OpVal.trunc(DstBitSize);
7334       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7335       OpVal = OpVal.lshr(DstBitSize);
7336     }
7337
7338     // For big endian targets, swap the order of the pieces of each element.
7339     if (TLI.isBigEndian())
7340       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7341   }
7342
7343   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7344 }
7345
7346 /// Try to perform FMA combining on a given FADD node.
7347 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7348   SDValue N0 = N->getOperand(0);
7349   SDValue N1 = N->getOperand(1);
7350   EVT VT = N->getValueType(0);
7351   SDLoc SL(N);
7352
7353   const TargetOptions &Options = DAG.getTarget().Options;
7354   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7355                        Options.UnsafeFPMath);
7356
7357   // Floating-point multiply-add with intermediate rounding.
7358   bool HasFMAD = (LegalOperations &&
7359                   TLI.isOperationLegal(ISD::FMAD, VT));
7360
7361   // Floating-point multiply-add without intermediate rounding.
7362   bool HasFMA = ((!LegalOperations ||
7363                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7364                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7365                  UnsafeFPMath);
7366
7367   // No valid opcode, do not combine.
7368   if (!HasFMAD && !HasFMA)
7369     return SDValue();
7370
7371   // Always prefer FMAD to FMA for precision.
7372   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7373   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7374   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7375
7376   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7377   if (N0.getOpcode() == ISD::FMUL &&
7378       (Aggressive || N0->hasOneUse())) {
7379     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7380                        N0.getOperand(0), N0.getOperand(1), N1);
7381   }
7382
7383   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7384   // Note: Commutes FADD operands.
7385   if (N1.getOpcode() == ISD::FMUL &&
7386       (Aggressive || N1->hasOneUse())) {
7387     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7388                        N1.getOperand(0), N1.getOperand(1), N0);
7389   }
7390
7391   // Look through FP_EXTEND nodes to do more combining.
7392   if (UnsafeFPMath && LookThroughFPExt) {
7393     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7394     if (N0.getOpcode() == ISD::FP_EXTEND) {
7395       SDValue N00 = N0.getOperand(0);
7396       if (N00.getOpcode() == ISD::FMUL)
7397         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7398                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7399                                        N00.getOperand(0)),
7400                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7401                                        N00.getOperand(1)), N1);
7402     }
7403
7404     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7405     // Note: Commutes FADD operands.
7406     if (N1.getOpcode() == ISD::FP_EXTEND) {
7407       SDValue N10 = N1.getOperand(0);
7408       if (N10.getOpcode() == ISD::FMUL)
7409         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7410                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7411                                        N10.getOperand(0)),
7412                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7413                                        N10.getOperand(1)), N0);
7414     }
7415   }
7416
7417   // More folding opportunities when target permits.
7418   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7419     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7420     if (N0.getOpcode() == PreferredFusedOpcode &&
7421         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7422       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7423                          N0.getOperand(0), N0.getOperand(1),
7424                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7425                                      N0.getOperand(2).getOperand(0),
7426                                      N0.getOperand(2).getOperand(1),
7427                                      N1));
7428     }
7429
7430     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7431     if (N1->getOpcode() == PreferredFusedOpcode &&
7432         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7433       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7434                          N1.getOperand(0), N1.getOperand(1),
7435                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7436                                      N1.getOperand(2).getOperand(0),
7437                                      N1.getOperand(2).getOperand(1),
7438                                      N0));
7439     }
7440
7441     if (UnsafeFPMath && LookThroughFPExt) {
7442       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7443       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7444       auto FoldFAddFMAFPExtFMul = [&] (
7445           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7446         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7447                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7448                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7449                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7450                                        Z));
7451       };
7452       if (N0.getOpcode() == PreferredFusedOpcode) {
7453         SDValue N02 = N0.getOperand(2);
7454         if (N02.getOpcode() == ISD::FP_EXTEND) {
7455           SDValue N020 = N02.getOperand(0);
7456           if (N020.getOpcode() == ISD::FMUL)
7457             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7458                                         N020.getOperand(0), N020.getOperand(1),
7459                                         N1);
7460         }
7461       }
7462
7463       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7464       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7465       // FIXME: This turns two single-precision and one double-precision
7466       // operation into two double-precision operations, which might not be
7467       // interesting for all targets, especially GPUs.
7468       auto FoldFAddFPExtFMAFMul = [&] (
7469           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7470         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7471                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7472                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7473                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7475                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7476                                        Z));
7477       };
7478       if (N0.getOpcode() == ISD::FP_EXTEND) {
7479         SDValue N00 = N0.getOperand(0);
7480         if (N00.getOpcode() == PreferredFusedOpcode) {
7481           SDValue N002 = N00.getOperand(2);
7482           if (N002.getOpcode() == ISD::FMUL)
7483             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7484                                         N002.getOperand(0), N002.getOperand(1),
7485                                         N1);
7486         }
7487       }
7488
7489       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7490       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7491       if (N1.getOpcode() == PreferredFusedOpcode) {
7492         SDValue N12 = N1.getOperand(2);
7493         if (N12.getOpcode() == ISD::FP_EXTEND) {
7494           SDValue N120 = N12.getOperand(0);
7495           if (N120.getOpcode() == ISD::FMUL)
7496             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7497                                         N120.getOperand(0), N120.getOperand(1),
7498                                         N0);
7499         }
7500       }
7501
7502       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7503       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7504       // FIXME: This turns two single-precision and one double-precision
7505       // operation into two double-precision operations, which might not be
7506       // interesting for all targets, especially GPUs.
7507       if (N1.getOpcode() == ISD::FP_EXTEND) {
7508         SDValue N10 = N1.getOperand(0);
7509         if (N10.getOpcode() == PreferredFusedOpcode) {
7510           SDValue N102 = N10.getOperand(2);
7511           if (N102.getOpcode() == ISD::FMUL)
7512             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7513                                         N102.getOperand(0), N102.getOperand(1),
7514                                         N0);
7515         }
7516       }
7517     }
7518   }
7519
7520   return SDValue();
7521 }
7522
7523 /// Try to perform FMA combining on a given FSUB node.
7524 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7525   SDValue N0 = N->getOperand(0);
7526   SDValue N1 = N->getOperand(1);
7527   EVT VT = N->getValueType(0);
7528   SDLoc SL(N);
7529
7530   const TargetOptions &Options = DAG.getTarget().Options;
7531   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7532                        Options.UnsafeFPMath);
7533
7534   // Floating-point multiply-add with intermediate rounding.
7535   bool HasFMAD = (LegalOperations &&
7536                   TLI.isOperationLegal(ISD::FMAD, VT));
7537
7538   // Floating-point multiply-add without intermediate rounding.
7539   bool HasFMA = ((!LegalOperations ||
7540                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7541                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7542                  UnsafeFPMath);
7543
7544   // No valid opcode, do not combine.
7545   if (!HasFMAD && !HasFMA)
7546     return SDValue();
7547
7548   // Always prefer FMAD to FMA for precision.
7549   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7550   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7551   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7552
7553   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7554   if (N0.getOpcode() == ISD::FMUL &&
7555       (Aggressive || N0->hasOneUse())) {
7556     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7557                        N0.getOperand(0), N0.getOperand(1),
7558                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7559   }
7560
7561   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7562   // Note: Commutes FSUB operands.
7563   if (N1.getOpcode() == ISD::FMUL &&
7564       (Aggressive || N1->hasOneUse()))
7565     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7566                        DAG.getNode(ISD::FNEG, SL, VT,
7567                                    N1.getOperand(0)),
7568                        N1.getOperand(1), N0);
7569
7570   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7571   if (N0.getOpcode() == ISD::FNEG &&
7572       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7573       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7574     SDValue N00 = N0.getOperand(0).getOperand(0);
7575     SDValue N01 = N0.getOperand(0).getOperand(1);
7576     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7577                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7578                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7579   }
7580
7581   // Look through FP_EXTEND nodes to do more combining.
7582   if (UnsafeFPMath && LookThroughFPExt) {
7583     // fold (fsub (fpext (fmul x, y)), z)
7584     //   -> (fma (fpext x), (fpext y), (fneg z))
7585     if (N0.getOpcode() == ISD::FP_EXTEND) {
7586       SDValue N00 = N0.getOperand(0);
7587       if (N00.getOpcode() == ISD::FMUL)
7588         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7589                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7590                                        N00.getOperand(0)),
7591                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7592                                        N00.getOperand(1)),
7593                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7594     }
7595
7596     // fold (fsub x, (fpext (fmul y, z)))
7597     //   -> (fma (fneg (fpext y)), (fpext z), x)
7598     // Note: Commutes FSUB operands.
7599     if (N1.getOpcode() == ISD::FP_EXTEND) {
7600       SDValue N10 = N1.getOperand(0);
7601       if (N10.getOpcode() == ISD::FMUL)
7602         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7603                            DAG.getNode(ISD::FNEG, SL, VT,
7604                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7605                                                    N10.getOperand(0))),
7606                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7607                                        N10.getOperand(1)),
7608                            N0);
7609     }
7610
7611     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7612     //   -> (fneg (fma (fpext x), (fpext y), z))
7613     // Note: This could be removed with appropriate canonicalization of the
7614     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7615     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7616     // from implementing the canonicalization in visitFSUB.
7617     if (N0.getOpcode() == ISD::FP_EXTEND) {
7618       SDValue N00 = N0.getOperand(0);
7619       if (N00.getOpcode() == ISD::FNEG) {
7620         SDValue N000 = N00.getOperand(0);
7621         if (N000.getOpcode() == ISD::FMUL) {
7622           return DAG.getNode(ISD::FNEG, SL, VT,
7623                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7624                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7625                                                      N000.getOperand(0)),
7626                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7627                                                      N000.getOperand(1)),
7628                                          N1));
7629         }
7630       }
7631     }
7632
7633     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7634     //   -> (fneg (fma (fpext x)), (fpext y), z)
7635     // Note: This could be removed with appropriate canonicalization of the
7636     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7637     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7638     // from implementing the canonicalization in visitFSUB.
7639     if (N0.getOpcode() == ISD::FNEG) {
7640       SDValue N00 = N0.getOperand(0);
7641       if (N00.getOpcode() == ISD::FP_EXTEND) {
7642         SDValue N000 = N00.getOperand(0);
7643         if (N000.getOpcode() == ISD::FMUL) {
7644           return DAG.getNode(ISD::FNEG, SL, VT,
7645                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7646                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7647                                                      N000.getOperand(0)),
7648                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7649                                                      N000.getOperand(1)),
7650                                          N1));
7651         }
7652       }
7653     }
7654
7655   }
7656
7657   // More folding opportunities when target permits.
7658   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7659     // fold (fsub (fma x, y, (fmul u, v)), z)
7660     //   -> (fma x, y (fma u, v, (fneg z)))
7661     if (N0.getOpcode() == PreferredFusedOpcode &&
7662         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7663       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7664                          N0.getOperand(0), N0.getOperand(1),
7665                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7666                                      N0.getOperand(2).getOperand(0),
7667                                      N0.getOperand(2).getOperand(1),
7668                                      DAG.getNode(ISD::FNEG, SL, VT,
7669                                                  N1)));
7670     }
7671
7672     // fold (fsub x, (fma y, z, (fmul u, v)))
7673     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7674     if (N1.getOpcode() == PreferredFusedOpcode &&
7675         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7676       SDValue N20 = N1.getOperand(2).getOperand(0);
7677       SDValue N21 = N1.getOperand(2).getOperand(1);
7678       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7679                          DAG.getNode(ISD::FNEG, SL, VT,
7680                                      N1.getOperand(0)),
7681                          N1.getOperand(1),
7682                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7683                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7684
7685                                      N21, N0));
7686     }
7687
7688     if (UnsafeFPMath && LookThroughFPExt) {
7689       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7690       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7691       if (N0.getOpcode() == PreferredFusedOpcode) {
7692         SDValue N02 = N0.getOperand(2);
7693         if (N02.getOpcode() == ISD::FP_EXTEND) {
7694           SDValue N020 = N02.getOperand(0);
7695           if (N020.getOpcode() == ISD::FMUL)
7696             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7697                                N0.getOperand(0), N0.getOperand(1),
7698                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7699                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7700                                                        N020.getOperand(0)),
7701                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7702                                                        N020.getOperand(1)),
7703                                            DAG.getNode(ISD::FNEG, SL, VT,
7704                                                        N1)));
7705         }
7706       }
7707
7708       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7709       //   -> (fma (fpext x), (fpext y),
7710       //           (fma (fpext u), (fpext v), (fneg z)))
7711       // FIXME: This turns two single-precision and one double-precision
7712       // operation into two double-precision operations, which might not be
7713       // interesting for all targets, especially GPUs.
7714       if (N0.getOpcode() == ISD::FP_EXTEND) {
7715         SDValue N00 = N0.getOperand(0);
7716         if (N00.getOpcode() == PreferredFusedOpcode) {
7717           SDValue N002 = N00.getOperand(2);
7718           if (N002.getOpcode() == ISD::FMUL)
7719             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7720                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7721                                            N00.getOperand(0)),
7722                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7723                                            N00.getOperand(1)),
7724                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7725                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                                        N002.getOperand(0)),
7727                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7728                                                        N002.getOperand(1)),
7729                                            DAG.getNode(ISD::FNEG, SL, VT,
7730                                                        N1)));
7731         }
7732       }
7733
7734       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7735       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7736       if (N1.getOpcode() == PreferredFusedOpcode &&
7737         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7738         SDValue N120 = N1.getOperand(2).getOperand(0);
7739         if (N120.getOpcode() == ISD::FMUL) {
7740           SDValue N1200 = N120.getOperand(0);
7741           SDValue N1201 = N120.getOperand(1);
7742           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7743                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7744                              N1.getOperand(1),
7745                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7746                                          DAG.getNode(ISD::FNEG, SL, VT,
7747                                              DAG.getNode(ISD::FP_EXTEND, SL,
7748                                                          VT, N1200)),
7749                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7750                                                      N1201),
7751                                          N0));
7752         }
7753       }
7754
7755       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7756       //   -> (fma (fneg (fpext y)), (fpext z),
7757       //           (fma (fneg (fpext u)), (fpext v), x))
7758       // FIXME: This turns two single-precision and one double-precision
7759       // operation into two double-precision operations, which might not be
7760       // interesting for all targets, especially GPUs.
7761       if (N1.getOpcode() == ISD::FP_EXTEND &&
7762         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7763         SDValue N100 = N1.getOperand(0).getOperand(0);
7764         SDValue N101 = N1.getOperand(0).getOperand(1);
7765         SDValue N102 = N1.getOperand(0).getOperand(2);
7766         if (N102.getOpcode() == ISD::FMUL) {
7767           SDValue N1020 = N102.getOperand(0);
7768           SDValue N1021 = N102.getOperand(1);
7769           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7770                              DAG.getNode(ISD::FNEG, SL, VT,
7771                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7772                                                      N100)),
7773                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7774                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7775                                          DAG.getNode(ISD::FNEG, SL, VT,
7776                                              DAG.getNode(ISD::FP_EXTEND, SL,
7777                                                          VT, N1020)),
7778                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7779                                                      N1021),
7780                                          N0));
7781         }
7782       }
7783     }
7784   }
7785
7786   return SDValue();
7787 }
7788
7789 SDValue DAGCombiner::visitFADD(SDNode *N) {
7790   SDValue N0 = N->getOperand(0);
7791   SDValue N1 = N->getOperand(1);
7792   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7793   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7794   EVT VT = N->getValueType(0);
7795   SDLoc DL(N);
7796   const TargetOptions &Options = DAG.getTarget().Options;
7797
7798   // fold vector ops
7799   if (VT.isVector())
7800     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7801       return FoldedVOp;
7802
7803   // fold (fadd c1, c2) -> c1 + c2
7804   if (N0CFP && N1CFP)
7805     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7806
7807   // canonicalize constant to RHS
7808   if (N0CFP && !N1CFP)
7809     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7810
7811   // fold (fadd A, (fneg B)) -> (fsub A, B)
7812   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7813       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7814     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7815                        GetNegatedExpression(N1, DAG, LegalOperations));
7816
7817   // fold (fadd (fneg A), B) -> (fsub B, A)
7818   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7819       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7820     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7821                        GetNegatedExpression(N0, DAG, LegalOperations));
7822
7823   // If 'unsafe math' is enabled, fold lots of things.
7824   if (Options.UnsafeFPMath) {
7825     // No FP constant should be created after legalization as Instruction
7826     // Selection pass has a hard time dealing with FP constants.
7827     bool AllowNewConst = (Level < AfterLegalizeDAG);
7828
7829     // fold (fadd A, 0) -> A
7830     if (N1CFP && N1CFP->getValueAPF().isZero())
7831       return N0;
7832
7833     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7834     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7835         isa<ConstantFPSDNode>(N0.getOperand(1)))
7836       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7837                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7838
7839     // If allowed, fold (fadd (fneg x), x) -> 0.0
7840     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7841       return DAG.getConstantFP(0.0, DL, VT);
7842
7843     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7844     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7845       return DAG.getConstantFP(0.0, DL, VT);
7846
7847     // We can fold chains of FADD's of the same value into multiplications.
7848     // This transform is not safe in general because we are reducing the number
7849     // of rounding steps.
7850     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7851       if (N0.getOpcode() == ISD::FMUL) {
7852         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7853         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7854
7855         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7856         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7857           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7858                                        DAG.getConstantFP(1.0, DL, VT));
7859           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7860         }
7861
7862         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7863         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7864             N1.getOperand(0) == N1.getOperand(1) &&
7865             N0.getOperand(0) == N1.getOperand(0)) {
7866           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7867                                        DAG.getConstantFP(2.0, DL, VT));
7868           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7869         }
7870       }
7871
7872       if (N1.getOpcode() == ISD::FMUL) {
7873         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7874         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7875
7876         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7877         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7878           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7879                                        DAG.getConstantFP(1.0, DL, VT));
7880           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7881         }
7882
7883         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7884         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7885             N0.getOperand(0) == N0.getOperand(1) &&
7886             N1.getOperand(0) == N0.getOperand(0)) {
7887           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7888                                        DAG.getConstantFP(2.0, DL, VT));
7889           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7890         }
7891       }
7892
7893       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7894         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7895         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7896         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7897             (N0.getOperand(0) == N1)) {
7898           return DAG.getNode(ISD::FMUL, DL, VT,
7899                              N1, DAG.getConstantFP(3.0, DL, VT));
7900         }
7901       }
7902
7903       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7904         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7905         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7906         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7907             N1.getOperand(0) == N0) {
7908           return DAG.getNode(ISD::FMUL, DL, VT,
7909                              N0, DAG.getConstantFP(3.0, DL, VT));
7910         }
7911       }
7912
7913       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7914       if (AllowNewConst &&
7915           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7916           N0.getOperand(0) == N0.getOperand(1) &&
7917           N1.getOperand(0) == N1.getOperand(1) &&
7918           N0.getOperand(0) == N1.getOperand(0)) {
7919         return DAG.getNode(ISD::FMUL, DL, VT,
7920                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7921       }
7922     }
7923   } // enable-unsafe-fp-math
7924
7925   // FADD -> FMA combines:
7926   SDValue Fused = visitFADDForFMACombine(N);
7927   if (Fused) {
7928     AddToWorklist(Fused.getNode());
7929     return Fused;
7930   }
7931
7932   return SDValue();
7933 }
7934
7935 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7936   SDValue N0 = N->getOperand(0);
7937   SDValue N1 = N->getOperand(1);
7938   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7939   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7940   EVT VT = N->getValueType(0);
7941   SDLoc dl(N);
7942   const TargetOptions &Options = DAG.getTarget().Options;
7943
7944   // fold vector ops
7945   if (VT.isVector())
7946     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7947       return FoldedVOp;
7948
7949   // fold (fsub c1, c2) -> c1-c2
7950   if (N0CFP && N1CFP)
7951     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7952
7953   // fold (fsub A, (fneg B)) -> (fadd A, B)
7954   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7955     return DAG.getNode(ISD::FADD, dl, VT, N0,
7956                        GetNegatedExpression(N1, DAG, LegalOperations));
7957
7958   // If 'unsafe math' is enabled, fold lots of things.
7959   if (Options.UnsafeFPMath) {
7960     // (fsub A, 0) -> A
7961     if (N1CFP && N1CFP->getValueAPF().isZero())
7962       return N0;
7963
7964     // (fsub 0, B) -> -B
7965     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7966       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7967         return GetNegatedExpression(N1, DAG, LegalOperations);
7968       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7969         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7970     }
7971
7972     // (fsub x, x) -> 0.0
7973     if (N0 == N1)
7974       return DAG.getConstantFP(0.0f, dl, VT);
7975
7976     // (fsub x, (fadd x, y)) -> (fneg y)
7977     // (fsub x, (fadd y, x)) -> (fneg y)
7978     if (N1.getOpcode() == ISD::FADD) {
7979       SDValue N10 = N1->getOperand(0);
7980       SDValue N11 = N1->getOperand(1);
7981
7982       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7983         return GetNegatedExpression(N11, DAG, LegalOperations);
7984
7985       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7986         return GetNegatedExpression(N10, DAG, LegalOperations);
7987     }
7988   }
7989
7990   // FSUB -> FMA combines:
7991   SDValue Fused = visitFSUBForFMACombine(N);
7992   if (Fused) {
7993     AddToWorklist(Fused.getNode());
7994     return Fused;
7995   }
7996
7997   return SDValue();
7998 }
7999
8000 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8001   SDValue N0 = N->getOperand(0);
8002   SDValue N1 = N->getOperand(1);
8003   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8004   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8005   EVT VT = N->getValueType(0);
8006   SDLoc DL(N);
8007   const TargetOptions &Options = DAG.getTarget().Options;
8008
8009   // fold vector ops
8010   if (VT.isVector()) {
8011     // This just handles C1 * C2 for vectors. Other vector folds are below.
8012     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8013       return FoldedVOp;
8014   }
8015
8016   // fold (fmul c1, c2) -> c1*c2
8017   if (N0CFP && N1CFP)
8018     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8019
8020   // canonicalize constant to RHS
8021   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8022      !isConstantFPBuildVectorOrConstantFP(N1))
8023     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8024
8025   // fold (fmul A, 1.0) -> A
8026   if (N1CFP && N1CFP->isExactlyValue(1.0))
8027     return N0;
8028
8029   if (Options.UnsafeFPMath) {
8030     // fold (fmul A, 0) -> 0
8031     if (N1CFP && N1CFP->getValueAPF().isZero())
8032       return N1;
8033
8034     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8035     if (N0.getOpcode() == ISD::FMUL) {
8036       // Fold scalars or any vector constants (not just splats).
8037       // This fold is done in general by InstCombine, but extra fmul insts
8038       // may have been generated during lowering.
8039       SDValue N00 = N0.getOperand(0);
8040       SDValue N01 = N0.getOperand(1);
8041       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8042       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8043       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8044       
8045       // Check 1: Make sure that the first operand of the inner multiply is NOT
8046       // a constant. Otherwise, we may induce infinite looping.
8047       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8048         // Check 2: Make sure that the second operand of the inner multiply and
8049         // the second operand of the outer multiply are constants.
8050         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8051             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8052           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8053           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8054         }
8055       }
8056     }
8057
8058     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8059     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8060     // during an early run of DAGCombiner can prevent folding with fmuls
8061     // inserted during lowering.
8062     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8063       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8064       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8065       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8066     }
8067   }
8068
8069   // fold (fmul X, 2.0) -> (fadd X, X)
8070   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8071     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8072
8073   // fold (fmul X, -1.0) -> (fneg X)
8074   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8075     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8076       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8077
8078   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8079   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8080     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8081       // Both can be negated for free, check to see if at least one is cheaper
8082       // negated.
8083       if (LHSNeg == 2 || RHSNeg == 2)
8084         return DAG.getNode(ISD::FMUL, DL, VT,
8085                            GetNegatedExpression(N0, DAG, LegalOperations),
8086                            GetNegatedExpression(N1, DAG, LegalOperations));
8087     }
8088   }
8089
8090   return SDValue();
8091 }
8092
8093 SDValue DAGCombiner::visitFMA(SDNode *N) {
8094   SDValue N0 = N->getOperand(0);
8095   SDValue N1 = N->getOperand(1);
8096   SDValue N2 = N->getOperand(2);
8097   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8098   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8099   EVT VT = N->getValueType(0);
8100   SDLoc dl(N);
8101   const TargetOptions &Options = DAG.getTarget().Options;
8102
8103   // Constant fold FMA.
8104   if (isa<ConstantFPSDNode>(N0) &&
8105       isa<ConstantFPSDNode>(N1) &&
8106       isa<ConstantFPSDNode>(N2)) {
8107     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8108   }
8109
8110   if (Options.UnsafeFPMath) {
8111     if (N0CFP && N0CFP->isZero())
8112       return N2;
8113     if (N1CFP && N1CFP->isZero())
8114       return N2;
8115   }
8116   if (N0CFP && N0CFP->isExactlyValue(1.0))
8117     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8118   if (N1CFP && N1CFP->isExactlyValue(1.0))
8119     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8120
8121   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8122   if (N0CFP && !N1CFP)
8123     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8124
8125   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8126   if (Options.UnsafeFPMath && N1CFP &&
8127       N2.getOpcode() == ISD::FMUL &&
8128       N0 == N2.getOperand(0) &&
8129       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8130     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8131                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8132   }
8133
8134
8135   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8136   if (Options.UnsafeFPMath &&
8137       N0.getOpcode() == ISD::FMUL && N1CFP &&
8138       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8139     return DAG.getNode(ISD::FMA, dl, VT,
8140                        N0.getOperand(0),
8141                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8142                        N2);
8143   }
8144
8145   // (fma x, 1, y) -> (fadd x, y)
8146   // (fma x, -1, y) -> (fadd (fneg x), y)
8147   if (N1CFP) {
8148     if (N1CFP->isExactlyValue(1.0))
8149       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8150
8151     if (N1CFP->isExactlyValue(-1.0) &&
8152         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8153       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8154       AddToWorklist(RHSNeg.getNode());
8155       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8156     }
8157   }
8158
8159   // (fma x, c, x) -> (fmul x, (c+1))
8160   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8161     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8162                        DAG.getNode(ISD::FADD, dl, VT,
8163                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8164
8165   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8166   if (Options.UnsafeFPMath && N1CFP &&
8167       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8168     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8169                        DAG.getNode(ISD::FADD, dl, VT,
8170                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8171
8172
8173   return SDValue();
8174 }
8175
8176 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8177   SDValue N0 = N->getOperand(0);
8178   SDValue N1 = N->getOperand(1);
8179   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8180   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8181   EVT VT = N->getValueType(0);
8182   SDLoc DL(N);
8183   const TargetOptions &Options = DAG.getTarget().Options;
8184
8185   // fold vector ops
8186   if (VT.isVector())
8187     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8188       return FoldedVOp;
8189
8190   // fold (fdiv c1, c2) -> c1/c2
8191   if (N0CFP && N1CFP)
8192     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8193
8194   if (Options.UnsafeFPMath) {
8195     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8196     if (N1CFP) {
8197       // Compute the reciprocal 1.0 / c2.
8198       APFloat N1APF = N1CFP->getValueAPF();
8199       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8200       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8201       // Only do the transform if the reciprocal is a legal fp immediate that
8202       // isn't too nasty (eg NaN, denormal, ...).
8203       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8204           (!LegalOperations ||
8205            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8206            // backend)... we should handle this gracefully after Legalize.
8207            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8208            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8209            TLI.isFPImmLegal(Recip, VT)))
8210         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8211                            DAG.getConstantFP(Recip, DL, VT));
8212     }
8213
8214     // If this FDIV is part of a reciprocal square root, it may be folded
8215     // into a target-specific square root estimate instruction.
8216     if (N1.getOpcode() == ISD::FSQRT) {
8217       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8218         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8219       }
8220     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8221                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8222       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8223         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8224         AddToWorklist(RV.getNode());
8225         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8226       }
8227     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8228                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8229       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8230         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8231         AddToWorklist(RV.getNode());
8232         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8233       }
8234     } else if (N1.getOpcode() == ISD::FMUL) {
8235       // Look through an FMUL. Even though this won't remove the FDIV directly,
8236       // it's still worthwhile to get rid of the FSQRT if possible.
8237       SDValue SqrtOp;
8238       SDValue OtherOp;
8239       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8240         SqrtOp = N1.getOperand(0);
8241         OtherOp = N1.getOperand(1);
8242       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8243         SqrtOp = N1.getOperand(1);
8244         OtherOp = N1.getOperand(0);
8245       }
8246       if (SqrtOp.getNode()) {
8247         // We found a FSQRT, so try to make this fold:
8248         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8249         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8250           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8251           AddToWorklist(RV.getNode());
8252           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8253         }
8254       }
8255     }
8256
8257     // Fold into a reciprocal estimate and multiply instead of a real divide.
8258     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8259       AddToWorklist(RV.getNode());
8260       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8261     }
8262   }
8263
8264   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8265   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8266     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8267       // Both can be negated for free, check to see if at least one is cheaper
8268       // negated.
8269       if (LHSNeg == 2 || RHSNeg == 2)
8270         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8271                            GetNegatedExpression(N0, DAG, LegalOperations),
8272                            GetNegatedExpression(N1, DAG, LegalOperations));
8273     }
8274   }
8275
8276   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8277   // reciprocal.
8278   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8279   // Notice that this is not always beneficial. One reason is different target
8280   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8281   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8282   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8283   if (Options.UnsafeFPMath) {
8284     // Skip if current node is a reciprocal.
8285     if (N0CFP && N0CFP->isExactlyValue(1.0))
8286       return SDValue();
8287
8288     SmallVector<SDNode *, 4> Users;
8289     // Find all FDIV users of the same divisor.
8290     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8291                               UE = N1.getNode()->use_end();
8292          UI != UE; ++UI) {
8293       SDNode *User = UI.getUse().getUser();
8294       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8295         Users.push_back(User);
8296     }
8297
8298     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8299       SDLoc DL(N);
8300       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8301       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8302
8303       // Dividend / Divisor -> Dividend * Reciprocal
8304       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8305         if ((*I)->getOperand(0) != FPOne) {
8306           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8307                                         (*I)->getOperand(0), Reciprocal);
8308           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8309         }
8310       }
8311       return SDValue();
8312     }
8313   }
8314
8315   return SDValue();
8316 }
8317
8318 SDValue DAGCombiner::visitFREM(SDNode *N) {
8319   SDValue N0 = N->getOperand(0);
8320   SDValue N1 = N->getOperand(1);
8321   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8322   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8323   EVT VT = N->getValueType(0);
8324
8325   // fold (frem c1, c2) -> fmod(c1,c2)
8326   if (N0CFP && N1CFP)
8327     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8328
8329   return SDValue();
8330 }
8331
8332 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8333   if (DAG.getTarget().Options.UnsafeFPMath &&
8334       !TLI.isFsqrtCheap()) {
8335     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8336     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8337       EVT VT = RV.getValueType();
8338       SDLoc DL(N);
8339       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8340       AddToWorklist(RV.getNode());
8341
8342       // Unfortunately, RV is now NaN if the input was exactly 0.
8343       // Select out this case and force the answer to 0.
8344       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8345       SDValue ZeroCmp =
8346         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8347                      N->getOperand(0), Zero, ISD::SETEQ);
8348       AddToWorklist(ZeroCmp.getNode());
8349       AddToWorklist(RV.getNode());
8350
8351       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8352                        DL, VT, ZeroCmp, Zero, RV);
8353       return RV;
8354     }
8355   }
8356   return SDValue();
8357 }
8358
8359 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8360   SDValue N0 = N->getOperand(0);
8361   SDValue N1 = N->getOperand(1);
8362   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8363   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8364   EVT VT = N->getValueType(0);
8365
8366   if (N0CFP && N1CFP)  // Constant fold
8367     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8368
8369   if (N1CFP) {
8370     const APFloat& V = N1CFP->getValueAPF();
8371     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8372     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8373     if (!V.isNegative()) {
8374       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8375         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8376     } else {
8377       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8378         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8379                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8380     }
8381   }
8382
8383   // copysign(fabs(x), y) -> copysign(x, y)
8384   // copysign(fneg(x), y) -> copysign(x, y)
8385   // copysign(copysign(x,z), y) -> copysign(x, y)
8386   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8387       N0.getOpcode() == ISD::FCOPYSIGN)
8388     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8389                        N0.getOperand(0), N1);
8390
8391   // copysign(x, abs(y)) -> abs(x)
8392   if (N1.getOpcode() == ISD::FABS)
8393     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8394
8395   // copysign(x, copysign(y,z)) -> copysign(x, z)
8396   if (N1.getOpcode() == ISD::FCOPYSIGN)
8397     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8398                        N0, N1.getOperand(1));
8399
8400   // copysign(x, fp_extend(y)) -> copysign(x, y)
8401   // copysign(x, fp_round(y)) -> copysign(x, y)
8402   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8403     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8404                        N0, N1.getOperand(0));
8405
8406   return SDValue();
8407 }
8408
8409 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8410   SDValue N0 = N->getOperand(0);
8411   EVT VT = N->getValueType(0);
8412   EVT OpVT = N0.getValueType();
8413
8414   // fold (sint_to_fp c1) -> c1fp
8415   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8416       // ...but only if the target supports immediate floating-point values
8417       (!LegalOperations ||
8418        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8419     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8420
8421   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8422   // but UINT_TO_FP is legal on this target, try to convert.
8423   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8424       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8425     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8426     if (DAG.SignBitIsZero(N0))
8427       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8428   }
8429
8430   // The next optimizations are desirable only if SELECT_CC can be lowered.
8431   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8432     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8433     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8434         !VT.isVector() &&
8435         (!LegalOperations ||
8436          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8437       SDLoc DL(N);
8438       SDValue Ops[] =
8439         { N0.getOperand(0), N0.getOperand(1),
8440           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8441           N0.getOperand(2) };
8442       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8443     }
8444
8445     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8446     //      (select_cc x, y, 1.0, 0.0,, cc)
8447     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8448         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8449         (!LegalOperations ||
8450          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8451       SDLoc DL(N);
8452       SDValue Ops[] =
8453         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8454           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8455           N0.getOperand(0).getOperand(2) };
8456       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8457     }
8458   }
8459
8460   return SDValue();
8461 }
8462
8463 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8464   SDValue N0 = N->getOperand(0);
8465   EVT VT = N->getValueType(0);
8466   EVT OpVT = N0.getValueType();
8467
8468   // fold (uint_to_fp c1) -> c1fp
8469   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8470       // ...but only if the target supports immediate floating-point values
8471       (!LegalOperations ||
8472        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8473     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8474
8475   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8476   // but SINT_TO_FP is legal on this target, try to convert.
8477   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8478       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8479     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8480     if (DAG.SignBitIsZero(N0))
8481       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8482   }
8483
8484   // The next optimizations are desirable only if SELECT_CC can be lowered.
8485   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8486     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8487
8488     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8489         (!LegalOperations ||
8490          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8491       SDLoc DL(N);
8492       SDValue Ops[] =
8493         { N0.getOperand(0), N0.getOperand(1),
8494           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8495           N0.getOperand(2) };
8496       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8497     }
8498   }
8499
8500   return SDValue();
8501 }
8502
8503 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8504 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8505   SDValue N0 = N->getOperand(0);
8506   EVT VT = N->getValueType(0);
8507
8508   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8509     return SDValue();
8510
8511   SDValue Src = N0.getOperand(0);
8512   EVT SrcVT = Src.getValueType();
8513   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8514   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8515
8516   // We can safely assume the conversion won't overflow the output range,
8517   // because (for example) (uint8_t)18293.f is undefined behavior.
8518
8519   // Since we can assume the conversion won't overflow, our decision as to
8520   // whether the input will fit in the float should depend on the minimum
8521   // of the input range and output range.
8522
8523   // This means this is also safe for a signed input and unsigned output, since
8524   // a negative input would lead to undefined behavior.
8525   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8526   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8527   unsigned ActualSize = std::min(InputSize, OutputSize);
8528   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8529
8530   // We can only fold away the float conversion if the input range can be
8531   // represented exactly in the float range.
8532   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8533     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8534       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8535                                                        : ISD::ZERO_EXTEND;
8536       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8537     }
8538     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8539       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8540     if (SrcVT == VT)
8541       return Src;
8542     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8543   }
8544   return SDValue();
8545 }
8546
8547 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8548   SDValue N0 = N->getOperand(0);
8549   EVT VT = N->getValueType(0);
8550
8551   // fold (fp_to_sint c1fp) -> c1
8552   if (isConstantFPBuildVectorOrConstantFP(N0))
8553     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8554
8555   return FoldIntToFPToInt(N, DAG);
8556 }
8557
8558 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8559   SDValue N0 = N->getOperand(0);
8560   EVT VT = N->getValueType(0);
8561
8562   // fold (fp_to_uint c1fp) -> c1
8563   if (isConstantFPBuildVectorOrConstantFP(N0))
8564     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8565
8566   return FoldIntToFPToInt(N, DAG);
8567 }
8568
8569 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8570   SDValue N0 = N->getOperand(0);
8571   SDValue N1 = N->getOperand(1);
8572   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8573   EVT VT = N->getValueType(0);
8574
8575   // fold (fp_round c1fp) -> c1fp
8576   if (N0CFP)
8577     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8578
8579   // fold (fp_round (fp_extend x)) -> x
8580   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8581     return N0.getOperand(0);
8582
8583   // fold (fp_round (fp_round x)) -> (fp_round x)
8584   if (N0.getOpcode() == ISD::FP_ROUND) {
8585     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8586     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8587     // If the first fp_round isn't a value preserving truncation, it might
8588     // introduce a tie in the second fp_round, that wouldn't occur in the
8589     // single-step fp_round we want to fold to.
8590     // In other words, double rounding isn't the same as rounding.
8591     // Also, this is a value preserving truncation iff both fp_round's are.
8592     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8593       SDLoc DL(N);
8594       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8595                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8596     }
8597   }
8598
8599   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8600   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8601     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8602                               N0.getOperand(0), N1);
8603     AddToWorklist(Tmp.getNode());
8604     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8605                        Tmp, N0.getOperand(1));
8606   }
8607
8608   return SDValue();
8609 }
8610
8611 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8612   SDValue N0 = N->getOperand(0);
8613   EVT VT = N->getValueType(0);
8614   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8615   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8616
8617   // fold (fp_round_inreg c1fp) -> c1fp
8618   if (N0CFP && isTypeLegal(EVT)) {
8619     SDLoc DL(N);
8620     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8621     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8622   }
8623
8624   return SDValue();
8625 }
8626
8627 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8628   SDValue N0 = N->getOperand(0);
8629   EVT VT = N->getValueType(0);
8630
8631   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8632   if (N->hasOneUse() &&
8633       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8634     return SDValue();
8635
8636   // fold (fp_extend c1fp) -> c1fp
8637   if (isConstantFPBuildVectorOrConstantFP(N0))
8638     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8639
8640   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8641   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8642       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8643     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8644
8645   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8646   // value of X.
8647   if (N0.getOpcode() == ISD::FP_ROUND
8648       && N0.getNode()->getConstantOperandVal(1) == 1) {
8649     SDValue In = N0.getOperand(0);
8650     if (In.getValueType() == VT) return In;
8651     if (VT.bitsLT(In.getValueType()))
8652       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8653                          In, N0.getOperand(1));
8654     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8655   }
8656
8657   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8658   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8659        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8660     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8661     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8662                                      LN0->getChain(),
8663                                      LN0->getBasePtr(), N0.getValueType(),
8664                                      LN0->getMemOperand());
8665     CombineTo(N, ExtLoad);
8666     CombineTo(N0.getNode(),
8667               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8668                           N0.getValueType(), ExtLoad,
8669                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8670               ExtLoad.getValue(1));
8671     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8672   }
8673
8674   return SDValue();
8675 }
8676
8677 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8678   SDValue N0 = N->getOperand(0);
8679   EVT VT = N->getValueType(0);
8680
8681   // fold (fceil c1) -> fceil(c1)
8682   if (isConstantFPBuildVectorOrConstantFP(N0))
8683     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8684
8685   return SDValue();
8686 }
8687
8688 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8689   SDValue N0 = N->getOperand(0);
8690   EVT VT = N->getValueType(0);
8691
8692   // fold (ftrunc c1) -> ftrunc(c1)
8693   if (isConstantFPBuildVectorOrConstantFP(N0))
8694     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8695
8696   return SDValue();
8697 }
8698
8699 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8700   SDValue N0 = N->getOperand(0);
8701   EVT VT = N->getValueType(0);
8702
8703   // fold (ffloor c1) -> ffloor(c1)
8704   if (isConstantFPBuildVectorOrConstantFP(N0))
8705     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8706
8707   return SDValue();
8708 }
8709
8710 // FIXME: FNEG and FABS have a lot in common; refactor.
8711 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8712   SDValue N0 = N->getOperand(0);
8713   EVT VT = N->getValueType(0);
8714
8715   // Constant fold FNEG.
8716   if (isConstantFPBuildVectorOrConstantFP(N0))
8717     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8718
8719   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8720                          &DAG.getTarget().Options))
8721     return GetNegatedExpression(N0, DAG, LegalOperations);
8722
8723   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8724   // constant pool values.
8725   if (!TLI.isFNegFree(VT) &&
8726       N0.getOpcode() == ISD::BITCAST &&
8727       N0.getNode()->hasOneUse()) {
8728     SDValue Int = N0.getOperand(0);
8729     EVT IntVT = Int.getValueType();
8730     if (IntVT.isInteger() && !IntVT.isVector()) {
8731       APInt SignMask;
8732       if (N0.getValueType().isVector()) {
8733         // For a vector, get a mask such as 0x80... per scalar element
8734         // and splat it.
8735         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8736         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8737       } else {
8738         // For a scalar, just generate 0x80...
8739         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8740       }
8741       SDLoc DL0(N0);
8742       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8743                         DAG.getConstant(SignMask, DL0, IntVT));
8744       AddToWorklist(Int.getNode());
8745       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8746     }
8747   }
8748
8749   // (fneg (fmul c, x)) -> (fmul -c, x)
8750   if (N0.getOpcode() == ISD::FMUL) {
8751     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8752     if (CFP1) {
8753       APFloat CVal = CFP1->getValueAPF();
8754       CVal.changeSign();
8755       if (Level >= AfterLegalizeDAG &&
8756           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8757            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8758         return DAG.getNode(
8759             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8760             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8761     }
8762   }
8763
8764   return SDValue();
8765 }
8766
8767 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8768   SDValue N0 = N->getOperand(0);
8769   SDValue N1 = N->getOperand(1);
8770   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8771   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8772
8773   if (N0CFP && N1CFP) {
8774     const APFloat &C0 = N0CFP->getValueAPF();
8775     const APFloat &C1 = N1CFP->getValueAPF();
8776     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8777   }
8778
8779   if (N0CFP) {
8780     EVT VT = N->getValueType(0);
8781     // Canonicalize to constant on RHS.
8782     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8783   }
8784
8785   return SDValue();
8786 }
8787
8788 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8789   SDValue N0 = N->getOperand(0);
8790   SDValue N1 = N->getOperand(1);
8791   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8792   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8793
8794   if (N0CFP && N1CFP) {
8795     const APFloat &C0 = N0CFP->getValueAPF();
8796     const APFloat &C1 = N1CFP->getValueAPF();
8797     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8798   }
8799
8800   if (N0CFP) {
8801     EVT VT = N->getValueType(0);
8802     // Canonicalize to constant on RHS.
8803     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8804   }
8805
8806   return SDValue();
8807 }
8808
8809 SDValue DAGCombiner::visitFABS(SDNode *N) {
8810   SDValue N0 = N->getOperand(0);
8811   EVT VT = N->getValueType(0);
8812
8813   // fold (fabs c1) -> fabs(c1)
8814   if (isConstantFPBuildVectorOrConstantFP(N0))
8815     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8816
8817   // fold (fabs (fabs x)) -> (fabs x)
8818   if (N0.getOpcode() == ISD::FABS)
8819     return N->getOperand(0);
8820
8821   // fold (fabs (fneg x)) -> (fabs x)
8822   // fold (fabs (fcopysign x, y)) -> (fabs x)
8823   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8824     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8825
8826   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8827   // constant pool values.
8828   if (!TLI.isFAbsFree(VT) &&
8829       N0.getOpcode() == ISD::BITCAST &&
8830       N0.getNode()->hasOneUse()) {
8831     SDValue Int = N0.getOperand(0);
8832     EVT IntVT = Int.getValueType();
8833     if (IntVT.isInteger() && !IntVT.isVector()) {
8834       APInt SignMask;
8835       if (N0.getValueType().isVector()) {
8836         // For a vector, get a mask such as 0x7f... per scalar element
8837         // and splat it.
8838         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8839         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8840       } else {
8841         // For a scalar, just generate 0x7f...
8842         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8843       }
8844       SDLoc DL(N0);
8845       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8846                         DAG.getConstant(SignMask, DL, IntVT));
8847       AddToWorklist(Int.getNode());
8848       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8849     }
8850   }
8851
8852   return SDValue();
8853 }
8854
8855 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8856   SDValue Chain = N->getOperand(0);
8857   SDValue N1 = N->getOperand(1);
8858   SDValue N2 = N->getOperand(2);
8859
8860   // If N is a constant we could fold this into a fallthrough or unconditional
8861   // branch. However that doesn't happen very often in normal code, because
8862   // Instcombine/SimplifyCFG should have handled the available opportunities.
8863   // If we did this folding here, it would be necessary to update the
8864   // MachineBasicBlock CFG, which is awkward.
8865
8866   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8867   // on the target.
8868   if (N1.getOpcode() == ISD::SETCC &&
8869       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8870                                    N1.getOperand(0).getValueType())) {
8871     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8872                        Chain, N1.getOperand(2),
8873                        N1.getOperand(0), N1.getOperand(1), N2);
8874   }
8875
8876   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8877       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8878        (N1.getOperand(0).hasOneUse() &&
8879         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8880     SDNode *Trunc = nullptr;
8881     if (N1.getOpcode() == ISD::TRUNCATE) {
8882       // Look pass the truncate.
8883       Trunc = N1.getNode();
8884       N1 = N1.getOperand(0);
8885     }
8886
8887     // Match this pattern so that we can generate simpler code:
8888     //
8889     //   %a = ...
8890     //   %b = and i32 %a, 2
8891     //   %c = srl i32 %b, 1
8892     //   brcond i32 %c ...
8893     //
8894     // into
8895     //
8896     //   %a = ...
8897     //   %b = and i32 %a, 2
8898     //   %c = setcc eq %b, 0
8899     //   brcond %c ...
8900     //
8901     // This applies only when the AND constant value has one bit set and the
8902     // SRL constant is equal to the log2 of the AND constant. The back-end is
8903     // smart enough to convert the result into a TEST/JMP sequence.
8904     SDValue Op0 = N1.getOperand(0);
8905     SDValue Op1 = N1.getOperand(1);
8906
8907     if (Op0.getOpcode() == ISD::AND &&
8908         Op1.getOpcode() == ISD::Constant) {
8909       SDValue AndOp1 = Op0.getOperand(1);
8910
8911       if (AndOp1.getOpcode() == ISD::Constant) {
8912         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8913
8914         if (AndConst.isPowerOf2() &&
8915             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8916           SDLoc DL(N);
8917           SDValue SetCC =
8918             DAG.getSetCC(DL,
8919                          getSetCCResultType(Op0.getValueType()),
8920                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8921                          ISD::SETNE);
8922
8923           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8924                                           MVT::Other, Chain, SetCC, N2);
8925           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8926           // will convert it back to (X & C1) >> C2.
8927           CombineTo(N, NewBRCond, false);
8928           // Truncate is dead.
8929           if (Trunc)
8930             deleteAndRecombine(Trunc);
8931           // Replace the uses of SRL with SETCC
8932           WorklistRemover DeadNodes(*this);
8933           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8934           deleteAndRecombine(N1.getNode());
8935           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8936         }
8937       }
8938     }
8939
8940     if (Trunc)
8941       // Restore N1 if the above transformation doesn't match.
8942       N1 = N->getOperand(1);
8943   }
8944
8945   // Transform br(xor(x, y)) -> br(x != y)
8946   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8947   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8948     SDNode *TheXor = N1.getNode();
8949     SDValue Op0 = TheXor->getOperand(0);
8950     SDValue Op1 = TheXor->getOperand(1);
8951     if (Op0.getOpcode() == Op1.getOpcode()) {
8952       // Avoid missing important xor optimizations.
8953       SDValue Tmp = visitXOR(TheXor);
8954       if (Tmp.getNode()) {
8955         if (Tmp.getNode() != TheXor) {
8956           DEBUG(dbgs() << "\nReplacing.8 ";
8957                 TheXor->dump(&DAG);
8958                 dbgs() << "\nWith: ";
8959                 Tmp.getNode()->dump(&DAG);
8960                 dbgs() << '\n');
8961           WorklistRemover DeadNodes(*this);
8962           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8963           deleteAndRecombine(TheXor);
8964           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8965                              MVT::Other, Chain, Tmp, N2);
8966         }
8967
8968         // visitXOR has changed XOR's operands or replaced the XOR completely,
8969         // bail out.
8970         return SDValue(N, 0);
8971       }
8972     }
8973
8974     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8975       bool Equal = false;
8976       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8977         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8978             Op0.getOpcode() == ISD::XOR) {
8979           TheXor = Op0.getNode();
8980           Equal = true;
8981         }
8982
8983       EVT SetCCVT = N1.getValueType();
8984       if (LegalTypes)
8985         SetCCVT = getSetCCResultType(SetCCVT);
8986       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8987                                    SetCCVT,
8988                                    Op0, Op1,
8989                                    Equal ? ISD::SETEQ : ISD::SETNE);
8990       // Replace the uses of XOR with SETCC
8991       WorklistRemover DeadNodes(*this);
8992       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8993       deleteAndRecombine(N1.getNode());
8994       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8995                          MVT::Other, Chain, SetCC, N2);
8996     }
8997   }
8998
8999   return SDValue();
9000 }
9001
9002 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9003 //
9004 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9005   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9006   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9007
9008   // If N is a constant we could fold this into a fallthrough or unconditional
9009   // branch. However that doesn't happen very often in normal code, because
9010   // Instcombine/SimplifyCFG should have handled the available opportunities.
9011   // If we did this folding here, it would be necessary to update the
9012   // MachineBasicBlock CFG, which is awkward.
9013
9014   // Use SimplifySetCC to simplify SETCC's.
9015   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9016                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9017                                false);
9018   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9019
9020   // fold to a simpler setcc
9021   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9022     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9023                        N->getOperand(0), Simp.getOperand(2),
9024                        Simp.getOperand(0), Simp.getOperand(1),
9025                        N->getOperand(4));
9026
9027   return SDValue();
9028 }
9029
9030 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9031 /// and that N may be folded in the load / store addressing mode.
9032 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9033                                     SelectionDAG &DAG,
9034                                     const TargetLowering &TLI) {
9035   EVT VT;
9036   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9037     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9038       return false;
9039     VT = LD->getMemoryVT();
9040   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9041     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9042       return false;
9043     VT = ST->getMemoryVT();
9044   } else
9045     return false;
9046
9047   TargetLowering::AddrMode AM;
9048   if (N->getOpcode() == ISD::ADD) {
9049     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9050     if (Offset)
9051       // [reg +/- imm]
9052       AM.BaseOffs = Offset->getSExtValue();
9053     else
9054       // [reg +/- reg]
9055       AM.Scale = 1;
9056   } else if (N->getOpcode() == ISD::SUB) {
9057     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9058     if (Offset)
9059       // [reg +/- imm]
9060       AM.BaseOffs = -Offset->getSExtValue();
9061     else
9062       // [reg +/- reg]
9063       AM.Scale = 1;
9064   } else
9065     return false;
9066
9067   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9068 }
9069
9070 /// Try turning a load/store into a pre-indexed load/store when the base
9071 /// pointer is an add or subtract and it has other uses besides the load/store.
9072 /// After the transformation, the new indexed load/store has effectively folded
9073 /// the add/subtract in and all of its other uses are redirected to the
9074 /// new load/store.
9075 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9076   if (Level < AfterLegalizeDAG)
9077     return false;
9078
9079   bool isLoad = true;
9080   SDValue Ptr;
9081   EVT VT;
9082   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9083     if (LD->isIndexed())
9084       return false;
9085     VT = LD->getMemoryVT();
9086     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9087         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9088       return false;
9089     Ptr = LD->getBasePtr();
9090   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9091     if (ST->isIndexed())
9092       return false;
9093     VT = ST->getMemoryVT();
9094     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9095         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9096       return false;
9097     Ptr = ST->getBasePtr();
9098     isLoad = false;
9099   } else {
9100     return false;
9101   }
9102
9103   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9104   // out.  There is no reason to make this a preinc/predec.
9105   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9106       Ptr.getNode()->hasOneUse())
9107     return false;
9108
9109   // Ask the target to do addressing mode selection.
9110   SDValue BasePtr;
9111   SDValue Offset;
9112   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9113   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9114     return false;
9115
9116   // Backends without true r+i pre-indexed forms may need to pass a
9117   // constant base with a variable offset so that constant coercion
9118   // will work with the patterns in canonical form.
9119   bool Swapped = false;
9120   if (isa<ConstantSDNode>(BasePtr)) {
9121     std::swap(BasePtr, Offset);
9122     Swapped = true;
9123   }
9124
9125   // Don't create a indexed load / store with zero offset.
9126   if (isa<ConstantSDNode>(Offset) &&
9127       cast<ConstantSDNode>(Offset)->isNullValue())
9128     return false;
9129
9130   // Try turning it into a pre-indexed load / store except when:
9131   // 1) The new base ptr is a frame index.
9132   // 2) If N is a store and the new base ptr is either the same as or is a
9133   //    predecessor of the value being stored.
9134   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9135   //    that would create a cycle.
9136   // 4) All uses are load / store ops that use it as old base ptr.
9137
9138   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9139   // (plus the implicit offset) to a register to preinc anyway.
9140   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9141     return false;
9142
9143   // Check #2.
9144   if (!isLoad) {
9145     SDValue Val = cast<StoreSDNode>(N)->getValue();
9146     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9147       return false;
9148   }
9149
9150   // If the offset is a constant, there may be other adds of constants that
9151   // can be folded with this one. We should do this to avoid having to keep
9152   // a copy of the original base pointer.
9153   SmallVector<SDNode *, 16> OtherUses;
9154   if (isa<ConstantSDNode>(Offset))
9155     for (SDNode *Use : BasePtr.getNode()->uses()) {
9156       if (Use == Ptr.getNode())
9157         continue;
9158
9159       if (Use->isPredecessorOf(N))
9160         continue;
9161
9162       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9163         OtherUses.clear();
9164         break;
9165       }
9166
9167       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9168       if (Op1.getNode() == BasePtr.getNode())
9169         std::swap(Op0, Op1);
9170       assert(Op0.getNode() == BasePtr.getNode() &&
9171              "Use of ADD/SUB but not an operand");
9172
9173       if (!isa<ConstantSDNode>(Op1)) {
9174         OtherUses.clear();
9175         break;
9176       }
9177
9178       // FIXME: In some cases, we can be smarter about this.
9179       if (Op1.getValueType() != Offset.getValueType()) {
9180         OtherUses.clear();
9181         break;
9182       }
9183
9184       OtherUses.push_back(Use);
9185     }
9186
9187   if (Swapped)
9188     std::swap(BasePtr, Offset);
9189
9190   // Now check for #3 and #4.
9191   bool RealUse = false;
9192
9193   // Caches for hasPredecessorHelper
9194   SmallPtrSet<const SDNode *, 32> Visited;
9195   SmallVector<const SDNode *, 16> Worklist;
9196
9197   for (SDNode *Use : Ptr.getNode()->uses()) {
9198     if (Use == N)
9199       continue;
9200     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9201       return false;
9202
9203     // If Ptr may be folded in addressing mode of other use, then it's
9204     // not profitable to do this transformation.
9205     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9206       RealUse = true;
9207   }
9208
9209   if (!RealUse)
9210     return false;
9211
9212   SDValue Result;
9213   if (isLoad)
9214     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9215                                 BasePtr, Offset, AM);
9216   else
9217     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9218                                  BasePtr, Offset, AM);
9219   ++PreIndexedNodes;
9220   ++NodesCombined;
9221   DEBUG(dbgs() << "\nReplacing.4 ";
9222         N->dump(&DAG);
9223         dbgs() << "\nWith: ";
9224         Result.getNode()->dump(&DAG);
9225         dbgs() << '\n');
9226   WorklistRemover DeadNodes(*this);
9227   if (isLoad) {
9228     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9229     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9230   } else {
9231     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9232   }
9233
9234   // Finally, since the node is now dead, remove it from the graph.
9235   deleteAndRecombine(N);
9236
9237   if (Swapped)
9238     std::swap(BasePtr, Offset);
9239
9240   // Replace other uses of BasePtr that can be updated to use Ptr
9241   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9242     unsigned OffsetIdx = 1;
9243     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9244       OffsetIdx = 0;
9245     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9246            BasePtr.getNode() && "Expected BasePtr operand");
9247
9248     // We need to replace ptr0 in the following expression:
9249     //   x0 * offset0 + y0 * ptr0 = t0
9250     // knowing that
9251     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9252     //
9253     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9254     // indexed load/store and the expresion that needs to be re-written.
9255     //
9256     // Therefore, we have:
9257     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9258
9259     ConstantSDNode *CN =
9260       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9261     int X0, X1, Y0, Y1;
9262     APInt Offset0 = CN->getAPIntValue();
9263     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9264
9265     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9266     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9267     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9268     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9269
9270     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9271
9272     APInt CNV = Offset0;
9273     if (X0 < 0) CNV = -CNV;
9274     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9275     else CNV = CNV - Offset1;
9276
9277     SDLoc DL(OtherUses[i]);
9278
9279     // We can now generate the new expression.
9280     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9281     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9282
9283     SDValue NewUse = DAG.getNode(Opcode,
9284                                  DL,
9285                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9286     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9287     deleteAndRecombine(OtherUses[i]);
9288   }
9289
9290   // Replace the uses of Ptr with uses of the updated base value.
9291   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9292   deleteAndRecombine(Ptr.getNode());
9293
9294   return true;
9295 }
9296
9297 /// Try to combine a load/store with a add/sub of the base pointer node into a
9298 /// post-indexed load/store. The transformation folded the add/subtract into the
9299 /// new indexed load/store effectively and all of its uses are redirected to the
9300 /// new load/store.
9301 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9302   if (Level < AfterLegalizeDAG)
9303     return false;
9304
9305   bool isLoad = true;
9306   SDValue Ptr;
9307   EVT VT;
9308   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9309     if (LD->isIndexed())
9310       return false;
9311     VT = LD->getMemoryVT();
9312     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9313         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9314       return false;
9315     Ptr = LD->getBasePtr();
9316   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9317     if (ST->isIndexed())
9318       return false;
9319     VT = ST->getMemoryVT();
9320     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9321         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9322       return false;
9323     Ptr = ST->getBasePtr();
9324     isLoad = false;
9325   } else {
9326     return false;
9327   }
9328
9329   if (Ptr.getNode()->hasOneUse())
9330     return false;
9331
9332   for (SDNode *Op : Ptr.getNode()->uses()) {
9333     if (Op == N ||
9334         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9335       continue;
9336
9337     SDValue BasePtr;
9338     SDValue Offset;
9339     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9340     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9341       // Don't create a indexed load / store with zero offset.
9342       if (isa<ConstantSDNode>(Offset) &&
9343           cast<ConstantSDNode>(Offset)->isNullValue())
9344         continue;
9345
9346       // Try turning it into a post-indexed load / store except when
9347       // 1) All uses are load / store ops that use it as base ptr (and
9348       //    it may be folded as addressing mmode).
9349       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9350       //    nor a successor of N. Otherwise, if Op is folded that would
9351       //    create a cycle.
9352
9353       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9354         continue;
9355
9356       // Check for #1.
9357       bool TryNext = false;
9358       for (SDNode *Use : BasePtr.getNode()->uses()) {
9359         if (Use == Ptr.getNode())
9360           continue;
9361
9362         // If all the uses are load / store addresses, then don't do the
9363         // transformation.
9364         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9365           bool RealUse = false;
9366           for (SDNode *UseUse : Use->uses()) {
9367             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9368               RealUse = true;
9369           }
9370
9371           if (!RealUse) {
9372             TryNext = true;
9373             break;
9374           }
9375         }
9376       }
9377
9378       if (TryNext)
9379         continue;
9380
9381       // Check for #2
9382       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9383         SDValue Result = isLoad
9384           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9385                                BasePtr, Offset, AM)
9386           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9387                                 BasePtr, Offset, AM);
9388         ++PostIndexedNodes;
9389         ++NodesCombined;
9390         DEBUG(dbgs() << "\nReplacing.5 ";
9391               N->dump(&DAG);
9392               dbgs() << "\nWith: ";
9393               Result.getNode()->dump(&DAG);
9394               dbgs() << '\n');
9395         WorklistRemover DeadNodes(*this);
9396         if (isLoad) {
9397           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9398           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9399         } else {
9400           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9401         }
9402
9403         // Finally, since the node is now dead, remove it from the graph.
9404         deleteAndRecombine(N);
9405
9406         // Replace the uses of Use with uses of the updated base value.
9407         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9408                                       Result.getValue(isLoad ? 1 : 0));
9409         deleteAndRecombine(Op);
9410         return true;
9411       }
9412     }
9413   }
9414
9415   return false;
9416 }
9417
9418 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9419 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9420   ISD::MemIndexedMode AM = LD->getAddressingMode();
9421   assert(AM != ISD::UNINDEXED);
9422   SDValue BP = LD->getOperand(1);
9423   SDValue Inc = LD->getOperand(2);
9424
9425   // Some backends use TargetConstants for load offsets, but don't expect
9426   // TargetConstants in general ADD nodes. We can convert these constants into
9427   // regular Constants (if the constant is not opaque).
9428   assert((Inc.getOpcode() != ISD::TargetConstant ||
9429           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9430          "Cannot split out indexing using opaque target constants");
9431   if (Inc.getOpcode() == ISD::TargetConstant) {
9432     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9433     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9434                           ConstInc->getValueType(0));
9435   }
9436
9437   unsigned Opc =
9438       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9439   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9440 }
9441
9442 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9443   LoadSDNode *LD  = cast<LoadSDNode>(N);
9444   SDValue Chain = LD->getChain();
9445   SDValue Ptr   = LD->getBasePtr();
9446
9447   // If load is not volatile and there are no uses of the loaded value (and
9448   // the updated indexed value in case of indexed loads), change uses of the
9449   // chain value into uses of the chain input (i.e. delete the dead load).
9450   if (!LD->isVolatile()) {
9451     if (N->getValueType(1) == MVT::Other) {
9452       // Unindexed loads.
9453       if (!N->hasAnyUseOfValue(0)) {
9454         // It's not safe to use the two value CombineTo variant here. e.g.
9455         // v1, chain2 = load chain1, loc
9456         // v2, chain3 = load chain2, loc
9457         // v3         = add v2, c
9458         // Now we replace use of chain2 with chain1.  This makes the second load
9459         // isomorphic to the one we are deleting, and thus makes this load live.
9460         DEBUG(dbgs() << "\nReplacing.6 ";
9461               N->dump(&DAG);
9462               dbgs() << "\nWith chain: ";
9463               Chain.getNode()->dump(&DAG);
9464               dbgs() << "\n");
9465         WorklistRemover DeadNodes(*this);
9466         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9467
9468         if (N->use_empty())
9469           deleteAndRecombine(N);
9470
9471         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9472       }
9473     } else {
9474       // Indexed loads.
9475       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9476
9477       // If this load has an opaque TargetConstant offset, then we cannot split
9478       // the indexing into an add/sub directly (that TargetConstant may not be
9479       // valid for a different type of node, and we cannot convert an opaque
9480       // target constant into a regular constant).
9481       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9482                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9483
9484       if (!N->hasAnyUseOfValue(0) &&
9485           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9486         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9487         SDValue Index;
9488         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9489           Index = SplitIndexingFromLoad(LD);
9490           // Try to fold the base pointer arithmetic into subsequent loads and
9491           // stores.
9492           AddUsersToWorklist(N);
9493         } else
9494           Index = DAG.getUNDEF(N->getValueType(1));
9495         DEBUG(dbgs() << "\nReplacing.7 ";
9496               N->dump(&DAG);
9497               dbgs() << "\nWith: ";
9498               Undef.getNode()->dump(&DAG);
9499               dbgs() << " and 2 other values\n");
9500         WorklistRemover DeadNodes(*this);
9501         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9502         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9503         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9504         deleteAndRecombine(N);
9505         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9506       }
9507     }
9508   }
9509
9510   // If this load is directly stored, replace the load value with the stored
9511   // value.
9512   // TODO: Handle store large -> read small portion.
9513   // TODO: Handle TRUNCSTORE/LOADEXT
9514   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9515     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9516       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9517       if (PrevST->getBasePtr() == Ptr &&
9518           PrevST->getValue().getValueType() == N->getValueType(0))
9519       return CombineTo(N, Chain.getOperand(1), Chain);
9520     }
9521   }
9522
9523   // Try to infer better alignment information than the load already has.
9524   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9525     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9526       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9527         SDValue NewLoad =
9528                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9529                               LD->getValueType(0),
9530                               Chain, Ptr, LD->getPointerInfo(),
9531                               LD->getMemoryVT(),
9532                               LD->isVolatile(), LD->isNonTemporal(),
9533                               LD->isInvariant(), Align, LD->getAAInfo());
9534         if (NewLoad.getNode() != N)
9535           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9536       }
9537     }
9538   }
9539
9540   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9541                                                   : DAG.getSubtarget().useAA();
9542 #ifndef NDEBUG
9543   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9544       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9545     UseAA = false;
9546 #endif
9547   if (UseAA && LD->isUnindexed()) {
9548     // Walk up chain skipping non-aliasing memory nodes.
9549     SDValue BetterChain = FindBetterChain(N, Chain);
9550
9551     // If there is a better chain.
9552     if (Chain != BetterChain) {
9553       SDValue ReplLoad;
9554
9555       // Replace the chain to void dependency.
9556       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9557         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9558                                BetterChain, Ptr, LD->getMemOperand());
9559       } else {
9560         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9561                                   LD->getValueType(0),
9562                                   BetterChain, Ptr, LD->getMemoryVT(),
9563                                   LD->getMemOperand());
9564       }
9565
9566       // Create token factor to keep old chain connected.
9567       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9568                                   MVT::Other, Chain, ReplLoad.getValue(1));
9569
9570       // Make sure the new and old chains are cleaned up.
9571       AddToWorklist(Token.getNode());
9572
9573       // Replace uses with load result and token factor. Don't add users
9574       // to work list.
9575       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9576     }
9577   }
9578
9579   // Try transforming N to an indexed load.
9580   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9581     return SDValue(N, 0);
9582
9583   // Try to slice up N to more direct loads if the slices are mapped to
9584   // different register banks or pairing can take place.
9585   if (SliceUpLoad(N))
9586     return SDValue(N, 0);
9587
9588   return SDValue();
9589 }
9590
9591 namespace {
9592 /// \brief Helper structure used to slice a load in smaller loads.
9593 /// Basically a slice is obtained from the following sequence:
9594 /// Origin = load Ty1, Base
9595 /// Shift = srl Ty1 Origin, CstTy Amount
9596 /// Inst = trunc Shift to Ty2
9597 ///
9598 /// Then, it will be rewriten into:
9599 /// Slice = load SliceTy, Base + SliceOffset
9600 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9601 ///
9602 /// SliceTy is deduced from the number of bits that are actually used to
9603 /// build Inst.
9604 struct LoadedSlice {
9605   /// \brief Helper structure used to compute the cost of a slice.
9606   struct Cost {
9607     /// Are we optimizing for code size.
9608     bool ForCodeSize;
9609     /// Various cost.
9610     unsigned Loads;
9611     unsigned Truncates;
9612     unsigned CrossRegisterBanksCopies;
9613     unsigned ZExts;
9614     unsigned Shift;
9615
9616     Cost(bool ForCodeSize = false)
9617         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9618           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9619
9620     /// \brief Get the cost of one isolated slice.
9621     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9622         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9623           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9624       EVT TruncType = LS.Inst->getValueType(0);
9625       EVT LoadedType = LS.getLoadedType();
9626       if (TruncType != LoadedType &&
9627           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9628         ZExts = 1;
9629     }
9630
9631     /// \brief Account for slicing gain in the current cost.
9632     /// Slicing provide a few gains like removing a shift or a
9633     /// truncate. This method allows to grow the cost of the original
9634     /// load with the gain from this slice.
9635     void addSliceGain(const LoadedSlice &LS) {
9636       // Each slice saves a truncate.
9637       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9638       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9639                               LS.Inst->getOperand(0).getValueType()))
9640         ++Truncates;
9641       // If there is a shift amount, this slice gets rid of it.
9642       if (LS.Shift)
9643         ++Shift;
9644       // If this slice can merge a cross register bank copy, account for it.
9645       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9646         ++CrossRegisterBanksCopies;
9647     }
9648
9649     Cost &operator+=(const Cost &RHS) {
9650       Loads += RHS.Loads;
9651       Truncates += RHS.Truncates;
9652       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9653       ZExts += RHS.ZExts;
9654       Shift += RHS.Shift;
9655       return *this;
9656     }
9657
9658     bool operator==(const Cost &RHS) const {
9659       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9660              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9661              ZExts == RHS.ZExts && Shift == RHS.Shift;
9662     }
9663
9664     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9665
9666     bool operator<(const Cost &RHS) const {
9667       // Assume cross register banks copies are as expensive as loads.
9668       // FIXME: Do we want some more target hooks?
9669       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9670       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9671       // Unless we are optimizing for code size, consider the
9672       // expensive operation first.
9673       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9674         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9675       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9676              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9677     }
9678
9679     bool operator>(const Cost &RHS) const { return RHS < *this; }
9680
9681     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9682
9683     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9684   };
9685   // The last instruction that represent the slice. This should be a
9686   // truncate instruction.
9687   SDNode *Inst;
9688   // The original load instruction.
9689   LoadSDNode *Origin;
9690   // The right shift amount in bits from the original load.
9691   unsigned Shift;
9692   // The DAG from which Origin came from.
9693   // This is used to get some contextual information about legal types, etc.
9694   SelectionDAG *DAG;
9695
9696   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9697               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9698       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9699
9700   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9701   /// \return Result is \p BitWidth and has used bits set to 1 and
9702   ///         not used bits set to 0.
9703   APInt getUsedBits() const {
9704     // Reproduce the trunc(lshr) sequence:
9705     // - Start from the truncated value.
9706     // - Zero extend to the desired bit width.
9707     // - Shift left.
9708     assert(Origin && "No original load to compare against.");
9709     unsigned BitWidth = Origin->getValueSizeInBits(0);
9710     assert(Inst && "This slice is not bound to an instruction");
9711     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9712            "Extracted slice is bigger than the whole type!");
9713     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9714     UsedBits.setAllBits();
9715     UsedBits = UsedBits.zext(BitWidth);
9716     UsedBits <<= Shift;
9717     return UsedBits;
9718   }
9719
9720   /// \brief Get the size of the slice to be loaded in bytes.
9721   unsigned getLoadedSize() const {
9722     unsigned SliceSize = getUsedBits().countPopulation();
9723     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9724     return SliceSize / 8;
9725   }
9726
9727   /// \brief Get the type that will be loaded for this slice.
9728   /// Note: This may not be the final type for the slice.
9729   EVT getLoadedType() const {
9730     assert(DAG && "Missing context");
9731     LLVMContext &Ctxt = *DAG->getContext();
9732     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9733   }
9734
9735   /// \brief Get the alignment of the load used for this slice.
9736   unsigned getAlignment() const {
9737     unsigned Alignment = Origin->getAlignment();
9738     unsigned Offset = getOffsetFromBase();
9739     if (Offset != 0)
9740       Alignment = MinAlign(Alignment, Alignment + Offset);
9741     return Alignment;
9742   }
9743
9744   /// \brief Check if this slice can be rewritten with legal operations.
9745   bool isLegal() const {
9746     // An invalid slice is not legal.
9747     if (!Origin || !Inst || !DAG)
9748       return false;
9749
9750     // Offsets are for indexed load only, we do not handle that.
9751     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9752       return false;
9753
9754     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9755
9756     // Check that the type is legal.
9757     EVT SliceType = getLoadedType();
9758     if (!TLI.isTypeLegal(SliceType))
9759       return false;
9760
9761     // Check that the load is legal for this type.
9762     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9763       return false;
9764
9765     // Check that the offset can be computed.
9766     // 1. Check its type.
9767     EVT PtrType = Origin->getBasePtr().getValueType();
9768     if (PtrType == MVT::Untyped || PtrType.isExtended())
9769       return false;
9770
9771     // 2. Check that it fits in the immediate.
9772     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9773       return false;
9774
9775     // 3. Check that the computation is legal.
9776     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9777       return false;
9778
9779     // Check that the zext is legal if it needs one.
9780     EVT TruncateType = Inst->getValueType(0);
9781     if (TruncateType != SliceType &&
9782         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9783       return false;
9784
9785     return true;
9786   }
9787
9788   /// \brief Get the offset in bytes of this slice in the original chunk of
9789   /// bits.
9790   /// \pre DAG != nullptr.
9791   uint64_t getOffsetFromBase() const {
9792     assert(DAG && "Missing context.");
9793     bool IsBigEndian =
9794         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9795     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9796     uint64_t Offset = Shift / 8;
9797     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9798     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9799            "The size of the original loaded type is not a multiple of a"
9800            " byte.");
9801     // If Offset is bigger than TySizeInBytes, it means we are loading all
9802     // zeros. This should have been optimized before in the process.
9803     assert(TySizeInBytes > Offset &&
9804            "Invalid shift amount for given loaded size");
9805     if (IsBigEndian)
9806       Offset = TySizeInBytes - Offset - getLoadedSize();
9807     return Offset;
9808   }
9809
9810   /// \brief Generate the sequence of instructions to load the slice
9811   /// represented by this object and redirect the uses of this slice to
9812   /// this new sequence of instructions.
9813   /// \pre this->Inst && this->Origin are valid Instructions and this
9814   /// object passed the legal check: LoadedSlice::isLegal returned true.
9815   /// \return The last instruction of the sequence used to load the slice.
9816   SDValue loadSlice() const {
9817     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9818     const SDValue &OldBaseAddr = Origin->getBasePtr();
9819     SDValue BaseAddr = OldBaseAddr;
9820     // Get the offset in that chunk of bytes w.r.t. the endianess.
9821     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9822     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9823     if (Offset) {
9824       // BaseAddr = BaseAddr + Offset.
9825       EVT ArithType = BaseAddr.getValueType();
9826       SDLoc DL(Origin);
9827       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9828                               DAG->getConstant(Offset, DL, ArithType));
9829     }
9830
9831     // Create the type of the loaded slice according to its size.
9832     EVT SliceType = getLoadedType();
9833
9834     // Create the load for the slice.
9835     SDValue LastInst = DAG->getLoad(
9836         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9837         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9838         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9839     // If the final type is not the same as the loaded type, this means that
9840     // we have to pad with zero. Create a zero extend for that.
9841     EVT FinalType = Inst->getValueType(0);
9842     if (SliceType != FinalType)
9843       LastInst =
9844           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9845     return LastInst;
9846   }
9847
9848   /// \brief Check if this slice can be merged with an expensive cross register
9849   /// bank copy. E.g.,
9850   /// i = load i32
9851   /// f = bitcast i32 i to float
9852   bool canMergeExpensiveCrossRegisterBankCopy() const {
9853     if (!Inst || !Inst->hasOneUse())
9854       return false;
9855     SDNode *Use = *Inst->use_begin();
9856     if (Use->getOpcode() != ISD::BITCAST)
9857       return false;
9858     assert(DAG && "Missing context");
9859     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9860     EVT ResVT = Use->getValueType(0);
9861     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9862     const TargetRegisterClass *ArgRC =
9863         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9864     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9865       return false;
9866
9867     // At this point, we know that we perform a cross-register-bank copy.
9868     // Check if it is expensive.
9869     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9870     // Assume bitcasts are cheap, unless both register classes do not
9871     // explicitly share a common sub class.
9872     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9873       return false;
9874
9875     // Check if it will be merged with the load.
9876     // 1. Check the alignment constraint.
9877     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9878         ResVT.getTypeForEVT(*DAG->getContext()));
9879
9880     if (RequiredAlignment > getAlignment())
9881       return false;
9882
9883     // 2. Check that the load is a legal operation for that type.
9884     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9885       return false;
9886
9887     // 3. Check that we do not have a zext in the way.
9888     if (Inst->getValueType(0) != getLoadedType())
9889       return false;
9890
9891     return true;
9892   }
9893 };
9894 }
9895
9896 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9897 /// \p UsedBits looks like 0..0 1..1 0..0.
9898 static bool areUsedBitsDense(const APInt &UsedBits) {
9899   // If all the bits are one, this is dense!
9900   if (UsedBits.isAllOnesValue())
9901     return true;
9902
9903   // Get rid of the unused bits on the right.
9904   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9905   // Get rid of the unused bits on the left.
9906   if (NarrowedUsedBits.countLeadingZeros())
9907     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9908   // Check that the chunk of bits is completely used.
9909   return NarrowedUsedBits.isAllOnesValue();
9910 }
9911
9912 /// \brief Check whether or not \p First and \p Second are next to each other
9913 /// in memory. This means that there is no hole between the bits loaded
9914 /// by \p First and the bits loaded by \p Second.
9915 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9916                                      const LoadedSlice &Second) {
9917   assert(First.Origin == Second.Origin && First.Origin &&
9918          "Unable to match different memory origins.");
9919   APInt UsedBits = First.getUsedBits();
9920   assert((UsedBits & Second.getUsedBits()) == 0 &&
9921          "Slices are not supposed to overlap.");
9922   UsedBits |= Second.getUsedBits();
9923   return areUsedBitsDense(UsedBits);
9924 }
9925
9926 /// \brief Adjust the \p GlobalLSCost according to the target
9927 /// paring capabilities and the layout of the slices.
9928 /// \pre \p GlobalLSCost should account for at least as many loads as
9929 /// there is in the slices in \p LoadedSlices.
9930 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9931                                  LoadedSlice::Cost &GlobalLSCost) {
9932   unsigned NumberOfSlices = LoadedSlices.size();
9933   // If there is less than 2 elements, no pairing is possible.
9934   if (NumberOfSlices < 2)
9935     return;
9936
9937   // Sort the slices so that elements that are likely to be next to each
9938   // other in memory are next to each other in the list.
9939   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9940             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9941     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9942     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9943   });
9944   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9945   // First (resp. Second) is the first (resp. Second) potentially candidate
9946   // to be placed in a paired load.
9947   const LoadedSlice *First = nullptr;
9948   const LoadedSlice *Second = nullptr;
9949   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9950                 // Set the beginning of the pair.
9951                                                            First = Second) {
9952
9953     Second = &LoadedSlices[CurrSlice];
9954
9955     // If First is NULL, it means we start a new pair.
9956     // Get to the next slice.
9957     if (!First)
9958       continue;
9959
9960     EVT LoadedType = First->getLoadedType();
9961
9962     // If the types of the slices are different, we cannot pair them.
9963     if (LoadedType != Second->getLoadedType())
9964       continue;
9965
9966     // Check if the target supplies paired loads for this type.
9967     unsigned RequiredAlignment = 0;
9968     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9969       // move to the next pair, this type is hopeless.
9970       Second = nullptr;
9971       continue;
9972     }
9973     // Check if we meet the alignment requirement.
9974     if (RequiredAlignment > First->getAlignment())
9975       continue;
9976
9977     // Check that both loads are next to each other in memory.
9978     if (!areSlicesNextToEachOther(*First, *Second))
9979       continue;
9980
9981     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9982     --GlobalLSCost.Loads;
9983     // Move to the next pair.
9984     Second = nullptr;
9985   }
9986 }
9987
9988 /// \brief Check the profitability of all involved LoadedSlice.
9989 /// Currently, it is considered profitable if there is exactly two
9990 /// involved slices (1) which are (2) next to each other in memory, and
9991 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9992 ///
9993 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9994 /// the elements themselves.
9995 ///
9996 /// FIXME: When the cost model will be mature enough, we can relax
9997 /// constraints (1) and (2).
9998 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9999                                 const APInt &UsedBits, bool ForCodeSize) {
10000   unsigned NumberOfSlices = LoadedSlices.size();
10001   if (StressLoadSlicing)
10002     return NumberOfSlices > 1;
10003
10004   // Check (1).
10005   if (NumberOfSlices != 2)
10006     return false;
10007
10008   // Check (2).
10009   if (!areUsedBitsDense(UsedBits))
10010     return false;
10011
10012   // Check (3).
10013   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10014   // The original code has one big load.
10015   OrigCost.Loads = 1;
10016   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10017     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10018     // Accumulate the cost of all the slices.
10019     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10020     GlobalSlicingCost += SliceCost;
10021
10022     // Account as cost in the original configuration the gain obtained
10023     // with the current slices.
10024     OrigCost.addSliceGain(LS);
10025   }
10026
10027   // If the target supports paired load, adjust the cost accordingly.
10028   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10029   return OrigCost > GlobalSlicingCost;
10030 }
10031
10032 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10033 /// operations, split it in the various pieces being extracted.
10034 ///
10035 /// This sort of thing is introduced by SROA.
10036 /// This slicing takes care not to insert overlapping loads.
10037 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10038 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10039   if (Level < AfterLegalizeDAG)
10040     return false;
10041
10042   LoadSDNode *LD = cast<LoadSDNode>(N);
10043   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10044       !LD->getValueType(0).isInteger())
10045     return false;
10046
10047   // Keep track of already used bits to detect overlapping values.
10048   // In that case, we will just abort the transformation.
10049   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10050
10051   SmallVector<LoadedSlice, 4> LoadedSlices;
10052
10053   // Check if this load is used as several smaller chunks of bits.
10054   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10055   // of computation for each trunc.
10056   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10057        UI != UIEnd; ++UI) {
10058     // Skip the uses of the chain.
10059     if (UI.getUse().getResNo() != 0)
10060       continue;
10061
10062     SDNode *User = *UI;
10063     unsigned Shift = 0;
10064
10065     // Check if this is a trunc(lshr).
10066     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10067         isa<ConstantSDNode>(User->getOperand(1))) {
10068       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10069       User = *User->use_begin();
10070     }
10071
10072     // At this point, User is a Truncate, iff we encountered, trunc or
10073     // trunc(lshr).
10074     if (User->getOpcode() != ISD::TRUNCATE)
10075       return false;
10076
10077     // The width of the type must be a power of 2 and greater than 8-bits.
10078     // Otherwise the load cannot be represented in LLVM IR.
10079     // Moreover, if we shifted with a non-8-bits multiple, the slice
10080     // will be across several bytes. We do not support that.
10081     unsigned Width = User->getValueSizeInBits(0);
10082     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10083       return 0;
10084
10085     // Build the slice for this chain of computations.
10086     LoadedSlice LS(User, LD, Shift, &DAG);
10087     APInt CurrentUsedBits = LS.getUsedBits();
10088
10089     // Check if this slice overlaps with another.
10090     if ((CurrentUsedBits & UsedBits) != 0)
10091       return false;
10092     // Update the bits used globally.
10093     UsedBits |= CurrentUsedBits;
10094
10095     // Check if the new slice would be legal.
10096     if (!LS.isLegal())
10097       return false;
10098
10099     // Record the slice.
10100     LoadedSlices.push_back(LS);
10101   }
10102
10103   // Abort slicing if it does not seem to be profitable.
10104   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10105     return false;
10106
10107   ++SlicedLoads;
10108
10109   // Rewrite each chain to use an independent load.
10110   // By construction, each chain can be represented by a unique load.
10111
10112   // Prepare the argument for the new token factor for all the slices.
10113   SmallVector<SDValue, 8> ArgChains;
10114   for (SmallVectorImpl<LoadedSlice>::const_iterator
10115            LSIt = LoadedSlices.begin(),
10116            LSItEnd = LoadedSlices.end();
10117        LSIt != LSItEnd; ++LSIt) {
10118     SDValue SliceInst = LSIt->loadSlice();
10119     CombineTo(LSIt->Inst, SliceInst, true);
10120     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10121       SliceInst = SliceInst.getOperand(0);
10122     assert(SliceInst->getOpcode() == ISD::LOAD &&
10123            "It takes more than a zext to get to the loaded slice!!");
10124     ArgChains.push_back(SliceInst.getValue(1));
10125   }
10126
10127   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10128                               ArgChains);
10129   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10130   return true;
10131 }
10132
10133 /// Check to see if V is (and load (ptr), imm), where the load is having
10134 /// specific bytes cleared out.  If so, return the byte size being masked out
10135 /// and the shift amount.
10136 static std::pair<unsigned, unsigned>
10137 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10138   std::pair<unsigned, unsigned> Result(0, 0);
10139
10140   // Check for the structure we're looking for.
10141   if (V->getOpcode() != ISD::AND ||
10142       !isa<ConstantSDNode>(V->getOperand(1)) ||
10143       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10144     return Result;
10145
10146   // Check the chain and pointer.
10147   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10148   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10149
10150   // The store should be chained directly to the load or be an operand of a
10151   // tokenfactor.
10152   if (LD == Chain.getNode())
10153     ; // ok.
10154   else if (Chain->getOpcode() != ISD::TokenFactor)
10155     return Result; // Fail.
10156   else {
10157     bool isOk = false;
10158     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10159       if (Chain->getOperand(i).getNode() == LD) {
10160         isOk = true;
10161         break;
10162       }
10163     if (!isOk) return Result;
10164   }
10165
10166   // This only handles simple types.
10167   if (V.getValueType() != MVT::i16 &&
10168       V.getValueType() != MVT::i32 &&
10169       V.getValueType() != MVT::i64)
10170     return Result;
10171
10172   // Check the constant mask.  Invert it so that the bits being masked out are
10173   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10174   // follow the sign bit for uniformity.
10175   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10176   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10177   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10178   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10179   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10180   if (NotMaskLZ == 64) return Result;  // All zero mask.
10181
10182   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10183   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10184     return Result;
10185
10186   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10187   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10188     NotMaskLZ -= 64-V.getValueSizeInBits();
10189
10190   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10191   switch (MaskedBytes) {
10192   case 1:
10193   case 2:
10194   case 4: break;
10195   default: return Result; // All one mask, or 5-byte mask.
10196   }
10197
10198   // Verify that the first bit starts at a multiple of mask so that the access
10199   // is aligned the same as the access width.
10200   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10201
10202   Result.first = MaskedBytes;
10203   Result.second = NotMaskTZ/8;
10204   return Result;
10205 }
10206
10207
10208 /// Check to see if IVal is something that provides a value as specified by
10209 /// MaskInfo. If so, replace the specified store with a narrower store of
10210 /// truncated IVal.
10211 static SDNode *
10212 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10213                                 SDValue IVal, StoreSDNode *St,
10214                                 DAGCombiner *DC) {
10215   unsigned NumBytes = MaskInfo.first;
10216   unsigned ByteShift = MaskInfo.second;
10217   SelectionDAG &DAG = DC->getDAG();
10218
10219   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10220   // that uses this.  If not, this is not a replacement.
10221   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10222                                   ByteShift*8, (ByteShift+NumBytes)*8);
10223   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10224
10225   // Check that it is legal on the target to do this.  It is legal if the new
10226   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10227   // legalization.
10228   MVT VT = MVT::getIntegerVT(NumBytes*8);
10229   if (!DC->isTypeLegal(VT))
10230     return nullptr;
10231
10232   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10233   // shifted by ByteShift and truncated down to NumBytes.
10234   if (ByteShift) {
10235     SDLoc DL(IVal);
10236     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10237                        DAG.getConstant(ByteShift*8, DL,
10238                                     DC->getShiftAmountTy(IVal.getValueType())));
10239   }
10240
10241   // Figure out the offset for the store and the alignment of the access.
10242   unsigned StOffset;
10243   unsigned NewAlign = St->getAlignment();
10244
10245   if (DAG.getTargetLoweringInfo().isLittleEndian())
10246     StOffset = ByteShift;
10247   else
10248     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10249
10250   SDValue Ptr = St->getBasePtr();
10251   if (StOffset) {
10252     SDLoc DL(IVal);
10253     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10254                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10255     NewAlign = MinAlign(NewAlign, StOffset);
10256   }
10257
10258   // Truncate down to the new size.
10259   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10260
10261   ++OpsNarrowed;
10262   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10263                       St->getPointerInfo().getWithOffset(StOffset),
10264                       false, false, NewAlign).getNode();
10265 }
10266
10267
10268 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10269 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10270 /// narrowing the load and store if it would end up being a win for performance
10271 /// or code size.
10272 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10273   StoreSDNode *ST  = cast<StoreSDNode>(N);
10274   if (ST->isVolatile())
10275     return SDValue();
10276
10277   SDValue Chain = ST->getChain();
10278   SDValue Value = ST->getValue();
10279   SDValue Ptr   = ST->getBasePtr();
10280   EVT VT = Value.getValueType();
10281
10282   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10283     return SDValue();
10284
10285   unsigned Opc = Value.getOpcode();
10286
10287   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10288   // is a byte mask indicating a consecutive number of bytes, check to see if
10289   // Y is known to provide just those bytes.  If so, we try to replace the
10290   // load + replace + store sequence with a single (narrower) store, which makes
10291   // the load dead.
10292   if (Opc == ISD::OR) {
10293     std::pair<unsigned, unsigned> MaskedLoad;
10294     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10295     if (MaskedLoad.first)
10296       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10297                                                   Value.getOperand(1), ST,this))
10298         return SDValue(NewST, 0);
10299
10300     // Or is commutative, so try swapping X and Y.
10301     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10302     if (MaskedLoad.first)
10303       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10304                                                   Value.getOperand(0), ST,this))
10305         return SDValue(NewST, 0);
10306   }
10307
10308   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10309       Value.getOperand(1).getOpcode() != ISD::Constant)
10310     return SDValue();
10311
10312   SDValue N0 = Value.getOperand(0);
10313   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10314       Chain == SDValue(N0.getNode(), 1)) {
10315     LoadSDNode *LD = cast<LoadSDNode>(N0);
10316     if (LD->getBasePtr() != Ptr ||
10317         LD->getPointerInfo().getAddrSpace() !=
10318         ST->getPointerInfo().getAddrSpace())
10319       return SDValue();
10320
10321     // Find the type to narrow it the load / op / store to.
10322     SDValue N1 = Value.getOperand(1);
10323     unsigned BitWidth = N1.getValueSizeInBits();
10324     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10325     if (Opc == ISD::AND)
10326       Imm ^= APInt::getAllOnesValue(BitWidth);
10327     if (Imm == 0 || Imm.isAllOnesValue())
10328       return SDValue();
10329     unsigned ShAmt = Imm.countTrailingZeros();
10330     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10331     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10332     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10333     // The narrowing should be profitable, the load/store operation should be
10334     // legal (or custom) and the store size should be equal to the NewVT width.
10335     while (NewBW < BitWidth &&
10336            (NewVT.getStoreSizeInBits() != NewBW ||
10337             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10338             !TLI.isNarrowingProfitable(VT, NewVT))) {
10339       NewBW = NextPowerOf2(NewBW);
10340       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10341     }
10342     if (NewBW >= BitWidth)
10343       return SDValue();
10344
10345     // If the lsb changed does not start at the type bitwidth boundary,
10346     // start at the previous one.
10347     if (ShAmt % NewBW)
10348       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10349     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10350                                    std::min(BitWidth, ShAmt + NewBW));
10351     if ((Imm & Mask) == Imm) {
10352       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10353       if (Opc == ISD::AND)
10354         NewImm ^= APInt::getAllOnesValue(NewBW);
10355       uint64_t PtrOff = ShAmt / 8;
10356       // For big endian targets, we need to adjust the offset to the pointer to
10357       // load the correct bytes.
10358       if (TLI.isBigEndian())
10359         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10360
10361       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10362       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10363       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10364         return SDValue();
10365
10366       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10367                                    Ptr.getValueType(), Ptr,
10368                                    DAG.getConstant(PtrOff, SDLoc(LD),
10369                                                    Ptr.getValueType()));
10370       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10371                                   LD->getChain(), NewPtr,
10372                                   LD->getPointerInfo().getWithOffset(PtrOff),
10373                                   LD->isVolatile(), LD->isNonTemporal(),
10374                                   LD->isInvariant(), NewAlign,
10375                                   LD->getAAInfo());
10376       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10377                                    DAG.getConstant(NewImm, SDLoc(Value),
10378                                                    NewVT));
10379       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10380                                    NewVal, NewPtr,
10381                                    ST->getPointerInfo().getWithOffset(PtrOff),
10382                                    false, false, NewAlign);
10383
10384       AddToWorklist(NewPtr.getNode());
10385       AddToWorklist(NewLD.getNode());
10386       AddToWorklist(NewVal.getNode());
10387       WorklistRemover DeadNodes(*this);
10388       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10389       ++OpsNarrowed;
10390       return NewST;
10391     }
10392   }
10393
10394   return SDValue();
10395 }
10396
10397 /// For a given floating point load / store pair, if the load value isn't used
10398 /// by any other operations, then consider transforming the pair to integer
10399 /// load / store operations if the target deems the transformation profitable.
10400 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10401   StoreSDNode *ST  = cast<StoreSDNode>(N);
10402   SDValue Chain = ST->getChain();
10403   SDValue Value = ST->getValue();
10404   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10405       Value.hasOneUse() &&
10406       Chain == SDValue(Value.getNode(), 1)) {
10407     LoadSDNode *LD = cast<LoadSDNode>(Value);
10408     EVT VT = LD->getMemoryVT();
10409     if (!VT.isFloatingPoint() ||
10410         VT != ST->getMemoryVT() ||
10411         LD->isNonTemporal() ||
10412         ST->isNonTemporal() ||
10413         LD->getPointerInfo().getAddrSpace() != 0 ||
10414         ST->getPointerInfo().getAddrSpace() != 0)
10415       return SDValue();
10416
10417     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10418     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10419         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10420         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10421         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10422       return SDValue();
10423
10424     unsigned LDAlign = LD->getAlignment();
10425     unsigned STAlign = ST->getAlignment();
10426     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10427     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10428     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10429       return SDValue();
10430
10431     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10432                                 LD->getChain(), LD->getBasePtr(),
10433                                 LD->getPointerInfo(),
10434                                 false, false, false, LDAlign);
10435
10436     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10437                                  NewLD, ST->getBasePtr(),
10438                                  ST->getPointerInfo(),
10439                                  false, false, STAlign);
10440
10441     AddToWorklist(NewLD.getNode());
10442     AddToWorklist(NewST.getNode());
10443     WorklistRemover DeadNodes(*this);
10444     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10445     ++LdStFP2Int;
10446     return NewST;
10447   }
10448
10449   return SDValue();
10450 }
10451
10452 namespace {
10453 /// Helper struct to parse and store a memory address as base + index + offset.
10454 /// We ignore sign extensions when it is safe to do so.
10455 /// The following two expressions are not equivalent. To differentiate we need
10456 /// to store whether there was a sign extension involved in the index
10457 /// computation.
10458 ///  (load (i64 add (i64 copyfromreg %c)
10459 ///                 (i64 signextend (add (i8 load %index)
10460 ///                                      (i8 1))))
10461 /// vs
10462 ///
10463 /// (load (i64 add (i64 copyfromreg %c)
10464 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10465 ///                                         (i32 1)))))
10466 struct BaseIndexOffset {
10467   SDValue Base;
10468   SDValue Index;
10469   int64_t Offset;
10470   bool IsIndexSignExt;
10471
10472   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10473
10474   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10475                   bool IsIndexSignExt) :
10476     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10477
10478   bool equalBaseIndex(const BaseIndexOffset &Other) {
10479     return Other.Base == Base && Other.Index == Index &&
10480       Other.IsIndexSignExt == IsIndexSignExt;
10481   }
10482
10483   /// Parses tree in Ptr for base, index, offset addresses.
10484   static BaseIndexOffset match(SDValue Ptr) {
10485     bool IsIndexSignExt = false;
10486
10487     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10488     // instruction, then it could be just the BASE or everything else we don't
10489     // know how to handle. Just use Ptr as BASE and give up.
10490     if (Ptr->getOpcode() != ISD::ADD)
10491       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10492
10493     // We know that we have at least an ADD instruction. Try to pattern match
10494     // the simple case of BASE + OFFSET.
10495     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10496       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10497       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10498                               IsIndexSignExt);
10499     }
10500
10501     // Inside a loop the current BASE pointer is calculated using an ADD and a
10502     // MUL instruction. In this case Ptr is the actual BASE pointer.
10503     // (i64 add (i64 %array_ptr)
10504     //          (i64 mul (i64 %induction_var)
10505     //                   (i64 %element_size)))
10506     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10507       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10508
10509     // Look at Base + Index + Offset cases.
10510     SDValue Base = Ptr->getOperand(0);
10511     SDValue IndexOffset = Ptr->getOperand(1);
10512
10513     // Skip signextends.
10514     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10515       IndexOffset = IndexOffset->getOperand(0);
10516       IsIndexSignExt = true;
10517     }
10518
10519     // Either the case of Base + Index (no offset) or something else.
10520     if (IndexOffset->getOpcode() != ISD::ADD)
10521       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10522
10523     // Now we have the case of Base + Index + offset.
10524     SDValue Index = IndexOffset->getOperand(0);
10525     SDValue Offset = IndexOffset->getOperand(1);
10526
10527     if (!isa<ConstantSDNode>(Offset))
10528       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10529
10530     // Ignore signextends.
10531     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10532       Index = Index->getOperand(0);
10533       IsIndexSignExt = true;
10534     } else IsIndexSignExt = false;
10535
10536     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10537     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10538   }
10539 };
10540 } // namespace
10541
10542 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10543                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10544                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10545   // Make sure we have something to merge.
10546   if (NumElem < 2)
10547     return false;
10548
10549   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10550   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10551   unsigned LatestNodeUsed = 0;
10552
10553   for (unsigned i=0; i < NumElem; ++i) {
10554     // Find a chain for the new wide-store operand. Notice that some
10555     // of the store nodes that we found may not be selected for inclusion
10556     // in the wide store. The chain we use needs to be the chain of the
10557     // latest store node which is *used* and replaced by the wide store.
10558     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10559       LatestNodeUsed = i;
10560   }
10561
10562   // The latest Node in the DAG.
10563   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10564   SDLoc DL(StoreNodes[0].MemNode);
10565
10566   SDValue StoredVal;
10567   if (UseVector) {
10568     // Find a legal type for the vector store.
10569     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10570     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10571     if (IsConstantSrc) {
10572       // A vector store with a constant source implies that the constant is
10573       // zero; we only handle merging stores of constant zeros because the zero
10574       // can be materialized without a load.
10575       // It may be beneficial to loosen this restriction to allow non-zero
10576       // store merging.
10577       StoredVal = DAG.getConstant(0, DL, Ty);
10578     } else {
10579       SmallVector<SDValue, 8> Ops;
10580       for (unsigned i = 0; i < NumElem ; ++i) {
10581         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10582         SDValue Val = St->getValue();
10583         // All of the operands of a BUILD_VECTOR must have the same type.
10584         if (Val.getValueType() != MemVT)
10585           return false;
10586         Ops.push_back(Val);
10587       }
10588
10589       // Build the extracted vector elements back into a vector.
10590       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10591     }
10592   } else {
10593     // We should always use a vector store when merging extracted vector
10594     // elements, so this path implies a store of constants.
10595     assert(IsConstantSrc && "Merged vector elements should use vector store");
10596
10597     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10598     APInt StoreInt(StoreBW, 0);
10599
10600     // Construct a single integer constant which is made of the smaller
10601     // constant inputs.
10602     bool IsLE = TLI.isLittleEndian();
10603     for (unsigned i = 0; i < NumElem ; ++i) {
10604       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10605       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10606       SDValue Val = St->getValue();
10607       StoreInt <<= ElementSizeBytes*8;
10608       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10609         StoreInt |= C->getAPIntValue().zext(StoreBW);
10610       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10611         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10612       } else {
10613         llvm_unreachable("Invalid constant element type");
10614       }
10615     }
10616
10617     // Create the new Load and Store operations.
10618     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10619     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10620   }
10621
10622   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10623                                   FirstInChain->getBasePtr(),
10624                                   FirstInChain->getPointerInfo(),
10625                                   false, false,
10626                                   FirstInChain->getAlignment());
10627
10628   // Replace the last store with the new store
10629   CombineTo(LatestOp, NewStore);
10630   // Erase all other stores.
10631   for (unsigned i = 0; i < NumElem ; ++i) {
10632     if (StoreNodes[i].MemNode == LatestOp)
10633       continue;
10634     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10635     // ReplaceAllUsesWith will replace all uses that existed when it was
10636     // called, but graph optimizations may cause new ones to appear. For
10637     // example, the case in pr14333 looks like
10638     //
10639     //  St's chain -> St -> another store -> X
10640     //
10641     // And the only difference from St to the other store is the chain.
10642     // When we change it's chain to be St's chain they become identical,
10643     // get CSEed and the net result is that X is now a use of St.
10644     // Since we know that St is redundant, just iterate.
10645     while (!St->use_empty())
10646       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10647     deleteAndRecombine(St);
10648   }
10649
10650   return true;
10651 }
10652
10653 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10654   if (OptLevel == CodeGenOpt::None)
10655     return false;
10656
10657   EVT MemVT = St->getMemoryVT();
10658   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10659   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10660       Attribute::NoImplicitFloat);
10661
10662   // Don't merge vectors into wider inputs.
10663   if (MemVT.isVector() || !MemVT.isSimple())
10664     return false;
10665
10666   // Perform an early exit check. Do not bother looking at stored values that
10667   // are not constants, loads, or extracted vector elements.
10668   SDValue StoredVal = St->getValue();
10669   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10670   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10671                        isa<ConstantFPSDNode>(StoredVal);
10672   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10673
10674   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10675     return false;
10676
10677   // Only look at ends of store sequences.
10678   SDValue Chain = SDValue(St, 0);
10679   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10680     return false;
10681
10682   // This holds the base pointer, index, and the offset in bytes from the base
10683   // pointer.
10684   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10685
10686   // We must have a base and an offset.
10687   if (!BasePtr.Base.getNode())
10688     return false;
10689
10690   // Do not handle stores to undef base pointers.
10691   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10692     return false;
10693
10694   // Save the LoadSDNodes that we find in the chain.
10695   // We need to make sure that these nodes do not interfere with
10696   // any of the store nodes.
10697   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10698
10699   // Save the StoreSDNodes that we find in the chain.
10700   SmallVector<MemOpLink, 8> StoreNodes;
10701
10702   // Walk up the chain and look for nodes with offsets from the same
10703   // base pointer. Stop when reaching an instruction with a different kind
10704   // or instruction which has a different base pointer.
10705   unsigned Seq = 0;
10706   StoreSDNode *Index = St;
10707   while (Index) {
10708     // If the chain has more than one use, then we can't reorder the mem ops.
10709     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10710       break;
10711
10712     // Find the base pointer and offset for this memory node.
10713     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10714
10715     // Check that the base pointer is the same as the original one.
10716     if (!Ptr.equalBaseIndex(BasePtr))
10717       break;
10718
10719     // Check that the alignment is the same.
10720     if (Index->getAlignment() != St->getAlignment())
10721       break;
10722
10723     // The memory operands must not be volatile.
10724     if (Index->isVolatile() || Index->isIndexed())
10725       break;
10726
10727     // No truncation.
10728     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10729       if (St->isTruncatingStore())
10730         break;
10731
10732     // The stored memory type must be the same.
10733     if (Index->getMemoryVT() != MemVT)
10734       break;
10735
10736     // We do not allow unaligned stores because we want to prevent overriding
10737     // stores.
10738     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10739       break;
10740
10741     // We found a potential memory operand to merge.
10742     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10743
10744     // Find the next memory operand in the chain. If the next operand in the
10745     // chain is a store then move up and continue the scan with the next
10746     // memory operand. If the next operand is a load save it and use alias
10747     // information to check if it interferes with anything.
10748     SDNode *NextInChain = Index->getChain().getNode();
10749     while (1) {
10750       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10751         // We found a store node. Use it for the next iteration.
10752         Index = STn;
10753         break;
10754       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10755         if (Ldn->isVolatile()) {
10756           Index = nullptr;
10757           break;
10758         }
10759
10760         // Save the load node for later. Continue the scan.
10761         AliasLoadNodes.push_back(Ldn);
10762         NextInChain = Ldn->getChain().getNode();
10763         continue;
10764       } else {
10765         Index = nullptr;
10766         break;
10767       }
10768     }
10769   }
10770
10771   // Check if there is anything to merge.
10772   if (StoreNodes.size() < 2)
10773     return false;
10774
10775   // Sort the memory operands according to their distance from the base pointer.
10776   std::sort(StoreNodes.begin(), StoreNodes.end(),
10777             [](MemOpLink LHS, MemOpLink RHS) {
10778     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10779            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10780             LHS.SequenceNum > RHS.SequenceNum);
10781   });
10782
10783   // Scan the memory operations on the chain and find the first non-consecutive
10784   // store memory address.
10785   unsigned LastConsecutiveStore = 0;
10786   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10787   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10788
10789     // Check that the addresses are consecutive starting from the second
10790     // element in the list of stores.
10791     if (i > 0) {
10792       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10793       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10794         break;
10795     }
10796
10797     bool Alias = false;
10798     // Check if this store interferes with any of the loads that we found.
10799     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10800       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10801         Alias = true;
10802         break;
10803       }
10804     // We found a load that alias with this store. Stop the sequence.
10805     if (Alias)
10806       break;
10807
10808     // Mark this node as useful.
10809     LastConsecutiveStore = i;
10810   }
10811
10812   // The node with the lowest store address.
10813   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10814
10815   // Store the constants into memory as one consecutive store.
10816   if (IsConstantSrc) {
10817     unsigned LastLegalType = 0;
10818     unsigned LastLegalVectorType = 0;
10819     bool NonZero = false;
10820     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10821       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10822       SDValue StoredVal = St->getValue();
10823
10824       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10825         NonZero |= !C->isNullValue();
10826       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10827         NonZero |= !C->getConstantFPValue()->isNullValue();
10828       } else {
10829         // Non-constant.
10830         break;
10831       }
10832
10833       // Find a legal type for the constant store.
10834       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10835       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10836       if (TLI.isTypeLegal(StoreTy))
10837         LastLegalType = i+1;
10838       // Or check whether a truncstore is legal.
10839       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10840                TargetLowering::TypePromoteInteger) {
10841         EVT LegalizedStoredValueTy =
10842           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10843         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10844           LastLegalType = i+1;
10845       }
10846
10847       // Find a legal type for the vector store.
10848       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10849       if (TLI.isTypeLegal(Ty))
10850         LastLegalVectorType = i + 1;
10851     }
10852
10853     // We only use vectors if the constant is known to be zero and the
10854     // function is not marked with the noimplicitfloat attribute.
10855     if (NonZero || NoVectors)
10856       LastLegalVectorType = 0;
10857
10858     // Check if we found a legal integer type to store.
10859     if (LastLegalType == 0 && LastLegalVectorType == 0)
10860       return false;
10861
10862     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10863     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10864
10865     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10866                                            true, UseVector);
10867   }
10868
10869   // When extracting multiple vector elements, try to store them
10870   // in one vector store rather than a sequence of scalar stores.
10871   if (IsExtractVecEltSrc) {
10872     unsigned NumElem = 0;
10873     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10874       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10875       SDValue StoredVal = St->getValue();
10876       // This restriction could be loosened.
10877       // Bail out if any stored values are not elements extracted from a vector.
10878       // It should be possible to handle mixed sources, but load sources need
10879       // more careful handling (see the block of code below that handles
10880       // consecutive loads).
10881       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10882         return false;
10883
10884       // Find a legal type for the vector store.
10885       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10886       if (TLI.isTypeLegal(Ty))
10887         NumElem = i + 1;
10888     }
10889
10890     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10891                                            false, true);
10892   }
10893
10894   // Below we handle the case of multiple consecutive stores that
10895   // come from multiple consecutive loads. We merge them into a single
10896   // wide load and a single wide store.
10897
10898   // Look for load nodes which are used by the stored values.
10899   SmallVector<MemOpLink, 8> LoadNodes;
10900
10901   // Find acceptable loads. Loads need to have the same chain (token factor),
10902   // must not be zext, volatile, indexed, and they must be consecutive.
10903   BaseIndexOffset LdBasePtr;
10904   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10905     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10906     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10907     if (!Ld) break;
10908
10909     // Loads must only have one use.
10910     if (!Ld->hasNUsesOfValue(1, 0))
10911       break;
10912
10913     // Check that the alignment is the same as the stores.
10914     if (Ld->getAlignment() != St->getAlignment())
10915       break;
10916
10917     // The memory operands must not be volatile.
10918     if (Ld->isVolatile() || Ld->isIndexed())
10919       break;
10920
10921     // We do not accept ext loads.
10922     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10923       break;
10924
10925     // The stored memory type must be the same.
10926     if (Ld->getMemoryVT() != MemVT)
10927       break;
10928
10929     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10930     // If this is not the first ptr that we check.
10931     if (LdBasePtr.Base.getNode()) {
10932       // The base ptr must be the same.
10933       if (!LdPtr.equalBaseIndex(LdBasePtr))
10934         break;
10935     } else {
10936       // Check that all other base pointers are the same as this one.
10937       LdBasePtr = LdPtr;
10938     }
10939
10940     // We found a potential memory operand to merge.
10941     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10942   }
10943
10944   if (LoadNodes.size() < 2)
10945     return false;
10946
10947   // If we have load/store pair instructions and we only have two values,
10948   // don't bother.
10949   unsigned RequiredAlignment;
10950   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10951       St->getAlignment() >= RequiredAlignment)
10952     return false;
10953
10954   // Scan the memory operations on the chain and find the first non-consecutive
10955   // load memory address. These variables hold the index in the store node
10956   // array.
10957   unsigned LastConsecutiveLoad = 0;
10958   // This variable refers to the size and not index in the array.
10959   unsigned LastLegalVectorType = 0;
10960   unsigned LastLegalIntegerType = 0;
10961   StartAddress = LoadNodes[0].OffsetFromBase;
10962   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10963   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10964     // All loads much share the same chain.
10965     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10966       break;
10967
10968     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10969     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10970       break;
10971     LastConsecutiveLoad = i;
10972
10973     // Find a legal type for the vector store.
10974     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10975     if (TLI.isTypeLegal(StoreTy))
10976       LastLegalVectorType = i + 1;
10977
10978     // Find a legal type for the integer store.
10979     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10980     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10981     if (TLI.isTypeLegal(StoreTy))
10982       LastLegalIntegerType = i + 1;
10983     // Or check whether a truncstore and extload is legal.
10984     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10985              TargetLowering::TypePromoteInteger) {
10986       EVT LegalizedStoredValueTy =
10987         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10988       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10989           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10990           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10991           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10992         LastLegalIntegerType = i+1;
10993     }
10994   }
10995
10996   // Only use vector types if the vector type is larger than the integer type.
10997   // If they are the same, use integers.
10998   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10999   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11000
11001   // We add +1 here because the LastXXX variables refer to location while
11002   // the NumElem refers to array/index size.
11003   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11004   NumElem = std::min(LastLegalType, NumElem);
11005
11006   if (NumElem < 2)
11007     return false;
11008
11009   // The latest Node in the DAG.
11010   unsigned LatestNodeUsed = 0;
11011   for (unsigned i=1; i<NumElem; ++i) {
11012     // Find a chain for the new wide-store operand. Notice that some
11013     // of the store nodes that we found may not be selected for inclusion
11014     // in the wide store. The chain we use needs to be the chain of the
11015     // latest store node which is *used* and replaced by the wide store.
11016     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11017       LatestNodeUsed = i;
11018   }
11019
11020   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11021
11022   // Find if it is better to use vectors or integers to load and store
11023   // to memory.
11024   EVT JointMemOpVT;
11025   if (UseVectorTy) {
11026     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11027   } else {
11028     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11029     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11030   }
11031
11032   SDLoc LoadDL(LoadNodes[0].MemNode);
11033   SDLoc StoreDL(StoreNodes[0].MemNode);
11034
11035   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11036   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
11037                                 FirstLoad->getChain(),
11038                                 FirstLoad->getBasePtr(),
11039                                 FirstLoad->getPointerInfo(),
11040                                 false, false, false,
11041                                 FirstLoad->getAlignment());
11042
11043   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
11044                                   FirstInChain->getBasePtr(),
11045                                   FirstInChain->getPointerInfo(), false, false,
11046                                   FirstInChain->getAlignment());
11047
11048   // Replace one of the loads with the new load.
11049   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11050   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11051                                 SDValue(NewLoad.getNode(), 1));
11052
11053   // Remove the rest of the load chains.
11054   for (unsigned i = 1; i < NumElem ; ++i) {
11055     // Replace all chain users of the old load nodes with the chain of the new
11056     // load node.
11057     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11058     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11059   }
11060
11061   // Replace the last store with the new store.
11062   CombineTo(LatestOp, NewStore);
11063   // Erase all other stores.
11064   for (unsigned i = 0; i < NumElem ; ++i) {
11065     // Remove all Store nodes.
11066     if (StoreNodes[i].MemNode == LatestOp)
11067       continue;
11068     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11069     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11070     deleteAndRecombine(St);
11071   }
11072
11073   return true;
11074 }
11075
11076 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11077   StoreSDNode *ST  = cast<StoreSDNode>(N);
11078   SDValue Chain = ST->getChain();
11079   SDValue Value = ST->getValue();
11080   SDValue Ptr   = ST->getBasePtr();
11081
11082   // If this is a store of a bit convert, store the input value if the
11083   // resultant store does not need a higher alignment than the original.
11084   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11085       ST->isUnindexed()) {
11086     unsigned OrigAlign = ST->getAlignment();
11087     EVT SVT = Value.getOperand(0).getValueType();
11088     unsigned Align = TLI.getDataLayout()->
11089       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11090     if (Align <= OrigAlign &&
11091         ((!LegalOperations && !ST->isVolatile()) ||
11092          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11093       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11094                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11095                           ST->isNonTemporal(), OrigAlign,
11096                           ST->getAAInfo());
11097   }
11098
11099   // Turn 'store undef, Ptr' -> nothing.
11100   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11101     return Chain;
11102
11103   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11104   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11105     // NOTE: If the original store is volatile, this transform must not increase
11106     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11107     // processor operation but an i64 (which is not legal) requires two.  So the
11108     // transform should not be done in this case.
11109     if (Value.getOpcode() != ISD::TargetConstantFP) {
11110       SDValue Tmp;
11111       switch (CFP->getSimpleValueType(0).SimpleTy) {
11112       default: llvm_unreachable("Unknown FP type");
11113       case MVT::f16:    // We don't do this for these yet.
11114       case MVT::f80:
11115       case MVT::f128:
11116       case MVT::ppcf128:
11117         break;
11118       case MVT::f32:
11119         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11120             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11121           ;
11122           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11123                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11124                               MVT::i32);
11125           return DAG.getStore(Chain, SDLoc(N), Tmp,
11126                               Ptr, ST->getMemOperand());
11127         }
11128         break;
11129       case MVT::f64:
11130         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11131              !ST->isVolatile()) ||
11132             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11133           ;
11134           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11135                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11136           return DAG.getStore(Chain, SDLoc(N), Tmp,
11137                               Ptr, ST->getMemOperand());
11138         }
11139
11140         if (!ST->isVolatile() &&
11141             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11142           // Many FP stores are not made apparent until after legalize, e.g. for
11143           // argument passing.  Since this is so common, custom legalize the
11144           // 64-bit integer store into two 32-bit stores.
11145           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11146           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11147           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11148           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11149
11150           unsigned Alignment = ST->getAlignment();
11151           bool isVolatile = ST->isVolatile();
11152           bool isNonTemporal = ST->isNonTemporal();
11153           AAMDNodes AAInfo = ST->getAAInfo();
11154
11155           SDLoc DL(N);
11156
11157           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11158                                      Ptr, ST->getPointerInfo(),
11159                                      isVolatile, isNonTemporal,
11160                                      ST->getAlignment(), AAInfo);
11161           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11162                             DAG.getConstant(4, DL, Ptr.getValueType()));
11163           Alignment = MinAlign(Alignment, 4U);
11164           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11165                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11166                                      isVolatile, isNonTemporal,
11167                                      Alignment, AAInfo);
11168           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11169                              St0, St1);
11170         }
11171
11172         break;
11173       }
11174     }
11175   }
11176
11177   // Try to infer better alignment information than the store already has.
11178   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11179     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11180       if (Align > ST->getAlignment()) {
11181         SDValue NewStore =
11182                DAG.getTruncStore(Chain, SDLoc(N), Value,
11183                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11184                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11185                                  ST->getAAInfo());
11186         if (NewStore.getNode() != N)
11187           return CombineTo(ST, NewStore, true);
11188       }
11189     }
11190   }
11191
11192   // Try transforming a pair floating point load / store ops to integer
11193   // load / store ops.
11194   SDValue NewST = TransformFPLoadStorePair(N);
11195   if (NewST.getNode())
11196     return NewST;
11197
11198   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11199                                                   : DAG.getSubtarget().useAA();
11200 #ifndef NDEBUG
11201   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11202       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11203     UseAA = false;
11204 #endif
11205   if (UseAA && ST->isUnindexed()) {
11206     // Walk up chain skipping non-aliasing memory nodes.
11207     SDValue BetterChain = FindBetterChain(N, Chain);
11208
11209     // If there is a better chain.
11210     if (Chain != BetterChain) {
11211       SDValue ReplStore;
11212
11213       // Replace the chain to avoid dependency.
11214       if (ST->isTruncatingStore()) {
11215         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11216                                       ST->getMemoryVT(), ST->getMemOperand());
11217       } else {
11218         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11219                                  ST->getMemOperand());
11220       }
11221
11222       // Create token to keep both nodes around.
11223       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11224                                   MVT::Other, Chain, ReplStore);
11225
11226       // Make sure the new and old chains are cleaned up.
11227       AddToWorklist(Token.getNode());
11228
11229       // Don't add users to work list.
11230       return CombineTo(N, Token, false);
11231     }
11232   }
11233
11234   // Try transforming N to an indexed store.
11235   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11236     return SDValue(N, 0);
11237
11238   // FIXME: is there such a thing as a truncating indexed store?
11239   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11240       Value.getValueType().isInteger()) {
11241     // See if we can simplify the input to this truncstore with knowledge that
11242     // only the low bits are being used.  For example:
11243     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11244     SDValue Shorter =
11245       GetDemandedBits(Value,
11246                       APInt::getLowBitsSet(
11247                         Value.getValueType().getScalarType().getSizeInBits(),
11248                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11249     AddToWorklist(Value.getNode());
11250     if (Shorter.getNode())
11251       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11252                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11253
11254     // Otherwise, see if we can simplify the operation with
11255     // SimplifyDemandedBits, which only works if the value has a single use.
11256     if (SimplifyDemandedBits(Value,
11257                         APInt::getLowBitsSet(
11258                           Value.getValueType().getScalarType().getSizeInBits(),
11259                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11260       return SDValue(N, 0);
11261   }
11262
11263   // If this is a load followed by a store to the same location, then the store
11264   // is dead/noop.
11265   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11266     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11267         ST->isUnindexed() && !ST->isVolatile() &&
11268         // There can't be any side effects between the load and store, such as
11269         // a call or store.
11270         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11271       // The store is dead, remove it.
11272       return Chain;
11273     }
11274   }
11275
11276   // If this is a store followed by a store with the same value to the same
11277   // location, then the store is dead/noop.
11278   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11279     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11280         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11281         ST1->isUnindexed() && !ST1->isVolatile()) {
11282       // The store is dead, remove it.
11283       return Chain;
11284     }
11285   }
11286
11287   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11288   // truncating store.  We can do this even if this is already a truncstore.
11289   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11290       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11291       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11292                             ST->getMemoryVT())) {
11293     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11294                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11295   }
11296
11297   // Only perform this optimization before the types are legal, because we
11298   // don't want to perform this optimization on every DAGCombine invocation.
11299   if (!LegalTypes) {
11300     bool EverChanged = false;
11301
11302     do {
11303       // There can be multiple store sequences on the same chain.
11304       // Keep trying to merge store sequences until we are unable to do so
11305       // or until we merge the last store on the chain.
11306       bool Changed = MergeConsecutiveStores(ST);
11307       EverChanged |= Changed;
11308       if (!Changed) break;
11309     } while (ST->getOpcode() != ISD::DELETED_NODE);
11310
11311     if (EverChanged)
11312       return SDValue(N, 0);
11313   }
11314
11315   return ReduceLoadOpStoreWidth(N);
11316 }
11317
11318 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11319   SDValue InVec = N->getOperand(0);
11320   SDValue InVal = N->getOperand(1);
11321   SDValue EltNo = N->getOperand(2);
11322   SDLoc dl(N);
11323
11324   // If the inserted element is an UNDEF, just use the input vector.
11325   if (InVal.getOpcode() == ISD::UNDEF)
11326     return InVec;
11327
11328   EVT VT = InVec.getValueType();
11329
11330   // If we can't generate a legal BUILD_VECTOR, exit
11331   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11332     return SDValue();
11333
11334   // Check that we know which element is being inserted
11335   if (!isa<ConstantSDNode>(EltNo))
11336     return SDValue();
11337   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11338
11339   // Canonicalize insert_vector_elt dag nodes.
11340   // Example:
11341   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11342   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11343   //
11344   // Do this only if the child insert_vector node has one use; also
11345   // do this only if indices are both constants and Idx1 < Idx0.
11346   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11347       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11348     unsigned OtherElt =
11349       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11350     if (Elt < OtherElt) {
11351       // Swap nodes.
11352       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11353                                   InVec.getOperand(0), InVal, EltNo);
11354       AddToWorklist(NewOp.getNode());
11355       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11356                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11357     }
11358   }
11359
11360   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11361   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11362   // vector elements.
11363   SmallVector<SDValue, 8> Ops;
11364   // Do not combine these two vectors if the output vector will not replace
11365   // the input vector.
11366   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11367     Ops.append(InVec.getNode()->op_begin(),
11368                InVec.getNode()->op_end());
11369   } else if (InVec.getOpcode() == ISD::UNDEF) {
11370     unsigned NElts = VT.getVectorNumElements();
11371     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11372   } else {
11373     return SDValue();
11374   }
11375
11376   // Insert the element
11377   if (Elt < Ops.size()) {
11378     // All the operands of BUILD_VECTOR must have the same type;
11379     // we enforce that here.
11380     EVT OpVT = Ops[0].getValueType();
11381     if (InVal.getValueType() != OpVT)
11382       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11383                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11384                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11385     Ops[Elt] = InVal;
11386   }
11387
11388   // Return the new vector
11389   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11390 }
11391
11392 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11393     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11394   EVT ResultVT = EVE->getValueType(0);
11395   EVT VecEltVT = InVecVT.getVectorElementType();
11396   unsigned Align = OriginalLoad->getAlignment();
11397   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11398       VecEltVT.getTypeForEVT(*DAG.getContext()));
11399
11400   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11401     return SDValue();
11402
11403   Align = NewAlign;
11404
11405   SDValue NewPtr = OriginalLoad->getBasePtr();
11406   SDValue Offset;
11407   EVT PtrType = NewPtr.getValueType();
11408   MachinePointerInfo MPI;
11409   SDLoc DL(EVE);
11410   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11411     int Elt = ConstEltNo->getZExtValue();
11412     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11413     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11414     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11415   } else {
11416     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11417     Offset = DAG.getNode(
11418         ISD::MUL, DL, PtrType, Offset,
11419         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11420     MPI = OriginalLoad->getPointerInfo();
11421   }
11422   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11423
11424   // The replacement we need to do here is a little tricky: we need to
11425   // replace an extractelement of a load with a load.
11426   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11427   // Note that this replacement assumes that the extractvalue is the only
11428   // use of the load; that's okay because we don't want to perform this
11429   // transformation in other cases anyway.
11430   SDValue Load;
11431   SDValue Chain;
11432   if (ResultVT.bitsGT(VecEltVT)) {
11433     // If the result type of vextract is wider than the load, then issue an
11434     // extending load instead.
11435     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11436                                                   VecEltVT)
11437                                    ? ISD::ZEXTLOAD
11438                                    : ISD::EXTLOAD;
11439     Load = DAG.getExtLoad(
11440         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11441         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11442         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11443     Chain = Load.getValue(1);
11444   } else {
11445     Load = DAG.getLoad(
11446         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11447         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11448         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11449     Chain = Load.getValue(1);
11450     if (ResultVT.bitsLT(VecEltVT))
11451       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11452     else
11453       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11454   }
11455   WorklistRemover DeadNodes(*this);
11456   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11457   SDValue To[] = { Load, Chain };
11458   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11459   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11460   // worklist explicitly as well.
11461   AddToWorklist(Load.getNode());
11462   AddUsersToWorklist(Load.getNode()); // Add users too
11463   // Make sure to revisit this node to clean it up; it will usually be dead.
11464   AddToWorklist(EVE);
11465   ++OpsNarrowed;
11466   return SDValue(EVE, 0);
11467 }
11468
11469 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11470   // (vextract (scalar_to_vector val, 0) -> val
11471   SDValue InVec = N->getOperand(0);
11472   EVT VT = InVec.getValueType();
11473   EVT NVT = N->getValueType(0);
11474
11475   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11476     // Check if the result type doesn't match the inserted element type. A
11477     // SCALAR_TO_VECTOR may truncate the inserted element and the
11478     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11479     SDValue InOp = InVec.getOperand(0);
11480     if (InOp.getValueType() != NVT) {
11481       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11482       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11483     }
11484     return InOp;
11485   }
11486
11487   SDValue EltNo = N->getOperand(1);
11488   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11489
11490   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11491   // We only perform this optimization before the op legalization phase because
11492   // we may introduce new vector instructions which are not backed by TD
11493   // patterns. For example on AVX, extracting elements from a wide vector
11494   // without using extract_subvector. However, if we can find an underlying
11495   // scalar value, then we can always use that.
11496   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11497       && ConstEltNo) {
11498     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11499     int NumElem = VT.getVectorNumElements();
11500     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11501     // Find the new index to extract from.
11502     int OrigElt = SVOp->getMaskElt(Elt);
11503
11504     // Extracting an undef index is undef.
11505     if (OrigElt == -1)
11506       return DAG.getUNDEF(NVT);
11507
11508     // Select the right vector half to extract from.
11509     SDValue SVInVec;
11510     if (OrigElt < NumElem) {
11511       SVInVec = InVec->getOperand(0);
11512     } else {
11513       SVInVec = InVec->getOperand(1);
11514       OrigElt -= NumElem;
11515     }
11516
11517     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11518       SDValue InOp = SVInVec.getOperand(OrigElt);
11519       if (InOp.getValueType() != NVT) {
11520         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11521         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11522       }
11523
11524       return InOp;
11525     }
11526
11527     // FIXME: We should handle recursing on other vector shuffles and
11528     // scalar_to_vector here as well.
11529
11530     if (!LegalOperations) {
11531       EVT IndexTy = TLI.getVectorIdxTy();
11532       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11533                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11534     }
11535   }
11536
11537   bool BCNumEltsChanged = false;
11538   EVT ExtVT = VT.getVectorElementType();
11539   EVT LVT = ExtVT;
11540
11541   // If the result of load has to be truncated, then it's not necessarily
11542   // profitable.
11543   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11544     return SDValue();
11545
11546   if (InVec.getOpcode() == ISD::BITCAST) {
11547     // Don't duplicate a load with other uses.
11548     if (!InVec.hasOneUse())
11549       return SDValue();
11550
11551     EVT BCVT = InVec.getOperand(0).getValueType();
11552     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11553       return SDValue();
11554     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11555       BCNumEltsChanged = true;
11556     InVec = InVec.getOperand(0);
11557     ExtVT = BCVT.getVectorElementType();
11558   }
11559
11560   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11561   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11562       ISD::isNormalLoad(InVec.getNode()) &&
11563       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11564     SDValue Index = N->getOperand(1);
11565     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11566       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11567                                                            OrigLoad);
11568   }
11569
11570   // Perform only after legalization to ensure build_vector / vector_shuffle
11571   // optimizations have already been done.
11572   if (!LegalOperations) return SDValue();
11573
11574   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11575   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11576   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11577
11578   if (ConstEltNo) {
11579     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11580
11581     LoadSDNode *LN0 = nullptr;
11582     const ShuffleVectorSDNode *SVN = nullptr;
11583     if (ISD::isNormalLoad(InVec.getNode())) {
11584       LN0 = cast<LoadSDNode>(InVec);
11585     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11586                InVec.getOperand(0).getValueType() == ExtVT &&
11587                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11588       // Don't duplicate a load with other uses.
11589       if (!InVec.hasOneUse())
11590         return SDValue();
11591
11592       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11593     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11594       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11595       // =>
11596       // (load $addr+1*size)
11597
11598       // Don't duplicate a load with other uses.
11599       if (!InVec.hasOneUse())
11600         return SDValue();
11601
11602       // If the bit convert changed the number of elements, it is unsafe
11603       // to examine the mask.
11604       if (BCNumEltsChanged)
11605         return SDValue();
11606
11607       // Select the input vector, guarding against out of range extract vector.
11608       unsigned NumElems = VT.getVectorNumElements();
11609       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11610       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11611
11612       if (InVec.getOpcode() == ISD::BITCAST) {
11613         // Don't duplicate a load with other uses.
11614         if (!InVec.hasOneUse())
11615           return SDValue();
11616
11617         InVec = InVec.getOperand(0);
11618       }
11619       if (ISD::isNormalLoad(InVec.getNode())) {
11620         LN0 = cast<LoadSDNode>(InVec);
11621         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11622         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11623       }
11624     }
11625
11626     // Make sure we found a non-volatile load and the extractelement is
11627     // the only use.
11628     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11629       return SDValue();
11630
11631     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11632     if (Elt == -1)
11633       return DAG.getUNDEF(LVT);
11634
11635     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11636   }
11637
11638   return SDValue();
11639 }
11640
11641 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11642 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11643   // We perform this optimization post type-legalization because
11644   // the type-legalizer often scalarizes integer-promoted vectors.
11645   // Performing this optimization before may create bit-casts which
11646   // will be type-legalized to complex code sequences.
11647   // We perform this optimization only before the operation legalizer because we
11648   // may introduce illegal operations.
11649   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11650     return SDValue();
11651
11652   unsigned NumInScalars = N->getNumOperands();
11653   SDLoc dl(N);
11654   EVT VT = N->getValueType(0);
11655
11656   // Check to see if this is a BUILD_VECTOR of a bunch of values
11657   // which come from any_extend or zero_extend nodes. If so, we can create
11658   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11659   // optimizations. We do not handle sign-extend because we can't fill the sign
11660   // using shuffles.
11661   EVT SourceType = MVT::Other;
11662   bool AllAnyExt = true;
11663
11664   for (unsigned i = 0; i != NumInScalars; ++i) {
11665     SDValue In = N->getOperand(i);
11666     // Ignore undef inputs.
11667     if (In.getOpcode() == ISD::UNDEF) continue;
11668
11669     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11670     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11671
11672     // Abort if the element is not an extension.
11673     if (!ZeroExt && !AnyExt) {
11674       SourceType = MVT::Other;
11675       break;
11676     }
11677
11678     // The input is a ZeroExt or AnyExt. Check the original type.
11679     EVT InTy = In.getOperand(0).getValueType();
11680
11681     // Check that all of the widened source types are the same.
11682     if (SourceType == MVT::Other)
11683       // First time.
11684       SourceType = InTy;
11685     else if (InTy != SourceType) {
11686       // Multiple income types. Abort.
11687       SourceType = MVT::Other;
11688       break;
11689     }
11690
11691     // Check if all of the extends are ANY_EXTENDs.
11692     AllAnyExt &= AnyExt;
11693   }
11694
11695   // In order to have valid types, all of the inputs must be extended from the
11696   // same source type and all of the inputs must be any or zero extend.
11697   // Scalar sizes must be a power of two.
11698   EVT OutScalarTy = VT.getScalarType();
11699   bool ValidTypes = SourceType != MVT::Other &&
11700                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11701                  isPowerOf2_32(SourceType.getSizeInBits());
11702
11703   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11704   // turn into a single shuffle instruction.
11705   if (!ValidTypes)
11706     return SDValue();
11707
11708   bool isLE = TLI.isLittleEndian();
11709   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11710   assert(ElemRatio > 1 && "Invalid element size ratio");
11711   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11712                                DAG.getConstant(0, SDLoc(N), SourceType);
11713
11714   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11715   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11716
11717   // Populate the new build_vector
11718   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11719     SDValue Cast = N->getOperand(i);
11720     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11721             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11722             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11723     SDValue In;
11724     if (Cast.getOpcode() == ISD::UNDEF)
11725       In = DAG.getUNDEF(SourceType);
11726     else
11727       In = Cast->getOperand(0);
11728     unsigned Index = isLE ? (i * ElemRatio) :
11729                             (i * ElemRatio + (ElemRatio - 1));
11730
11731     assert(Index < Ops.size() && "Invalid index");
11732     Ops[Index] = In;
11733   }
11734
11735   // The type of the new BUILD_VECTOR node.
11736   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11737   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11738          "Invalid vector size");
11739   // Check if the new vector type is legal.
11740   if (!isTypeLegal(VecVT)) return SDValue();
11741
11742   // Make the new BUILD_VECTOR.
11743   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11744
11745   // The new BUILD_VECTOR node has the potential to be further optimized.
11746   AddToWorklist(BV.getNode());
11747   // Bitcast to the desired type.
11748   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11749 }
11750
11751 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11752   EVT VT = N->getValueType(0);
11753
11754   unsigned NumInScalars = N->getNumOperands();
11755   SDLoc dl(N);
11756
11757   EVT SrcVT = MVT::Other;
11758   unsigned Opcode = ISD::DELETED_NODE;
11759   unsigned NumDefs = 0;
11760
11761   for (unsigned i = 0; i != NumInScalars; ++i) {
11762     SDValue In = N->getOperand(i);
11763     unsigned Opc = In.getOpcode();
11764
11765     if (Opc == ISD::UNDEF)
11766       continue;
11767
11768     // If all scalar values are floats and converted from integers.
11769     if (Opcode == ISD::DELETED_NODE &&
11770         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11771       Opcode = Opc;
11772     }
11773
11774     if (Opc != Opcode)
11775       return SDValue();
11776
11777     EVT InVT = In.getOperand(0).getValueType();
11778
11779     // If all scalar values are typed differently, bail out. It's chosen to
11780     // simplify BUILD_VECTOR of integer types.
11781     if (SrcVT == MVT::Other)
11782       SrcVT = InVT;
11783     if (SrcVT != InVT)
11784       return SDValue();
11785     NumDefs++;
11786   }
11787
11788   // If the vector has just one element defined, it's not worth to fold it into
11789   // a vectorized one.
11790   if (NumDefs < 2)
11791     return SDValue();
11792
11793   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11794          && "Should only handle conversion from integer to float.");
11795   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11796
11797   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11798
11799   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11800     return SDValue();
11801
11802   // Just because the floating-point vector type is legal does not necessarily
11803   // mean that the corresponding integer vector type is.
11804   if (!isTypeLegal(NVT))
11805     return SDValue();
11806
11807   SmallVector<SDValue, 8> Opnds;
11808   for (unsigned i = 0; i != NumInScalars; ++i) {
11809     SDValue In = N->getOperand(i);
11810
11811     if (In.getOpcode() == ISD::UNDEF)
11812       Opnds.push_back(DAG.getUNDEF(SrcVT));
11813     else
11814       Opnds.push_back(In.getOperand(0));
11815   }
11816   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11817   AddToWorklist(BV.getNode());
11818
11819   return DAG.getNode(Opcode, dl, VT, BV);
11820 }
11821
11822 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11823   unsigned NumInScalars = N->getNumOperands();
11824   SDLoc dl(N);
11825   EVT VT = N->getValueType(0);
11826
11827   // A vector built entirely of undefs is undef.
11828   if (ISD::allOperandsUndef(N))
11829     return DAG.getUNDEF(VT);
11830
11831   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11832     return V;
11833
11834   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11835     return V;
11836
11837   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11838   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11839   // at most two distinct vectors, turn this into a shuffle node.
11840
11841   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11842   if (!isTypeLegal(VT))
11843     return SDValue();
11844
11845   // May only combine to shuffle after legalize if shuffle is legal.
11846   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11847     return SDValue();
11848
11849   SDValue VecIn1, VecIn2;
11850   bool UsesZeroVector = false;
11851   for (unsigned i = 0; i != NumInScalars; ++i) {
11852     SDValue Op = N->getOperand(i);
11853     // Ignore undef inputs.
11854     if (Op.getOpcode() == ISD::UNDEF) continue;
11855
11856     // See if we can combine this build_vector into a blend with a zero vector.
11857     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11858         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11859         (Op.getOpcode() == ISD::ConstantFP &&
11860         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11861       UsesZeroVector = true;
11862       continue;
11863     }
11864
11865     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11866     // constant index, bail out.
11867     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11868         !isa<ConstantSDNode>(Op.getOperand(1))) {
11869       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11870       break;
11871     }
11872
11873     // We allow up to two distinct input vectors.
11874     SDValue ExtractedFromVec = Op.getOperand(0);
11875     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11876       continue;
11877
11878     if (!VecIn1.getNode()) {
11879       VecIn1 = ExtractedFromVec;
11880     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11881       VecIn2 = ExtractedFromVec;
11882     } else {
11883       // Too many inputs.
11884       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11885       break;
11886     }
11887   }
11888
11889   // If everything is good, we can make a shuffle operation.
11890   if (VecIn1.getNode()) {
11891     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11892     SmallVector<int, 8> Mask;
11893     for (unsigned i = 0; i != NumInScalars; ++i) {
11894       unsigned Opcode = N->getOperand(i).getOpcode();
11895       if (Opcode == ISD::UNDEF) {
11896         Mask.push_back(-1);
11897         continue;
11898       }
11899
11900       // Operands can also be zero.
11901       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11902         assert(UsesZeroVector &&
11903                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11904                "Unexpected node found!");
11905         Mask.push_back(NumInScalars+i);
11906         continue;
11907       }
11908
11909       // If extracting from the first vector, just use the index directly.
11910       SDValue Extract = N->getOperand(i);
11911       SDValue ExtVal = Extract.getOperand(1);
11912       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11913       if (Extract.getOperand(0) == VecIn1) {
11914         Mask.push_back(ExtIndex);
11915         continue;
11916       }
11917
11918       // Otherwise, use InIdx + InputVecSize
11919       Mask.push_back(InNumElements + ExtIndex);
11920     }
11921
11922     // Avoid introducing illegal shuffles with zero.
11923     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11924       return SDValue();
11925
11926     // We can't generate a shuffle node with mismatched input and output types.
11927     // Attempt to transform a single input vector to the correct type.
11928     if ((VT != VecIn1.getValueType())) {
11929       // If the input vector type has a different base type to the output
11930       // vector type, bail out.
11931       EVT VTElemType = VT.getVectorElementType();
11932       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11933           (VecIn2.getNode() &&
11934            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11935         return SDValue();
11936
11937       // If the input vector is too small, widen it.
11938       // We only support widening of vectors which are half the size of the
11939       // output registers. For example XMM->YMM widening on X86 with AVX.
11940       EVT VecInT = VecIn1.getValueType();
11941       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11942         // If we only have one small input, widen it by adding undef values.
11943         if (!VecIn2.getNode())
11944           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11945                                DAG.getUNDEF(VecIn1.getValueType()));
11946         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11947           // If we have two small inputs of the same type, try to concat them.
11948           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11949           VecIn2 = SDValue(nullptr, 0);
11950         } else
11951           return SDValue();
11952       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11953         // If the input vector is too large, try to split it.
11954         // We don't support having two input vectors that are too large.
11955         // If the zero vector was used, we can not split the vector,
11956         // since we'd need 3 inputs.
11957         if (UsesZeroVector || VecIn2.getNode())
11958           return SDValue();
11959
11960         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11961           return SDValue();
11962
11963         // Try to replace VecIn1 with two extract_subvectors
11964         // No need to update the masks, they should still be correct.
11965         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11966           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11967         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11968           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11969       } else
11970         return SDValue();
11971     }
11972
11973     if (UsesZeroVector)
11974       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11975                                 DAG.getConstantFP(0.0, dl, VT);
11976     else
11977       // If VecIn2 is unused then change it to undef.
11978       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11979
11980     // Check that we were able to transform all incoming values to the same
11981     // type.
11982     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11983         VecIn1.getValueType() != VT)
11984           return SDValue();
11985
11986     // Return the new VECTOR_SHUFFLE node.
11987     SDValue Ops[2];
11988     Ops[0] = VecIn1;
11989     Ops[1] = VecIn2;
11990     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11991   }
11992
11993   return SDValue();
11994 }
11995
11996 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11997   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11998   EVT OpVT = N->getOperand(0).getValueType();
11999
12000   // If the operands are legal vectors, leave them alone.
12001   if (TLI.isTypeLegal(OpVT))
12002     return SDValue();
12003
12004   SDLoc DL(N);
12005   EVT VT = N->getValueType(0);
12006   SmallVector<SDValue, 8> Ops;
12007
12008   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12009   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12010
12011   // Keep track of what we encounter.
12012   bool AnyInteger = false;
12013   bool AnyFP = false;
12014   for (const SDValue &Op : N->ops()) {
12015     if (ISD::BITCAST == Op.getOpcode() &&
12016         !Op.getOperand(0).getValueType().isVector())
12017       Ops.push_back(Op.getOperand(0));
12018     else if (ISD::UNDEF == Op.getOpcode())
12019       Ops.push_back(ScalarUndef);
12020     else
12021       return SDValue();
12022
12023     // Note whether we encounter an integer or floating point scalar.
12024     // If it's neither, bail out, it could be something weird like x86mmx.
12025     EVT LastOpVT = Ops.back().getValueType();
12026     if (LastOpVT.isFloatingPoint())
12027       AnyFP = true;
12028     else if (LastOpVT.isInteger())
12029       AnyInteger = true;
12030     else
12031       return SDValue();
12032   }
12033
12034   // If any of the operands is a floating point scalar bitcast to a vector,
12035   // use floating point types throughout, and bitcast everything.  
12036   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12037   if (AnyFP) {
12038     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12039     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12040     if (AnyInteger) {
12041       for (SDValue &Op : Ops) {
12042         if (Op.getValueType() == SVT)
12043           continue;
12044         if (Op.getOpcode() == ISD::UNDEF)
12045           Op = ScalarUndef;
12046         else
12047           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12048       }
12049     }
12050   }
12051
12052   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12053                                VT.getSizeInBits() / SVT.getSizeInBits());
12054   return DAG.getNode(ISD::BITCAST, DL, VT,
12055                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12056 }
12057
12058 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12059   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12060   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12061   // inputs come from at most two distinct vectors, turn this into a shuffle
12062   // node.
12063
12064   // If we only have one input vector, we don't need to do any concatenation.
12065   if (N->getNumOperands() == 1)
12066     return N->getOperand(0);
12067
12068   // Check if all of the operands are undefs.
12069   EVT VT = N->getValueType(0);
12070   if (ISD::allOperandsUndef(N))
12071     return DAG.getUNDEF(VT);
12072
12073   // Optimize concat_vectors where all but the first of the vectors are undef.
12074   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12075         return Op.getOpcode() == ISD::UNDEF;
12076       })) {
12077     SDValue In = N->getOperand(0);
12078     assert(In.getValueType().isVector() && "Must concat vectors");
12079
12080     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12081     if (In->getOpcode() == ISD::BITCAST &&
12082         !In->getOperand(0)->getValueType(0).isVector()) {
12083       SDValue Scalar = In->getOperand(0);
12084
12085       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12086       // look through the trunc so we can still do the transform:
12087       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12088       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12089           !TLI.isTypeLegal(Scalar.getValueType()) &&
12090           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12091         Scalar = Scalar->getOperand(0);
12092
12093       EVT SclTy = Scalar->getValueType(0);
12094
12095       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12096         return SDValue();
12097
12098       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12099                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12100       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12101         return SDValue();
12102
12103       SDLoc dl = SDLoc(N);
12104       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12105       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12106     }
12107   }
12108
12109   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12110   // We have already tested above for an UNDEF only concatenation.
12111   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12112   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12113   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12114     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12115   };
12116   bool AllBuildVectorsOrUndefs =
12117       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12118   if (AllBuildVectorsOrUndefs) {
12119     SmallVector<SDValue, 8> Opnds;
12120     EVT SVT = VT.getScalarType();
12121
12122     EVT MinVT = SVT;
12123     if (!SVT.isFloatingPoint()) {
12124       // If BUILD_VECTOR are from built from integer, they may have different
12125       // operand types. Get the smallest type and truncate all operands to it.
12126       bool FoundMinVT = false;
12127       for (const SDValue &Op : N->ops())
12128         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12129           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12130           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12131           FoundMinVT = true;
12132         }
12133       assert(FoundMinVT && "Concat vector type mismatch");
12134     }
12135
12136     for (const SDValue &Op : N->ops()) {
12137       EVT OpVT = Op.getValueType();
12138       unsigned NumElts = OpVT.getVectorNumElements();
12139
12140       if (ISD::UNDEF == Op.getOpcode())
12141         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12142
12143       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12144         if (SVT.isFloatingPoint()) {
12145           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12146           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12147         } else {
12148           for (unsigned i = 0; i != NumElts; ++i)
12149             Opnds.push_back(
12150                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12151         }
12152       }
12153     }
12154
12155     assert(VT.getVectorNumElements() == Opnds.size() &&
12156            "Concat vector type mismatch");
12157     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12158   }
12159
12160   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12161   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12162     return V;
12163
12164   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12165   // nodes often generate nop CONCAT_VECTOR nodes.
12166   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12167   // place the incoming vectors at the exact same location.
12168   SDValue SingleSource = SDValue();
12169   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12170
12171   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12172     SDValue Op = N->getOperand(i);
12173
12174     if (Op.getOpcode() == ISD::UNDEF)
12175       continue;
12176
12177     // Check if this is the identity extract:
12178     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12179       return SDValue();
12180
12181     // Find the single incoming vector for the extract_subvector.
12182     if (SingleSource.getNode()) {
12183       if (Op.getOperand(0) != SingleSource)
12184         return SDValue();
12185     } else {
12186       SingleSource = Op.getOperand(0);
12187
12188       // Check the source type is the same as the type of the result.
12189       // If not, this concat may extend the vector, so we can not
12190       // optimize it away.
12191       if (SingleSource.getValueType() != N->getValueType(0))
12192         return SDValue();
12193     }
12194
12195     unsigned IdentityIndex = i * PartNumElem;
12196     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12197     // The extract index must be constant.
12198     if (!CS)
12199       return SDValue();
12200
12201     // Check that we are reading from the identity index.
12202     if (CS->getZExtValue() != IdentityIndex)
12203       return SDValue();
12204   }
12205
12206   if (SingleSource.getNode())
12207     return SingleSource;
12208
12209   return SDValue();
12210 }
12211
12212 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12213   EVT NVT = N->getValueType(0);
12214   SDValue V = N->getOperand(0);
12215
12216   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12217     // Combine:
12218     //    (extract_subvec (concat V1, V2, ...), i)
12219     // Into:
12220     //    Vi if possible
12221     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12222     // type.
12223     if (V->getOperand(0).getValueType() != NVT)
12224       return SDValue();
12225     unsigned Idx = N->getConstantOperandVal(1);
12226     unsigned NumElems = NVT.getVectorNumElements();
12227     assert((Idx % NumElems) == 0 &&
12228            "IDX in concat is not a multiple of the result vector length.");
12229     return V->getOperand(Idx / NumElems);
12230   }
12231
12232   // Skip bitcasting
12233   if (V->getOpcode() == ISD::BITCAST)
12234     V = V.getOperand(0);
12235
12236   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12237     SDLoc dl(N);
12238     // Handle only simple case where vector being inserted and vector
12239     // being extracted are of same type, and are half size of larger vectors.
12240     EVT BigVT = V->getOperand(0).getValueType();
12241     EVT SmallVT = V->getOperand(1).getValueType();
12242     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12243       return SDValue();
12244
12245     // Only handle cases where both indexes are constants with the same type.
12246     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12247     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12248
12249     if (InsIdx && ExtIdx &&
12250         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12251         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12252       // Combine:
12253       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12254       // Into:
12255       //    indices are equal or bit offsets are equal => V1
12256       //    otherwise => (extract_subvec V1, ExtIdx)
12257       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12258           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12259         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12260       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12261                          DAG.getNode(ISD::BITCAST, dl,
12262                                      N->getOperand(0).getValueType(),
12263                                      V->getOperand(0)), N->getOperand(1));
12264     }
12265   }
12266
12267   return SDValue();
12268 }
12269
12270 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12271                                                  SDValue V, SelectionDAG &DAG) {
12272   SDLoc DL(V);
12273   EVT VT = V.getValueType();
12274
12275   switch (V.getOpcode()) {
12276   default:
12277     return V;
12278
12279   case ISD::CONCAT_VECTORS: {
12280     EVT OpVT = V->getOperand(0).getValueType();
12281     int OpSize = OpVT.getVectorNumElements();
12282     SmallBitVector OpUsedElements(OpSize, false);
12283     bool FoundSimplification = false;
12284     SmallVector<SDValue, 4> NewOps;
12285     NewOps.reserve(V->getNumOperands());
12286     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12287       SDValue Op = V->getOperand(i);
12288       bool OpUsed = false;
12289       for (int j = 0; j < OpSize; ++j)
12290         if (UsedElements[i * OpSize + j]) {
12291           OpUsedElements[j] = true;
12292           OpUsed = true;
12293         }
12294       NewOps.push_back(
12295           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12296                  : DAG.getUNDEF(OpVT));
12297       FoundSimplification |= Op == NewOps.back();
12298       OpUsedElements.reset();
12299     }
12300     if (FoundSimplification)
12301       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12302     return V;
12303   }
12304
12305   case ISD::INSERT_SUBVECTOR: {
12306     SDValue BaseV = V->getOperand(0);
12307     SDValue SubV = V->getOperand(1);
12308     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12309     if (!IdxN)
12310       return V;
12311
12312     int SubSize = SubV.getValueType().getVectorNumElements();
12313     int Idx = IdxN->getZExtValue();
12314     bool SubVectorUsed = false;
12315     SmallBitVector SubUsedElements(SubSize, false);
12316     for (int i = 0; i < SubSize; ++i)
12317       if (UsedElements[i + Idx]) {
12318         SubVectorUsed = true;
12319         SubUsedElements[i] = true;
12320         UsedElements[i + Idx] = false;
12321       }
12322
12323     // Now recurse on both the base and sub vectors.
12324     SDValue SimplifiedSubV =
12325         SubVectorUsed
12326             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12327             : DAG.getUNDEF(SubV.getValueType());
12328     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12329     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12330       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12331                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12332     return V;
12333   }
12334   }
12335 }
12336
12337 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12338                                        SDValue N1, SelectionDAG &DAG) {
12339   EVT VT = SVN->getValueType(0);
12340   int NumElts = VT.getVectorNumElements();
12341   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12342   for (int M : SVN->getMask())
12343     if (M >= 0 && M < NumElts)
12344       N0UsedElements[M] = true;
12345     else if (M >= NumElts)
12346       N1UsedElements[M - NumElts] = true;
12347
12348   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12349   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12350   if (S0 == N0 && S1 == N1)
12351     return SDValue();
12352
12353   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12354 }
12355
12356 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12357 // or turn a shuffle of a single concat into simpler shuffle then concat.
12358 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12359   EVT VT = N->getValueType(0);
12360   unsigned NumElts = VT.getVectorNumElements();
12361
12362   SDValue N0 = N->getOperand(0);
12363   SDValue N1 = N->getOperand(1);
12364   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12365
12366   SmallVector<SDValue, 4> Ops;
12367   EVT ConcatVT = N0.getOperand(0).getValueType();
12368   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12369   unsigned NumConcats = NumElts / NumElemsPerConcat;
12370
12371   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12372   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12373   // half vector elements.
12374   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12375       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12376                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12377     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12378                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12379     N1 = DAG.getUNDEF(ConcatVT);
12380     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12381   }
12382
12383   // Look at every vector that's inserted. We're looking for exact
12384   // subvector-sized copies from a concatenated vector
12385   for (unsigned I = 0; I != NumConcats; ++I) {
12386     // Make sure we're dealing with a copy.
12387     unsigned Begin = I * NumElemsPerConcat;
12388     bool AllUndef = true, NoUndef = true;
12389     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12390       if (SVN->getMaskElt(J) >= 0)
12391         AllUndef = false;
12392       else
12393         NoUndef = false;
12394     }
12395
12396     if (NoUndef) {
12397       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12398         return SDValue();
12399
12400       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12401         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12402           return SDValue();
12403
12404       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12405       if (FirstElt < N0.getNumOperands())
12406         Ops.push_back(N0.getOperand(FirstElt));
12407       else
12408         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12409
12410     } else if (AllUndef) {
12411       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12412     } else { // Mixed with general masks and undefs, can't do optimization.
12413       return SDValue();
12414     }
12415   }
12416
12417   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12418 }
12419
12420 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12421   EVT VT = N->getValueType(0);
12422   unsigned NumElts = VT.getVectorNumElements();
12423
12424   SDValue N0 = N->getOperand(0);
12425   SDValue N1 = N->getOperand(1);
12426
12427   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12428
12429   // Canonicalize shuffle undef, undef -> undef
12430   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12431     return DAG.getUNDEF(VT);
12432
12433   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12434
12435   // Canonicalize shuffle v, v -> v, undef
12436   if (N0 == N1) {
12437     SmallVector<int, 8> NewMask;
12438     for (unsigned i = 0; i != NumElts; ++i) {
12439       int Idx = SVN->getMaskElt(i);
12440       if (Idx >= (int)NumElts) Idx -= NumElts;
12441       NewMask.push_back(Idx);
12442     }
12443     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12444                                 &NewMask[0]);
12445   }
12446
12447   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12448   if (N0.getOpcode() == ISD::UNDEF) {
12449     SmallVector<int, 8> NewMask;
12450     for (unsigned i = 0; i != NumElts; ++i) {
12451       int Idx = SVN->getMaskElt(i);
12452       if (Idx >= 0) {
12453         if (Idx >= (int)NumElts)
12454           Idx -= NumElts;
12455         else
12456           Idx = -1; // remove reference to lhs
12457       }
12458       NewMask.push_back(Idx);
12459     }
12460     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12461                                 &NewMask[0]);
12462   }
12463
12464   // Remove references to rhs if it is undef
12465   if (N1.getOpcode() == ISD::UNDEF) {
12466     bool Changed = false;
12467     SmallVector<int, 8> NewMask;
12468     for (unsigned i = 0; i != NumElts; ++i) {
12469       int Idx = SVN->getMaskElt(i);
12470       if (Idx >= (int)NumElts) {
12471         Idx = -1;
12472         Changed = true;
12473       }
12474       NewMask.push_back(Idx);
12475     }
12476     if (Changed)
12477       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12478   }
12479
12480   // If it is a splat, check if the argument vector is another splat or a
12481   // build_vector.
12482   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12483     SDNode *V = N0.getNode();
12484
12485     // If this is a bit convert that changes the element type of the vector but
12486     // not the number of vector elements, look through it.  Be careful not to
12487     // look though conversions that change things like v4f32 to v2f64.
12488     if (V->getOpcode() == ISD::BITCAST) {
12489       SDValue ConvInput = V->getOperand(0);
12490       if (ConvInput.getValueType().isVector() &&
12491           ConvInput.getValueType().getVectorNumElements() == NumElts)
12492         V = ConvInput.getNode();
12493     }
12494
12495     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12496       assert(V->getNumOperands() == NumElts &&
12497              "BUILD_VECTOR has wrong number of operands");
12498       SDValue Base;
12499       bool AllSame = true;
12500       for (unsigned i = 0; i != NumElts; ++i) {
12501         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12502           Base = V->getOperand(i);
12503           break;
12504         }
12505       }
12506       // Splat of <u, u, u, u>, return <u, u, u, u>
12507       if (!Base.getNode())
12508         return N0;
12509       for (unsigned i = 0; i != NumElts; ++i) {
12510         if (V->getOperand(i) != Base) {
12511           AllSame = false;
12512           break;
12513         }
12514       }
12515       // Splat of <x, x, x, x>, return <x, x, x, x>
12516       if (AllSame)
12517         return N0;
12518
12519       // Canonicalize any other splat as a build_vector.
12520       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12521       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12522       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12523                                   V->getValueType(0), Ops);
12524
12525       // We may have jumped through bitcasts, so the type of the
12526       // BUILD_VECTOR may not match the type of the shuffle.
12527       if (V->getValueType(0) != VT)
12528         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12529       return NewBV;
12530     }
12531   }
12532
12533   // There are various patterns used to build up a vector from smaller vectors,
12534   // subvectors, or elements. Scan chains of these and replace unused insertions
12535   // or components with undef.
12536   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12537     return S;
12538
12539   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12540       Level < AfterLegalizeVectorOps &&
12541       (N1.getOpcode() == ISD::UNDEF ||
12542       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12543        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12544     SDValue V = partitionShuffleOfConcats(N, DAG);
12545
12546     if (V.getNode())
12547       return V;
12548   }
12549
12550   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12551   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12552   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12553     SmallVector<SDValue, 8> Ops;
12554     for (int M : SVN->getMask()) {
12555       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12556       if (M >= 0) {
12557         int Idx = M % NumElts;
12558         SDValue &S = (M < (int)NumElts ? N0 : N1);
12559         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12560           Op = S.getOperand(Idx);
12561         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12562           if (Idx == 0)
12563             Op = S.getOperand(0);
12564         } else {
12565           // Operand can't be combined - bail out.
12566           break;
12567         }
12568       }
12569       Ops.push_back(Op);
12570     }
12571     if (Ops.size() == VT.getVectorNumElements()) {
12572       // BUILD_VECTOR requires all inputs to be of the same type, find the
12573       // maximum type and extend them all.
12574       EVT SVT = VT.getScalarType();
12575       if (SVT.isInteger())
12576         for (SDValue &Op : Ops)
12577           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12578       if (SVT != VT.getScalarType())
12579         for (SDValue &Op : Ops)
12580           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12581                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12582                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12583       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12584     }
12585   }
12586
12587   // If this shuffle only has a single input that is a bitcasted shuffle,
12588   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12589   // back to their original types.
12590   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12591       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12592       TLI.isTypeLegal(VT)) {
12593
12594     // Peek through the bitcast only if there is one user.
12595     SDValue BC0 = N0;
12596     while (BC0.getOpcode() == ISD::BITCAST) {
12597       if (!BC0.hasOneUse())
12598         break;
12599       BC0 = BC0.getOperand(0);
12600     }
12601
12602     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12603       if (Scale == 1)
12604         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12605
12606       SmallVector<int, 8> NewMask;
12607       for (int M : Mask)
12608         for (int s = 0; s != Scale; ++s)
12609           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12610       return NewMask;
12611     };
12612
12613     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12614       EVT SVT = VT.getScalarType();
12615       EVT InnerVT = BC0->getValueType(0);
12616       EVT InnerSVT = InnerVT.getScalarType();
12617
12618       // Determine which shuffle works with the smaller scalar type.
12619       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12620       EVT ScaleSVT = ScaleVT.getScalarType();
12621
12622       if (TLI.isTypeLegal(ScaleVT) &&
12623           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12624           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12625
12626         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12627         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12628
12629         // Scale the shuffle masks to the smaller scalar type.
12630         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12631         SmallVector<int, 8> InnerMask =
12632             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12633         SmallVector<int, 8> OuterMask =
12634             ScaleShuffleMask(SVN->getMask(), OuterScale);
12635
12636         // Merge the shuffle masks.
12637         SmallVector<int, 8> NewMask;
12638         for (int M : OuterMask)
12639           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12640
12641         // Test for shuffle mask legality over both commutations.
12642         SDValue SV0 = BC0->getOperand(0);
12643         SDValue SV1 = BC0->getOperand(1);
12644         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12645         if (!LegalMask) {
12646           std::swap(SV0, SV1);
12647           ShuffleVectorSDNode::commuteMask(NewMask);
12648           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12649         }
12650
12651         if (LegalMask) {
12652           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12653           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12654           return DAG.getNode(
12655               ISD::BITCAST, SDLoc(N), VT,
12656               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12657         }
12658       }
12659     }
12660   }
12661
12662   // Canonicalize shuffles according to rules:
12663   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12664   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12665   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12666   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12667       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12668       TLI.isTypeLegal(VT)) {
12669     // The incoming shuffle must be of the same type as the result of the
12670     // current shuffle.
12671     assert(N1->getOperand(0).getValueType() == VT &&
12672            "Shuffle types don't match");
12673
12674     SDValue SV0 = N1->getOperand(0);
12675     SDValue SV1 = N1->getOperand(1);
12676     bool HasSameOp0 = N0 == SV0;
12677     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12678     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12679       // Commute the operands of this shuffle so that next rule
12680       // will trigger.
12681       return DAG.getCommutedVectorShuffle(*SVN);
12682   }
12683
12684   // Try to fold according to rules:
12685   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12686   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12687   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12688   // Don't try to fold shuffles with illegal type.
12689   // Only fold if this shuffle is the only user of the other shuffle.
12690   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12691       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12692     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12693
12694     // The incoming shuffle must be of the same type as the result of the
12695     // current shuffle.
12696     assert(OtherSV->getOperand(0).getValueType() == VT &&
12697            "Shuffle types don't match");
12698
12699     SDValue SV0, SV1;
12700     SmallVector<int, 4> Mask;
12701     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12702     // operand, and SV1 as the second operand.
12703     for (unsigned i = 0; i != NumElts; ++i) {
12704       int Idx = SVN->getMaskElt(i);
12705       if (Idx < 0) {
12706         // Propagate Undef.
12707         Mask.push_back(Idx);
12708         continue;
12709       }
12710
12711       SDValue CurrentVec;
12712       if (Idx < (int)NumElts) {
12713         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12714         // shuffle mask to identify which vector is actually referenced.
12715         Idx = OtherSV->getMaskElt(Idx);
12716         if (Idx < 0) {
12717           // Propagate Undef.
12718           Mask.push_back(Idx);
12719           continue;
12720         }
12721
12722         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12723                                            : OtherSV->getOperand(1);
12724       } else {
12725         // This shuffle index references an element within N1.
12726         CurrentVec = N1;
12727       }
12728
12729       // Simple case where 'CurrentVec' is UNDEF.
12730       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12731         Mask.push_back(-1);
12732         continue;
12733       }
12734
12735       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12736       // will be the first or second operand of the combined shuffle.
12737       Idx = Idx % NumElts;
12738       if (!SV0.getNode() || SV0 == CurrentVec) {
12739         // Ok. CurrentVec is the left hand side.
12740         // Update the mask accordingly.
12741         SV0 = CurrentVec;
12742         Mask.push_back(Idx);
12743         continue;
12744       }
12745
12746       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12747       if (SV1.getNode() && SV1 != CurrentVec)
12748         return SDValue();
12749
12750       // Ok. CurrentVec is the right hand side.
12751       // Update the mask accordingly.
12752       SV1 = CurrentVec;
12753       Mask.push_back(Idx + NumElts);
12754     }
12755
12756     // Check if all indices in Mask are Undef. In case, propagate Undef.
12757     bool isUndefMask = true;
12758     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12759       isUndefMask &= Mask[i] < 0;
12760
12761     if (isUndefMask)
12762       return DAG.getUNDEF(VT);
12763
12764     if (!SV0.getNode())
12765       SV0 = DAG.getUNDEF(VT);
12766     if (!SV1.getNode())
12767       SV1 = DAG.getUNDEF(VT);
12768
12769     // Avoid introducing shuffles with illegal mask.
12770     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12771       ShuffleVectorSDNode::commuteMask(Mask);
12772
12773       if (!TLI.isShuffleMaskLegal(Mask, VT))
12774         return SDValue();
12775
12776       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12777       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12778       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12779       std::swap(SV0, SV1);
12780     }
12781
12782     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12783     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12784     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12785     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12786   }
12787
12788   return SDValue();
12789 }
12790
12791 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12792   SDValue InVal = N->getOperand(0);
12793   EVT VT = N->getValueType(0);
12794
12795   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12796   // with a VECTOR_SHUFFLE.
12797   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12798     SDValue InVec = InVal->getOperand(0);
12799     SDValue EltNo = InVal->getOperand(1);
12800
12801     // FIXME: We could support implicit truncation if the shuffle can be
12802     // scaled to a smaller vector scalar type.
12803     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12804     if (C0 && VT == InVec.getValueType() &&
12805         VT.getScalarType() == InVal.getValueType()) {
12806       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12807       int Elt = C0->getZExtValue();
12808       NewMask[0] = Elt;
12809
12810       if (TLI.isShuffleMaskLegal(NewMask, VT))
12811         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12812                                     NewMask);
12813     }
12814   }
12815
12816   return SDValue();
12817 }
12818
12819 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12820   SDValue N0 = N->getOperand(0);
12821   SDValue N2 = N->getOperand(2);
12822
12823   // If the input vector is a concatenation, and the insert replaces
12824   // one of the halves, we can optimize into a single concat_vectors.
12825   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12826       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12827     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12828     EVT VT = N->getValueType(0);
12829
12830     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12831     // (concat_vectors Z, Y)
12832     if (InsIdx == 0)
12833       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12834                          N->getOperand(1), N0.getOperand(1));
12835
12836     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12837     // (concat_vectors X, Z)
12838     if (InsIdx == VT.getVectorNumElements()/2)
12839       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12840                          N0.getOperand(0), N->getOperand(1));
12841   }
12842
12843   return SDValue();
12844 }
12845
12846 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12847   SDValue N0 = N->getOperand(0);
12848
12849   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12850   if (N0->getOpcode() == ISD::FP16_TO_FP)
12851     return N0->getOperand(0);
12852
12853   return SDValue();
12854 }
12855
12856 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12857 /// with the destination vector and a zero vector.
12858 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12859 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12860 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12861   EVT VT = N->getValueType(0);
12862   SDValue LHS = N->getOperand(0);
12863   SDValue RHS = N->getOperand(1);
12864   SDLoc dl(N);
12865
12866   // Make sure we're not running after operation legalization where it 
12867   // may have custom lowered the vector shuffles.
12868   if (LegalOperations)
12869     return SDValue();
12870
12871   if (N->getOpcode() != ISD::AND)
12872     return SDValue();
12873
12874   if (RHS.getOpcode() == ISD::BITCAST)
12875     RHS = RHS.getOperand(0);
12876
12877   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12878     SmallVector<int, 8> Indices;
12879     unsigned NumElts = RHS.getNumOperands();
12880
12881     for (unsigned i = 0; i != NumElts; ++i) {
12882       SDValue Elt = RHS.getOperand(i);
12883       if (!isa<ConstantSDNode>(Elt))
12884         return SDValue();
12885
12886       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12887         Indices.push_back(i);
12888       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12889         Indices.push_back(NumElts+i);
12890       else
12891         return SDValue();
12892     }
12893
12894     // Let's see if the target supports this vector_shuffle.
12895     EVT RVT = RHS.getValueType();
12896     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12897       return SDValue();
12898
12899     // Return the new VECTOR_SHUFFLE node.
12900     EVT EltVT = RVT.getVectorElementType();
12901     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12902                                    DAG.getConstant(0, dl, EltVT));
12903     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12904     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12905     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12906     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12907   }
12908
12909   return SDValue();
12910 }
12911
12912 /// Visit a binary vector operation, like ADD.
12913 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12914   assert(N->getValueType(0).isVector() &&
12915          "SimplifyVBinOp only works on vectors!");
12916
12917   SDValue LHS = N->getOperand(0);
12918   SDValue RHS = N->getOperand(1);
12919
12920   if (SDValue Shuffle = XformToShuffleWithZero(N))
12921     return Shuffle;
12922
12923   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12924   // this operation.
12925   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12926       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12927     // Check if both vectors are constants. If not bail out.
12928     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12929           cast<BuildVectorSDNode>(RHS)->isConstant()))
12930       return SDValue();
12931
12932     SmallVector<SDValue, 8> Ops;
12933     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12934       SDValue LHSOp = LHS.getOperand(i);
12935       SDValue RHSOp = RHS.getOperand(i);
12936
12937       // Can't fold divide by zero.
12938       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12939           N->getOpcode() == ISD::FDIV) {
12940         if ((RHSOp.getOpcode() == ISD::Constant &&
12941              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12942             (RHSOp.getOpcode() == ISD::ConstantFP &&
12943              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12944           break;
12945       }
12946
12947       EVT VT = LHSOp.getValueType();
12948       EVT RVT = RHSOp.getValueType();
12949       if (RVT != VT) {
12950         // Integer BUILD_VECTOR operands may have types larger than the element
12951         // size (e.g., when the element type is not legal).  Prior to type
12952         // legalization, the types may not match between the two BUILD_VECTORS.
12953         // Truncate one of the operands to make them match.
12954         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12955           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12956         } else {
12957           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12958           VT = RVT;
12959         }
12960       }
12961       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12962                                    LHSOp, RHSOp);
12963       if (FoldOp.getOpcode() != ISD::UNDEF &&
12964           FoldOp.getOpcode() != ISD::Constant &&
12965           FoldOp.getOpcode() != ISD::ConstantFP)
12966         break;
12967       Ops.push_back(FoldOp);
12968       AddToWorklist(FoldOp.getNode());
12969     }
12970
12971     if (Ops.size() == LHS.getNumOperands())
12972       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12973   }
12974
12975   // Type legalization might introduce new shuffles in the DAG.
12976   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12977   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12978   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12979       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12980       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12981       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12982     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12983     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12984
12985     if (SVN0->getMask().equals(SVN1->getMask())) {
12986       EVT VT = N->getValueType(0);
12987       SDValue UndefVector = LHS.getOperand(1);
12988       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12989                                      LHS.getOperand(0), RHS.getOperand(0));
12990       AddUsersToWorklist(N);
12991       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12992                                   &SVN0->getMask()[0]);
12993     }
12994   }
12995
12996   return SDValue();
12997 }
12998
12999 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13000                                     SDValue N1, SDValue N2){
13001   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13002
13003   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13004                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13005
13006   // If we got a simplified select_cc node back from SimplifySelectCC, then
13007   // break it down into a new SETCC node, and a new SELECT node, and then return
13008   // the SELECT node, since we were called with a SELECT node.
13009   if (SCC.getNode()) {
13010     // Check to see if we got a select_cc back (to turn into setcc/select).
13011     // Otherwise, just return whatever node we got back, like fabs.
13012     if (SCC.getOpcode() == ISD::SELECT_CC) {
13013       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13014                                   N0.getValueType(),
13015                                   SCC.getOperand(0), SCC.getOperand(1),
13016                                   SCC.getOperand(4));
13017       AddToWorklist(SETCC.getNode());
13018       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13019                            SCC.getOperand(2), SCC.getOperand(3));
13020     }
13021
13022     return SCC;
13023   }
13024   return SDValue();
13025 }
13026
13027 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13028 /// being selected between, see if we can simplify the select.  Callers of this
13029 /// should assume that TheSelect is deleted if this returns true.  As such, they
13030 /// should return the appropriate thing (e.g. the node) back to the top-level of
13031 /// the DAG combiner loop to avoid it being looked at.
13032 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13033                                     SDValue RHS) {
13034
13035   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13036   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13037   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13038     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13039       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13040       SDValue Sqrt = RHS;
13041       ISD::CondCode CC;
13042       SDValue CmpLHS;
13043       const ConstantFPSDNode *NegZero = nullptr;
13044
13045       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13046         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13047         CmpLHS = TheSelect->getOperand(0);
13048         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13049       } else {
13050         // SELECT or VSELECT
13051         SDValue Cmp = TheSelect->getOperand(0);
13052         if (Cmp.getOpcode() == ISD::SETCC) {
13053           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13054           CmpLHS = Cmp.getOperand(0);
13055           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13056         }
13057       }
13058       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13059           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13060           CC == ISD::SETULT || CC == ISD::SETLT)) {
13061         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13062         CombineTo(TheSelect, Sqrt);
13063         return true;
13064       }
13065     }
13066   }
13067   // Cannot simplify select with vector condition
13068   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13069
13070   // If this is a select from two identical things, try to pull the operation
13071   // through the select.
13072   if (LHS.getOpcode() != RHS.getOpcode() ||
13073       !LHS.hasOneUse() || !RHS.hasOneUse())
13074     return false;
13075
13076   // If this is a load and the token chain is identical, replace the select
13077   // of two loads with a load through a select of the address to load from.
13078   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13079   // constants have been dropped into the constant pool.
13080   if (LHS.getOpcode() == ISD::LOAD) {
13081     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13082     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13083
13084     // Token chains must be identical.
13085     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13086         // Do not let this transformation reduce the number of volatile loads.
13087         LLD->isVolatile() || RLD->isVolatile() ||
13088         // FIXME: If either is a pre/post inc/dec load,
13089         // we'd need to split out the address adjustment.
13090         LLD->isIndexed() || RLD->isIndexed() ||
13091         // If this is an EXTLOAD, the VT's must match.
13092         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13093         // If this is an EXTLOAD, the kind of extension must match.
13094         (LLD->getExtensionType() != RLD->getExtensionType() &&
13095          // The only exception is if one of the extensions is anyext.
13096          LLD->getExtensionType() != ISD::EXTLOAD &&
13097          RLD->getExtensionType() != ISD::EXTLOAD) ||
13098         // FIXME: this discards src value information.  This is
13099         // over-conservative. It would be beneficial to be able to remember
13100         // both potential memory locations.  Since we are discarding
13101         // src value info, don't do the transformation if the memory
13102         // locations are not in the default address space.
13103         LLD->getPointerInfo().getAddrSpace() != 0 ||
13104         RLD->getPointerInfo().getAddrSpace() != 0 ||
13105         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13106                                       LLD->getBasePtr().getValueType()))
13107       return false;
13108
13109     // Check that the select condition doesn't reach either load.  If so,
13110     // folding this will induce a cycle into the DAG.  If not, this is safe to
13111     // xform, so create a select of the addresses.
13112     SDValue Addr;
13113     if (TheSelect->getOpcode() == ISD::SELECT) {
13114       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13115       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13116           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13117         return false;
13118       // The loads must not depend on one another.
13119       if (LLD->isPredecessorOf(RLD) ||
13120           RLD->isPredecessorOf(LLD))
13121         return false;
13122       Addr = DAG.getSelect(SDLoc(TheSelect),
13123                            LLD->getBasePtr().getValueType(),
13124                            TheSelect->getOperand(0), LLD->getBasePtr(),
13125                            RLD->getBasePtr());
13126     } else {  // Otherwise SELECT_CC
13127       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13128       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13129
13130       if ((LLD->hasAnyUseOfValue(1) &&
13131            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13132           (RLD->hasAnyUseOfValue(1) &&
13133            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13134         return false;
13135
13136       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13137                          LLD->getBasePtr().getValueType(),
13138                          TheSelect->getOperand(0),
13139                          TheSelect->getOperand(1),
13140                          LLD->getBasePtr(), RLD->getBasePtr(),
13141                          TheSelect->getOperand(4));
13142     }
13143
13144     SDValue Load;
13145     // It is safe to replace the two loads if they have different alignments,
13146     // but the new load must be the minimum (most restrictive) alignment of the
13147     // inputs.
13148     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13149     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13150     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13151       Load = DAG.getLoad(TheSelect->getValueType(0),
13152                          SDLoc(TheSelect),
13153                          // FIXME: Discards pointer and AA info.
13154                          LLD->getChain(), Addr, MachinePointerInfo(),
13155                          LLD->isVolatile(), LLD->isNonTemporal(),
13156                          isInvariant, Alignment);
13157     } else {
13158       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13159                             RLD->getExtensionType() : LLD->getExtensionType(),
13160                             SDLoc(TheSelect),
13161                             TheSelect->getValueType(0),
13162                             // FIXME: Discards pointer and AA info.
13163                             LLD->getChain(), Addr, MachinePointerInfo(),
13164                             LLD->getMemoryVT(), LLD->isVolatile(),
13165                             LLD->isNonTemporal(), isInvariant, Alignment);
13166     }
13167
13168     // Users of the select now use the result of the load.
13169     CombineTo(TheSelect, Load);
13170
13171     // Users of the old loads now use the new load's chain.  We know the
13172     // old-load value is dead now.
13173     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13174     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13175     return true;
13176   }
13177
13178   return false;
13179 }
13180
13181 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13182 /// where 'cond' is the comparison specified by CC.
13183 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13184                                       SDValue N2, SDValue N3,
13185                                       ISD::CondCode CC, bool NotExtCompare) {
13186   // (x ? y : y) -> y.
13187   if (N2 == N3) return N2;
13188
13189   EVT VT = N2.getValueType();
13190   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13191   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13192   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13193
13194   // Determine if the condition we're dealing with is constant
13195   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13196                               N0, N1, CC, DL, false);
13197   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13198   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13199
13200   // fold select_cc true, x, y -> x
13201   if (SCCC && !SCCC->isNullValue())
13202     return N2;
13203   // fold select_cc false, x, y -> y
13204   if (SCCC && SCCC->isNullValue())
13205     return N3;
13206
13207   // Check to see if we can simplify the select into an fabs node
13208   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13209     // Allow either -0.0 or 0.0
13210     if (CFP->getValueAPF().isZero()) {
13211       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13212       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13213           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13214           N2 == N3.getOperand(0))
13215         return DAG.getNode(ISD::FABS, DL, VT, N0);
13216
13217       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13218       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13219           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13220           N2.getOperand(0) == N3)
13221         return DAG.getNode(ISD::FABS, DL, VT, N3);
13222     }
13223   }
13224
13225   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13226   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13227   // in it.  This is a win when the constant is not otherwise available because
13228   // it replaces two constant pool loads with one.  We only do this if the FP
13229   // type is known to be legal, because if it isn't, then we are before legalize
13230   // types an we want the other legalization to happen first (e.g. to avoid
13231   // messing with soft float) and if the ConstantFP is not legal, because if
13232   // it is legal, we may not need to store the FP constant in a constant pool.
13233   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13234     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13235       if (TLI.isTypeLegal(N2.getValueType()) &&
13236           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13237                TargetLowering::Legal &&
13238            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13239            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13240           // If both constants have multiple uses, then we won't need to do an
13241           // extra load, they are likely around in registers for other users.
13242           (TV->hasOneUse() || FV->hasOneUse())) {
13243         Constant *Elts[] = {
13244           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13245           const_cast<ConstantFP*>(TV->getConstantFPValue())
13246         };
13247         Type *FPTy = Elts[0]->getType();
13248         const DataLayout &TD = *TLI.getDataLayout();
13249
13250         // Create a ConstantArray of the two constants.
13251         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13252         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13253                                             TD.getPrefTypeAlignment(FPTy));
13254         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13255
13256         // Get the offsets to the 0 and 1 element of the array so that we can
13257         // select between them.
13258         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13259         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13260         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13261
13262         SDValue Cond = DAG.getSetCC(DL,
13263                                     getSetCCResultType(N0.getValueType()),
13264                                     N0, N1, CC);
13265         AddToWorklist(Cond.getNode());
13266         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13267                                           Cond, One, Zero);
13268         AddToWorklist(CstOffset.getNode());
13269         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13270                             CstOffset);
13271         AddToWorklist(CPIdx.getNode());
13272         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13273                            MachinePointerInfo::getConstantPool(), false,
13274                            false, false, Alignment);
13275       }
13276     }
13277
13278   // Check to see if we can perform the "gzip trick", transforming
13279   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13280   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13281       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13282        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13283     EVT XType = N0.getValueType();
13284     EVT AType = N2.getValueType();
13285     if (XType.bitsGE(AType)) {
13286       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13287       // single-bit constant.
13288       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13289         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13290         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13291         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13292                                        getShiftAmountTy(N0.getValueType()));
13293         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13294                                     XType, N0, ShCt);
13295         AddToWorklist(Shift.getNode());
13296
13297         if (XType.bitsGT(AType)) {
13298           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13299           AddToWorklist(Shift.getNode());
13300         }
13301
13302         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13303       }
13304
13305       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13306                                   XType, N0,
13307                                   DAG.getConstant(XType.getSizeInBits() - 1,
13308                                                   SDLoc(N0),
13309                                          getShiftAmountTy(N0.getValueType())));
13310       AddToWorklist(Shift.getNode());
13311
13312       if (XType.bitsGT(AType)) {
13313         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13314         AddToWorklist(Shift.getNode());
13315       }
13316
13317       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13318     }
13319   }
13320
13321   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13322   // where y is has a single bit set.
13323   // A plaintext description would be, we can turn the SELECT_CC into an AND
13324   // when the condition can be materialized as an all-ones register.  Any
13325   // single bit-test can be materialized as an all-ones register with
13326   // shift-left and shift-right-arith.
13327   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13328       N0->getValueType(0) == VT &&
13329       N1C && N1C->isNullValue() &&
13330       N2C && N2C->isNullValue()) {
13331     SDValue AndLHS = N0->getOperand(0);
13332     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13333     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13334       // Shift the tested bit over the sign bit.
13335       APInt AndMask = ConstAndRHS->getAPIntValue();
13336       SDValue ShlAmt =
13337         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13338                         getShiftAmountTy(AndLHS.getValueType()));
13339       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13340
13341       // Now arithmetic right shift it all the way over, so the result is either
13342       // all-ones, or zero.
13343       SDValue ShrAmt =
13344         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13345                         getShiftAmountTy(Shl.getValueType()));
13346       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13347
13348       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13349     }
13350   }
13351
13352   // fold select C, 16, 0 -> shl C, 4
13353   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13354       TLI.getBooleanContents(N0.getValueType()) ==
13355           TargetLowering::ZeroOrOneBooleanContent) {
13356
13357     // If the caller doesn't want us to simplify this into a zext of a compare,
13358     // don't do it.
13359     if (NotExtCompare && N2C->getAPIntValue() == 1)
13360       return SDValue();
13361
13362     // Get a SetCC of the condition
13363     // NOTE: Don't create a SETCC if it's not legal on this target.
13364     if (!LegalOperations ||
13365         TLI.isOperationLegal(ISD::SETCC,
13366           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13367       SDValue Temp, SCC;
13368       // cast from setcc result type to select result type
13369       if (LegalTypes) {
13370         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13371                             N0, N1, CC);
13372         if (N2.getValueType().bitsLT(SCC.getValueType()))
13373           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13374                                         N2.getValueType());
13375         else
13376           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13377                              N2.getValueType(), SCC);
13378       } else {
13379         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13380         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13381                            N2.getValueType(), SCC);
13382       }
13383
13384       AddToWorklist(SCC.getNode());
13385       AddToWorklist(Temp.getNode());
13386
13387       if (N2C->getAPIntValue() == 1)
13388         return Temp;
13389
13390       // shl setcc result by log2 n2c
13391       return DAG.getNode(
13392           ISD::SHL, DL, N2.getValueType(), Temp,
13393           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13394                           getShiftAmountTy(Temp.getValueType())));
13395     }
13396   }
13397
13398   // Check to see if this is the equivalent of setcc
13399   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13400   // otherwise, go ahead with the folds.
13401   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13402     EVT XType = N0.getValueType();
13403     if (!LegalOperations ||
13404         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13405       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13406       if (Res.getValueType() != VT)
13407         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13408       return Res;
13409     }
13410
13411     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13412     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13413         (!LegalOperations ||
13414          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13415       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13416       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13417                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13418                                          SDLoc(Ctlz),
13419                                        getShiftAmountTy(Ctlz.getValueType())));
13420     }
13421     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13422     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13423       SDLoc DL(N0);
13424       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13425                                   XType, DAG.getConstant(0, DL, XType), N0);
13426       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13427       return DAG.getNode(ISD::SRL, DL, XType,
13428                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13429                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13430                                          getShiftAmountTy(XType)));
13431     }
13432     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13433     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13434       SDLoc DL(N0);
13435       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13436                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13437                                          getShiftAmountTy(N0.getValueType())));
13438       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13439                                                                     XType));
13440     }
13441   }
13442
13443   // Check to see if this is an integer abs.
13444   // select_cc setg[te] X,  0,  X, -X ->
13445   // select_cc setgt    X, -1,  X, -X ->
13446   // select_cc setl[te] X,  0, -X,  X ->
13447   // select_cc setlt    X,  1, -X,  X ->
13448   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13449   if (N1C) {
13450     ConstantSDNode *SubC = nullptr;
13451     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13452          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13453         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13454       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13455     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13456               (N1C->isOne() && CC == ISD::SETLT)) &&
13457              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13458       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13459
13460     EVT XType = N0.getValueType();
13461     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13462       SDLoc DL(N0);
13463       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13464                                   N0,
13465                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13466                                          getShiftAmountTy(N0.getValueType())));
13467       SDValue Add = DAG.getNode(ISD::ADD, DL,
13468                                 XType, N0, Shift);
13469       AddToWorklist(Shift.getNode());
13470       AddToWorklist(Add.getNode());
13471       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13472     }
13473   }
13474
13475   return SDValue();
13476 }
13477
13478 /// This is a stub for TargetLowering::SimplifySetCC.
13479 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13480                                    SDValue N1, ISD::CondCode Cond,
13481                                    SDLoc DL, bool foldBooleans) {
13482   TargetLowering::DAGCombinerInfo
13483     DagCombineInfo(DAG, Level, false, this);
13484   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13485 }
13486
13487 /// Given an ISD::SDIV node expressing a divide by constant, return
13488 /// a DAG expression to select that will generate the same value by multiplying
13489 /// by a magic number.
13490 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13491 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13492   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13493   if (!C)
13494     return SDValue();
13495
13496   // Avoid division by zero.
13497   if (!C->getAPIntValue())
13498     return SDValue();
13499
13500   std::vector<SDNode*> Built;
13501   SDValue S =
13502       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13503
13504   for (SDNode *N : Built)
13505     AddToWorklist(N);
13506   return S;
13507 }
13508
13509 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13510 /// DAG expression that will generate the same value by right shifting.
13511 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13512   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13513   if (!C)
13514     return SDValue();
13515
13516   // Avoid division by zero.
13517   if (!C->getAPIntValue())
13518     return SDValue();
13519
13520   std::vector<SDNode *> Built;
13521   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13522
13523   for (SDNode *N : Built)
13524     AddToWorklist(N);
13525   return S;
13526 }
13527
13528 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13529 /// expression that will generate the same value by multiplying by a magic
13530 /// number.
13531 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13532 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13533   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13534   if (!C)
13535     return SDValue();
13536
13537   // Avoid division by zero.
13538   if (!C->getAPIntValue())
13539     return SDValue();
13540
13541   std::vector<SDNode*> Built;
13542   SDValue S =
13543       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13544
13545   for (SDNode *N : Built)
13546     AddToWorklist(N);
13547   return S;
13548 }
13549
13550 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13551   if (Level >= AfterLegalizeDAG)
13552     return SDValue();
13553
13554   // Expose the DAG combiner to the target combiner implementations.
13555   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13556
13557   unsigned Iterations = 0;
13558   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13559     if (Iterations) {
13560       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13561       // For the reciprocal, we need to find the zero of the function:
13562       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13563       //     =>
13564       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13565       //     does not require additional intermediate precision]
13566       EVT VT = Op.getValueType();
13567       SDLoc DL(Op);
13568       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13569
13570       AddToWorklist(Est.getNode());
13571
13572       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13573       for (unsigned i = 0; i < Iterations; ++i) {
13574         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13575         AddToWorklist(NewEst.getNode());
13576
13577         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13578         AddToWorklist(NewEst.getNode());
13579
13580         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13581         AddToWorklist(NewEst.getNode());
13582
13583         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13584         AddToWorklist(Est.getNode());
13585       }
13586     }
13587     return Est;
13588   }
13589
13590   return SDValue();
13591 }
13592
13593 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13594 /// For the reciprocal sqrt, we need to find the zero of the function:
13595 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13596 ///     =>
13597 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13598 /// As a result, we precompute A/2 prior to the iteration loop.
13599 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13600                                           unsigned Iterations) {
13601   EVT VT = Arg.getValueType();
13602   SDLoc DL(Arg);
13603   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13604
13605   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13606   // this entire sequence requires only one FP constant.
13607   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13608   AddToWorklist(HalfArg.getNode());
13609
13610   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13611   AddToWorklist(HalfArg.getNode());
13612
13613   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13614   for (unsigned i = 0; i < Iterations; ++i) {
13615     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13616     AddToWorklist(NewEst.getNode());
13617
13618     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13619     AddToWorklist(NewEst.getNode());
13620
13621     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13622     AddToWorklist(NewEst.getNode());
13623
13624     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13625     AddToWorklist(Est.getNode());
13626   }
13627   return Est;
13628 }
13629
13630 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13631 /// For the reciprocal sqrt, we need to find the zero of the function:
13632 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13633 ///     =>
13634 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13635 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13636                                           unsigned Iterations) {
13637   EVT VT = Arg.getValueType();
13638   SDLoc DL(Arg);
13639   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13640   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13641
13642   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13643   for (unsigned i = 0; i < Iterations; ++i) {
13644     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13645     AddToWorklist(HalfEst.getNode());
13646
13647     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13648     AddToWorklist(Est.getNode());
13649
13650     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13651     AddToWorklist(Est.getNode());
13652
13653     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13654     AddToWorklist(Est.getNode());
13655
13656     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13657     AddToWorklist(Est.getNode());
13658   }
13659   return Est;
13660 }
13661
13662 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13663   if (Level >= AfterLegalizeDAG)
13664     return SDValue();
13665
13666   // Expose the DAG combiner to the target combiner implementations.
13667   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13668   unsigned Iterations = 0;
13669   bool UseOneConstNR = false;
13670   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13671     AddToWorklist(Est.getNode());
13672     if (Iterations) {
13673       Est = UseOneConstNR ?
13674         BuildRsqrtNROneConst(Op, Est, Iterations) :
13675         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13676     }
13677     return Est;
13678   }
13679
13680   return SDValue();
13681 }
13682
13683 /// Return true if base is a frame index, which is known not to alias with
13684 /// anything but itself.  Provides base object and offset as results.
13685 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13686                            const GlobalValue *&GV, const void *&CV) {
13687   // Assume it is a primitive operation.
13688   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13689
13690   // If it's an adding a simple constant then integrate the offset.
13691   if (Base.getOpcode() == ISD::ADD) {
13692     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13693       Base = Base.getOperand(0);
13694       Offset += C->getZExtValue();
13695     }
13696   }
13697
13698   // Return the underlying GlobalValue, and update the Offset.  Return false
13699   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13700   // by multiple nodes with different offsets.
13701   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13702     GV = G->getGlobal();
13703     Offset += G->getOffset();
13704     return false;
13705   }
13706
13707   // Return the underlying Constant value, and update the Offset.  Return false
13708   // for ConstantSDNodes since the same constant pool entry may be represented
13709   // by multiple nodes with different offsets.
13710   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13711     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13712                                          : (const void *)C->getConstVal();
13713     Offset += C->getOffset();
13714     return false;
13715   }
13716   // If it's any of the following then it can't alias with anything but itself.
13717   return isa<FrameIndexSDNode>(Base);
13718 }
13719
13720 /// Return true if there is any possibility that the two addresses overlap.
13721 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13722   // If they are the same then they must be aliases.
13723   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13724
13725   // If they are both volatile then they cannot be reordered.
13726   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13727
13728   // Gather base node and offset information.
13729   SDValue Base1, Base2;
13730   int64_t Offset1, Offset2;
13731   const GlobalValue *GV1, *GV2;
13732   const void *CV1, *CV2;
13733   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13734                                       Base1, Offset1, GV1, CV1);
13735   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13736                                       Base2, Offset2, GV2, CV2);
13737
13738   // If they have a same base address then check to see if they overlap.
13739   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13740     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13741              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13742
13743   // It is possible for different frame indices to alias each other, mostly
13744   // when tail call optimization reuses return address slots for arguments.
13745   // To catch this case, look up the actual index of frame indices to compute
13746   // the real alias relationship.
13747   if (isFrameIndex1 && isFrameIndex2) {
13748     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13749     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13750     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13751     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13752              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13753   }
13754
13755   // Otherwise, if we know what the bases are, and they aren't identical, then
13756   // we know they cannot alias.
13757   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13758     return false;
13759
13760   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13761   // compared to the size and offset of the access, we may be able to prove they
13762   // do not alias.  This check is conservative for now to catch cases created by
13763   // splitting vector types.
13764   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13765       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13766       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13767        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13768       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13769     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13770     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13771
13772     // There is no overlap between these relatively aligned accesses of similar
13773     // size, return no alias.
13774     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13775         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13776       return false;
13777   }
13778
13779   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13780                    ? CombinerGlobalAA
13781                    : DAG.getSubtarget().useAA();
13782 #ifndef NDEBUG
13783   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13784       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13785     UseAA = false;
13786 #endif
13787   if (UseAA &&
13788       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13789     // Use alias analysis information.
13790     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13791                                  Op1->getSrcValueOffset());
13792     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13793         Op0->getSrcValueOffset() - MinOffset;
13794     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13795         Op1->getSrcValueOffset() - MinOffset;
13796     AliasAnalysis::AliasResult AAResult =
13797         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13798                                          Overlap1,
13799                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13800                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13801                                          Overlap2,
13802                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13803     if (AAResult == AliasAnalysis::NoAlias)
13804       return false;
13805   }
13806
13807   // Otherwise we have to assume they alias.
13808   return true;
13809 }
13810
13811 /// Walk up chain skipping non-aliasing memory nodes,
13812 /// looking for aliasing nodes and adding them to the Aliases vector.
13813 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13814                                    SmallVectorImpl<SDValue> &Aliases) {
13815   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13816   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13817
13818   // Get alias information for node.
13819   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13820
13821   // Starting off.
13822   Chains.push_back(OriginalChain);
13823   unsigned Depth = 0;
13824
13825   // Look at each chain and determine if it is an alias.  If so, add it to the
13826   // aliases list.  If not, then continue up the chain looking for the next
13827   // candidate.
13828   while (!Chains.empty()) {
13829     SDValue Chain = Chains.back();
13830     Chains.pop_back();
13831
13832     // For TokenFactor nodes, look at each operand and only continue up the
13833     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13834     // find more and revert to original chain since the xform is unlikely to be
13835     // profitable.
13836     //
13837     // FIXME: The depth check could be made to return the last non-aliasing
13838     // chain we found before we hit a tokenfactor rather than the original
13839     // chain.
13840     if (Depth > 6 || Aliases.size() == 2) {
13841       Aliases.clear();
13842       Aliases.push_back(OriginalChain);
13843       return;
13844     }
13845
13846     // Don't bother if we've been before.
13847     if (!Visited.insert(Chain.getNode()).second)
13848       continue;
13849
13850     switch (Chain.getOpcode()) {
13851     case ISD::EntryToken:
13852       // Entry token is ideal chain operand, but handled in FindBetterChain.
13853       break;
13854
13855     case ISD::LOAD:
13856     case ISD::STORE: {
13857       // Get alias information for Chain.
13858       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13859           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13860
13861       // If chain is alias then stop here.
13862       if (!(IsLoad && IsOpLoad) &&
13863           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13864         Aliases.push_back(Chain);
13865       } else {
13866         // Look further up the chain.
13867         Chains.push_back(Chain.getOperand(0));
13868         ++Depth;
13869       }
13870       break;
13871     }
13872
13873     case ISD::TokenFactor:
13874       // We have to check each of the operands of the token factor for "small"
13875       // token factors, so we queue them up.  Adding the operands to the queue
13876       // (stack) in reverse order maintains the original order and increases the
13877       // likelihood that getNode will find a matching token factor (CSE.)
13878       if (Chain.getNumOperands() > 16) {
13879         Aliases.push_back(Chain);
13880         break;
13881       }
13882       for (unsigned n = Chain.getNumOperands(); n;)
13883         Chains.push_back(Chain.getOperand(--n));
13884       ++Depth;
13885       break;
13886
13887     default:
13888       // For all other instructions we will just have to take what we can get.
13889       Aliases.push_back(Chain);
13890       break;
13891     }
13892   }
13893
13894   // We need to be careful here to also search for aliases through the
13895   // value operand of a store, etc. Consider the following situation:
13896   //   Token1 = ...
13897   //   L1 = load Token1, %52
13898   //   S1 = store Token1, L1, %51
13899   //   L2 = load Token1, %52+8
13900   //   S2 = store Token1, L2, %51+8
13901   //   Token2 = Token(S1, S2)
13902   //   L3 = load Token2, %53
13903   //   S3 = store Token2, L3, %52
13904   //   L4 = load Token2, %53+8
13905   //   S4 = store Token2, L4, %52+8
13906   // If we search for aliases of S3 (which loads address %52), and we look
13907   // only through the chain, then we'll miss the trivial dependence on L1
13908   // (which also loads from %52). We then might change all loads and
13909   // stores to use Token1 as their chain operand, which could result in
13910   // copying %53 into %52 before copying %52 into %51 (which should
13911   // happen first).
13912   //
13913   // The problem is, however, that searching for such data dependencies
13914   // can become expensive, and the cost is not directly related to the
13915   // chain depth. Instead, we'll rule out such configurations here by
13916   // insisting that we've visited all chain users (except for users
13917   // of the original chain, which is not necessary). When doing this,
13918   // we need to look through nodes we don't care about (otherwise, things
13919   // like register copies will interfere with trivial cases).
13920
13921   SmallVector<const SDNode *, 16> Worklist;
13922   for (const SDNode *N : Visited)
13923     if (N != OriginalChain.getNode())
13924       Worklist.push_back(N);
13925
13926   while (!Worklist.empty()) {
13927     const SDNode *M = Worklist.pop_back_val();
13928
13929     // We have already visited M, and want to make sure we've visited any uses
13930     // of M that we care about. For uses that we've not visisted, and don't
13931     // care about, queue them to the worklist.
13932
13933     for (SDNode::use_iterator UI = M->use_begin(),
13934          UIE = M->use_end(); UI != UIE; ++UI)
13935       if (UI.getUse().getValueType() == MVT::Other &&
13936           Visited.insert(*UI).second) {
13937         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13938           // We've not visited this use, and we care about it (it could have an
13939           // ordering dependency with the original node).
13940           Aliases.clear();
13941           Aliases.push_back(OriginalChain);
13942           return;
13943         }
13944
13945         // We've not visited this use, but we don't care about it. Mark it as
13946         // visited and enqueue it to the worklist.
13947         Worklist.push_back(*UI);
13948       }
13949   }
13950 }
13951
13952 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13953 /// (aliasing node.)
13954 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13955   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13956
13957   // Accumulate all the aliases to this node.
13958   GatherAllAliases(N, OldChain, Aliases);
13959
13960   // If no operands then chain to entry token.
13961   if (Aliases.size() == 0)
13962     return DAG.getEntryNode();
13963
13964   // If a single operand then chain to it.  We don't need to revisit it.
13965   if (Aliases.size() == 1)
13966     return Aliases[0];
13967
13968   // Construct a custom tailored token factor.
13969   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13970 }
13971
13972 /// This is the entry point for the file.
13973 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13974                            CodeGenOpt::Level OptLevel) {
13975   /// This is the main entry point to this class.
13976   DAGCombiner(*this, AA, OptLevel).Run(Level);
13977 }