Revert r236546, "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 (const BinaryWithFlagsSDNode *BinNode =
1456               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1457         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1458                                       BinNode->Flags.hasNoUnsignedWrap(),
1459                                       BinNode->Flags.hasNoSignedWrap(),
1460                                       BinNode->Flags.hasExact());
1461       } else {
1462         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1463       }
1464       if (CSENode)
1465         return SDValue(CSENode, 0);
1466     }
1467   }
1468
1469   return RV;
1470 }
1471
1472 /// Given a node, return its input chain if it has one, otherwise return a null
1473 /// sd operand.
1474 static SDValue getInputChainForNode(SDNode *N) {
1475   if (unsigned NumOps = N->getNumOperands()) {
1476     if (N->getOperand(0).getValueType() == MVT::Other)
1477       return N->getOperand(0);
1478     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1479       return N->getOperand(NumOps-1);
1480     for (unsigned i = 1; i < NumOps-1; ++i)
1481       if (N->getOperand(i).getValueType() == MVT::Other)
1482         return N->getOperand(i);
1483   }
1484   return SDValue();
1485 }
1486
1487 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1488   // If N has two operands, where one has an input chain equal to the other,
1489   // the 'other' chain is redundant.
1490   if (N->getNumOperands() == 2) {
1491     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1492       return N->getOperand(0);
1493     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1494       return N->getOperand(1);
1495   }
1496
1497   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1498   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1499   SmallPtrSet<SDNode*, 16> SeenOps;
1500   bool Changed = false;             // If we should replace this token factor.
1501
1502   // Start out with this token factor.
1503   TFs.push_back(N);
1504
1505   // Iterate through token factors.  The TFs grows when new token factors are
1506   // encountered.
1507   for (unsigned i = 0; i < TFs.size(); ++i) {
1508     SDNode *TF = TFs[i];
1509
1510     // Check each of the operands.
1511     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1512       SDValue Op = TF->getOperand(i);
1513
1514       switch (Op.getOpcode()) {
1515       case ISD::EntryToken:
1516         // Entry tokens don't need to be added to the list. They are
1517         // redundant.
1518         Changed = true;
1519         break;
1520
1521       case ISD::TokenFactor:
1522         if (Op.hasOneUse() &&
1523             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1524           // Queue up for processing.
1525           TFs.push_back(Op.getNode());
1526           // Clean up in case the token factor is removed.
1527           AddToWorklist(Op.getNode());
1528           Changed = true;
1529           break;
1530         }
1531         // Fall thru
1532
1533       default:
1534         // Only add if it isn't already in the list.
1535         if (SeenOps.insert(Op.getNode()).second)
1536           Ops.push_back(Op);
1537         else
1538           Changed = true;
1539         break;
1540       }
1541     }
1542   }
1543
1544   SDValue Result;
1545
1546   // If we've changed things around then replace token factor.
1547   if (Changed) {
1548     if (Ops.empty()) {
1549       // The entry token is the only possible outcome.
1550       Result = DAG.getEntryNode();
1551     } else {
1552       // New and improved token factor.
1553       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1554     }
1555
1556     // Add users to worklist if AA is enabled, since it may introduce
1557     // a lot of new chained token factors while removing memory deps.
1558     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1559       : DAG.getSubtarget().useAA();
1560     return CombineTo(N, Result, UseAA /*add to worklist*/);
1561   }
1562
1563   return Result;
1564 }
1565
1566 /// MERGE_VALUES can always be eliminated.
1567 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1568   WorklistRemover DeadNodes(*this);
1569   // Replacing results may cause a different MERGE_VALUES to suddenly
1570   // be CSE'd with N, and carry its uses with it. Iterate until no
1571   // uses remain, to ensure that the node can be safely deleted.
1572   // First add the users of this node to the work list so that they
1573   // can be tried again once they have new operands.
1574   AddUsersToWorklist(N);
1575   do {
1576     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1577       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1578   } while (!N->use_empty());
1579   deleteAndRecombine(N);
1580   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1581 }
1582
1583 SDValue DAGCombiner::visitADD(SDNode *N) {
1584   SDValue N0 = N->getOperand(0);
1585   SDValue N1 = N->getOperand(1);
1586   EVT VT = N0.getValueType();
1587
1588   // fold vector ops
1589   if (VT.isVector()) {
1590     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1591       return FoldedVOp;
1592
1593     // fold (add x, 0) -> x, vector edition
1594     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1595       return N0;
1596     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1597       return N1;
1598   }
1599
1600   // fold (add x, undef) -> undef
1601   if (N0.getOpcode() == ISD::UNDEF)
1602     return N0;
1603   if (N1.getOpcode() == ISD::UNDEF)
1604     return N1;
1605   // fold (add c1, c2) -> c1+c2
1606   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1607   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1608   if (N0C && N1C)
1609     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1610   // canonicalize constant to RHS
1611   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1612      !isConstantIntBuildVectorOrConstantInt(N1))
1613     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1614   // fold (add x, 0) -> x
1615   if (N1C && N1C->isNullValue())
1616     return N0;
1617   // fold (add Sym, c) -> Sym+c
1618   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1619     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1620         GA->getOpcode() == ISD::GlobalAddress)
1621       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1622                                   GA->getOffset() +
1623                                     (uint64_t)N1C->getSExtValue());
1624   // fold ((c1-A)+c2) -> (c1+c2)-A
1625   if (N1C && N0.getOpcode() == ISD::SUB)
1626     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1627       SDLoc DL(N);
1628       return DAG.getNode(ISD::SUB, DL, VT,
1629                          DAG.getConstant(N1C->getAPIntValue()+
1630                                          N0C->getAPIntValue(), DL, VT),
1631                          N0.getOperand(1));
1632     }
1633   // reassociate add
1634   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1635     return RADD;
1636   // fold ((0-A) + B) -> B-A
1637   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1638       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1639     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1640   // fold (A + (0-B)) -> A-B
1641   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1642       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1643     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1644   // fold (A+(B-A)) -> B
1645   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1646     return N1.getOperand(0);
1647   // fold ((B-A)+A) -> B
1648   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1649     return N0.getOperand(0);
1650   // fold (A+(B-(A+C))) to (B-C)
1651   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1652       N0 == N1.getOperand(1).getOperand(0))
1653     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1654                        N1.getOperand(1).getOperand(1));
1655   // fold (A+(B-(C+A))) to (B-C)
1656   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1657       N0 == N1.getOperand(1).getOperand(1))
1658     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1659                        N1.getOperand(1).getOperand(0));
1660   // fold (A+((B-A)+or-C)) to (B+or-C)
1661   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1662       N1.getOperand(0).getOpcode() == ISD::SUB &&
1663       N0 == N1.getOperand(0).getOperand(1))
1664     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1665                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1666
1667   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1668   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1669     SDValue N00 = N0.getOperand(0);
1670     SDValue N01 = N0.getOperand(1);
1671     SDValue N10 = N1.getOperand(0);
1672     SDValue N11 = N1.getOperand(1);
1673
1674     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1675       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1676                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1677                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1678   }
1679
1680   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1681     return SDValue(N, 0);
1682
1683   // fold (a+b) -> (a|b) iff a and b share no bits.
1684   if (VT.isInteger() && !VT.isVector()) {
1685     APInt LHSZero, LHSOne;
1686     APInt RHSZero, RHSOne;
1687     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1688
1689     if (LHSZero.getBoolValue()) {
1690       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1691
1692       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1693       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1694       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1695         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1696           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1697       }
1698     }
1699   }
1700
1701   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1702   if (N1.getOpcode() == ISD::SHL &&
1703       N1.getOperand(0).getOpcode() == ISD::SUB)
1704     if (ConstantSDNode *C =
1705           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1706       if (C->getAPIntValue() == 0)
1707         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1708                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1709                                        N1.getOperand(0).getOperand(1),
1710                                        N1.getOperand(1)));
1711   if (N0.getOpcode() == ISD::SHL &&
1712       N0.getOperand(0).getOpcode() == ISD::SUB)
1713     if (ConstantSDNode *C =
1714           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1715       if (C->getAPIntValue() == 0)
1716         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1717                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1718                                        N0.getOperand(0).getOperand(1),
1719                                        N0.getOperand(1)));
1720
1721   if (N1.getOpcode() == ISD::AND) {
1722     SDValue AndOp0 = N1.getOperand(0);
1723     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1724     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1725     unsigned DestBits = VT.getScalarType().getSizeInBits();
1726
1727     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1728     // and similar xforms where the inner op is either ~0 or 0.
1729     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1730       SDLoc DL(N);
1731       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1732     }
1733   }
1734
1735   // add (sext i1), X -> sub X, (zext i1)
1736   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1737       N0.getOperand(0).getValueType() == MVT::i1 &&
1738       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1739     SDLoc DL(N);
1740     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1741     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1742   }
1743
1744   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1745   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1746     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1747     if (TN->getVT() == MVT::i1) {
1748       SDLoc DL(N);
1749       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1750                                  DAG.getConstant(1, DL, VT));
1751       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1752     }
1753   }
1754
1755   return SDValue();
1756 }
1757
1758 SDValue DAGCombiner::visitADDC(SDNode *N) {
1759   SDValue N0 = N->getOperand(0);
1760   SDValue N1 = N->getOperand(1);
1761   EVT VT = N0.getValueType();
1762
1763   // If the flag result is dead, turn this into an ADD.
1764   if (!N->hasAnyUseOfValue(1))
1765     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1766                      DAG.getNode(ISD::CARRY_FALSE,
1767                                  SDLoc(N), MVT::Glue));
1768
1769   // canonicalize constant to RHS.
1770   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1771   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1772   if (N0C && !N1C)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1774
1775   // fold (addc x, 0) -> x + no carry out
1776   if (N1C && N1C->isNullValue())
1777     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1778                                         SDLoc(N), MVT::Glue));
1779
1780   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1781   APInt LHSZero, LHSOne;
1782   APInt RHSZero, RHSOne;
1783   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1784
1785   if (LHSZero.getBoolValue()) {
1786     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1787
1788     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1789     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1790     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1791       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1792                        DAG.getNode(ISD::CARRY_FALSE,
1793                                    SDLoc(N), MVT::Glue));
1794   }
1795
1796   return SDValue();
1797 }
1798
1799 SDValue DAGCombiner::visitADDE(SDNode *N) {
1800   SDValue N0 = N->getOperand(0);
1801   SDValue N1 = N->getOperand(1);
1802   SDValue CarryIn = N->getOperand(2);
1803
1804   // canonicalize constant to RHS
1805   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1806   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1807   if (N0C && !N1C)
1808     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1809                        N1, N0, CarryIn);
1810
1811   // fold (adde x, y, false) -> (addc x, y)
1812   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1813     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1814
1815   return SDValue();
1816 }
1817
1818 // Since it may not be valid to emit a fold to zero for vector initializers
1819 // check if we can before folding.
1820 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1821                              SelectionDAG &DAG,
1822                              bool LegalOperations, bool LegalTypes) {
1823   if (!VT.isVector())
1824     return DAG.getConstant(0, DL, VT);
1825   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1826     return DAG.getConstant(0, DL, VT);
1827   return SDValue();
1828 }
1829
1830 SDValue DAGCombiner::visitSUB(SDNode *N) {
1831   SDValue N0 = N->getOperand(0);
1832   SDValue N1 = N->getOperand(1);
1833   EVT VT = N0.getValueType();
1834
1835   // fold vector ops
1836   if (VT.isVector()) {
1837     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1838       return FoldedVOp;
1839
1840     // fold (sub x, 0) -> x, vector edition
1841     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1842       return N0;
1843   }
1844
1845   // fold (sub x, x) -> 0
1846   // FIXME: Refactor this and xor and other similar operations together.
1847   if (N0 == N1)
1848     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1849   // fold (sub c1, c2) -> c1-c2
1850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1852   if (N0C && N1C)
1853     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1854   // fold (sub x, c) -> (add x, -c)
1855   if (N1C) {
1856     SDLoc DL(N);
1857     return DAG.getNode(ISD::ADD, DL, VT, N0,
1858                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1859   }
1860   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1861   if (N0C && N0C->isAllOnesValue())
1862     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1863   // fold A-(A-B) -> B
1864   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1865     return N1.getOperand(1);
1866   // fold (A+B)-A -> B
1867   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1868     return N0.getOperand(1);
1869   // fold (A+B)-B -> A
1870   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1871     return N0.getOperand(0);
1872   // fold C2-(A+C1) -> (C2-C1)-A
1873   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1874     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1875   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1876     SDLoc DL(N);
1877     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1878                                    DL, VT);
1879     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1880                        N1.getOperand(0));
1881   }
1882   // fold ((A+(B+or-C))-B) -> A+or-C
1883   if (N0.getOpcode() == ISD::ADD &&
1884       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1885        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1886       N0.getOperand(1).getOperand(0) == N1)
1887     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1888                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1889   // fold ((A+(C+B))-B) -> A+C
1890   if (N0.getOpcode() == ISD::ADD &&
1891       N0.getOperand(1).getOpcode() == ISD::ADD &&
1892       N0.getOperand(1).getOperand(1) == N1)
1893     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1894                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1895   // fold ((A-(B-C))-C) -> A-B
1896   if (N0.getOpcode() == ISD::SUB &&
1897       N0.getOperand(1).getOpcode() == ISD::SUB &&
1898       N0.getOperand(1).getOperand(1) == N1)
1899     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1900                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1901
1902   // If either operand of a sub is undef, the result is undef
1903   if (N0.getOpcode() == ISD::UNDEF)
1904     return N0;
1905   if (N1.getOpcode() == ISD::UNDEF)
1906     return N1;
1907
1908   // If the relocation model supports it, consider symbol offsets.
1909   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1910     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1911       // fold (sub Sym, c) -> Sym-c
1912       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1913         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1914                                     GA->getOffset() -
1915                                       (uint64_t)N1C->getSExtValue());
1916       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1917       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1918         if (GA->getGlobal() == GB->getGlobal())
1919           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1920                                  SDLoc(N), VT);
1921     }
1922
1923   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1924   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1925     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1926     if (TN->getVT() == MVT::i1) {
1927       SDLoc DL(N);
1928       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1929                                  DAG.getConstant(1, DL, VT));
1930       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1931     }
1932   }
1933
1934   return SDValue();
1935 }
1936
1937 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1938   SDValue N0 = N->getOperand(0);
1939   SDValue N1 = N->getOperand(1);
1940   EVT VT = N0.getValueType();
1941
1942   // If the flag result is dead, turn this into an SUB.
1943   if (!N->hasAnyUseOfValue(1))
1944     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1945                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1946                                  MVT::Glue));
1947
1948   // fold (subc x, x) -> 0 + no borrow
1949   if (N0 == N1) {
1950     SDLoc DL(N);
1951     return CombineTo(N, DAG.getConstant(0, DL, VT),
1952                      DAG.getNode(ISD::CARRY_FALSE, DL,
1953                                  MVT::Glue));
1954   }
1955
1956   // fold (subc x, 0) -> x + no borrow
1957   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1958   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1959   if (N1C && N1C->isNullValue())
1960     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1961                                         MVT::Glue));
1962
1963   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1964   if (N0C && N0C->isAllOnesValue())
1965     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1966                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1967                                  MVT::Glue));
1968
1969   return SDValue();
1970 }
1971
1972 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1973   SDValue N0 = N->getOperand(0);
1974   SDValue N1 = N->getOperand(1);
1975   SDValue CarryIn = N->getOperand(2);
1976
1977   // fold (sube x, y, false) -> (subc x, y)
1978   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1979     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1980
1981   return SDValue();
1982 }
1983
1984 SDValue DAGCombiner::visitMUL(SDNode *N) {
1985   SDValue N0 = N->getOperand(0);
1986   SDValue N1 = N->getOperand(1);
1987   EVT VT = N0.getValueType();
1988
1989   // fold (mul x, undef) -> 0
1990   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1991     return DAG.getConstant(0, SDLoc(N), VT);
1992
1993   bool N0IsConst = false;
1994   bool N1IsConst = false;
1995   APInt ConstValue0, ConstValue1;
1996   // fold vector ops
1997   if (VT.isVector()) {
1998     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1999       return FoldedVOp;
2000
2001     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
2002     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
2003   } else {
2004     N0IsConst = isa<ConstantSDNode>(N0);
2005     if (N0IsConst)
2006       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2007     N1IsConst = isa<ConstantSDNode>(N1);
2008     if (N1IsConst)
2009       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2010   }
2011
2012   // fold (mul c1, c2) -> c1*c2
2013   if (N0IsConst && N1IsConst)
2014     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2015                                       N0.getNode(), N1.getNode());
2016
2017   // canonicalize constant to RHS (vector doesn't have to splat)
2018   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2019      !isConstantIntBuildVectorOrConstantInt(N1))
2020     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2021   // fold (mul x, 0) -> 0
2022   if (N1IsConst && ConstValue1 == 0)
2023     return N1;
2024   // We require a splat of the entire scalar bit width for non-contiguous
2025   // bit patterns.
2026   bool IsFullSplat =
2027     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2028   // fold (mul x, 1) -> x
2029   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2030     return N0;
2031   // fold (mul x, -1) -> 0-x
2032   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2033     SDLoc DL(N);
2034     return DAG.getNode(ISD::SUB, DL, VT,
2035                        DAG.getConstant(0, DL, VT), N0);
2036   }
2037   // fold (mul x, (1 << c)) -> x << c
2038   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2039     SDLoc DL(N);
2040     return DAG.getNode(ISD::SHL, DL, VT, N0,
2041                        DAG.getConstant(ConstValue1.logBase2(), DL,
2042                                        getShiftAmountTy(N0.getValueType())));
2043   }
2044   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2045   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2046     unsigned Log2Val = (-ConstValue1).logBase2();
2047     SDLoc DL(N);
2048     // FIXME: If the input is something that is easily negated (e.g. a
2049     // single-use add), we should put the negate there.
2050     return DAG.getNode(ISD::SUB, DL, VT,
2051                        DAG.getConstant(0, DL, VT),
2052                        DAG.getNode(ISD::SHL, DL, VT, N0,
2053                             DAG.getConstant(Log2Val, DL,
2054                                       getShiftAmountTy(N0.getValueType()))));
2055   }
2056
2057   APInt Val;
2058   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2059   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2060       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2061                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2062     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2063                              N1, N0.getOperand(1));
2064     AddToWorklist(C3.getNode());
2065     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2066                        N0.getOperand(0), C3);
2067   }
2068
2069   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2070   // use.
2071   {
2072     SDValue Sh(nullptr,0), Y(nullptr,0);
2073     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2074     if (N0.getOpcode() == ISD::SHL &&
2075         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2076                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2077         N0.getNode()->hasOneUse()) {
2078       Sh = N0; Y = N1;
2079     } else if (N1.getOpcode() == ISD::SHL &&
2080                isa<ConstantSDNode>(N1.getOperand(1)) &&
2081                N1.getNode()->hasOneUse()) {
2082       Sh = N1; Y = N0;
2083     }
2084
2085     if (Sh.getNode()) {
2086       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2087                                 Sh.getOperand(0), Y);
2088       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2089                          Mul, Sh.getOperand(1));
2090     }
2091   }
2092
2093   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2094   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2095       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2096                      isa<ConstantSDNode>(N0.getOperand(1))))
2097     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2098                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2099                                    N0.getOperand(0), N1),
2100                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2101                                    N0.getOperand(1), N1));
2102
2103   // reassociate mul
2104   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2105     return RMUL;
2106
2107   return SDValue();
2108 }
2109
2110 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2111   SDValue N0 = N->getOperand(0);
2112   SDValue N1 = N->getOperand(1);
2113   EVT VT = N->getValueType(0);
2114
2115   // fold vector ops
2116   if (VT.isVector())
2117     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2118       return FoldedVOp;
2119
2120   // fold (sdiv c1, c2) -> c1/c2
2121   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123   if (N0C && N1C && !N1C->isNullValue())
2124     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2125   // fold (sdiv X, 1) -> X
2126   if (N1C && N1C->getAPIntValue() == 1LL)
2127     return N0;
2128   // fold (sdiv X, -1) -> 0-X
2129   if (N1C && N1C->isAllOnesValue()) {
2130     SDLoc DL(N);
2131     return DAG.getNode(ISD::SUB, DL, VT,
2132                        DAG.getConstant(0, DL, VT), N0);
2133   }
2134   // If we know the sign bits of both operands are zero, strength reduce to a
2135   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2136   if (!VT.isVector()) {
2137     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2138       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2139                          N0, N1);
2140   }
2141
2142   // fold (sdiv X, pow2) -> simple ops after legalize
2143   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2144                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2145     // If dividing by powers of two is cheap, then don't perform the following
2146     // fold.
2147     if (TLI.isPow2SDivCheap())
2148       return SDValue();
2149
2150     // Target-specific implementation of sdiv x, pow2.
2151     SDValue Res = BuildSDIVPow2(N);
2152     if (Res.getNode())
2153       return Res;
2154
2155     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2156     SDLoc DL(N);
2157
2158     // Splat the sign bit into the register
2159     SDValue SGN =
2160         DAG.getNode(ISD::SRA, DL, VT, N0,
2161                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2162                                     getShiftAmountTy(N0.getValueType())));
2163     AddToWorklist(SGN.getNode());
2164
2165     // Add (N0 < 0) ? abs2 - 1 : 0;
2166     SDValue SRL =
2167         DAG.getNode(ISD::SRL, DL, VT, SGN,
2168                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2169                                     getShiftAmountTy(SGN.getValueType())));
2170     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2171     AddToWorklist(SRL.getNode());
2172     AddToWorklist(ADD.getNode());    // Divide by pow2
2173     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2174                   DAG.getConstant(lg2, DL,
2175                                   getShiftAmountTy(ADD.getValueType())));
2176
2177     // If we're dividing by a positive value, we're done.  Otherwise, we must
2178     // negate the result.
2179     if (N1C->getAPIntValue().isNonNegative())
2180       return SRA;
2181
2182     AddToWorklist(SRA.getNode());
2183     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2184   }
2185
2186   // If integer divide is expensive and we satisfy the requirements, emit an
2187   // alternate sequence.
2188   if (N1C && !TLI.isIntDivCheap()) {
2189     SDValue Op = BuildSDIV(N);
2190     if (Op.getNode()) return Op;
2191   }
2192
2193   // undef / X -> 0
2194   if (N0.getOpcode() == ISD::UNDEF)
2195     return DAG.getConstant(0, SDLoc(N), VT);
2196   // X / undef -> undef
2197   if (N1.getOpcode() == ISD::UNDEF)
2198     return N1;
2199
2200   return SDValue();
2201 }
2202
2203 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2204   SDValue N0 = N->getOperand(0);
2205   SDValue N1 = N->getOperand(1);
2206   EVT VT = N->getValueType(0);
2207
2208   // fold vector ops
2209   if (VT.isVector())
2210     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2211       return FoldedVOp;
2212
2213   // fold (udiv c1, c2) -> c1/c2
2214   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2215   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2216   if (N0C && N1C && !N1C->isNullValue())
2217     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2218   // fold (udiv x, (1 << c)) -> x >>u c
2219   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2220     SDLoc DL(N);
2221     return DAG.getNode(ISD::SRL, DL, VT, N0,
2222                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2223                                        getShiftAmountTy(N0.getValueType())));
2224   }
2225   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2226   if (N1.getOpcode() == ISD::SHL) {
2227     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2228       if (SHC->getAPIntValue().isPowerOf2()) {
2229         EVT ADDVT = N1.getOperand(1).getValueType();
2230         SDLoc DL(N);
2231         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2232                                   N1.getOperand(1),
2233                                   DAG.getConstant(SHC->getAPIntValue()
2234                                                                   .logBase2(),
2235                                                   DL, ADDVT));
2236         AddToWorklist(Add.getNode());
2237         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2238       }
2239     }
2240   }
2241   // fold (udiv x, c) -> alternate
2242   if (N1C && !TLI.isIntDivCheap()) {
2243     SDValue Op = BuildUDIV(N);
2244     if (Op.getNode()) return Op;
2245   }
2246
2247   // undef / X -> 0
2248   if (N0.getOpcode() == ISD::UNDEF)
2249     return DAG.getConstant(0, SDLoc(N), VT);
2250   // X / undef -> undef
2251   if (N1.getOpcode() == ISD::UNDEF)
2252     return N1;
2253
2254   return SDValue();
2255 }
2256
2257 SDValue DAGCombiner::visitSREM(SDNode *N) {
2258   SDValue N0 = N->getOperand(0);
2259   SDValue N1 = N->getOperand(1);
2260   EVT VT = N->getValueType(0);
2261
2262   // fold (srem c1, c2) -> c1%c2
2263   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2264   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2265   if (N0C && N1C && !N1C->isNullValue())
2266     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2267   // If we know the sign bits of both operands are zero, strength reduce to a
2268   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2269   if (!VT.isVector()) {
2270     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2271       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2272   }
2273
2274   // If X/C can be simplified by the division-by-constant logic, lower
2275   // X%C to the equivalent of X-X/C*C.
2276   if (N1C && !N1C->isNullValue()) {
2277     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2278     AddToWorklist(Div.getNode());
2279     SDValue OptimizedDiv = combine(Div.getNode());
2280     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2281       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2282                                 OptimizedDiv, N1);
2283       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2284       AddToWorklist(Mul.getNode());
2285       return Sub;
2286     }
2287   }
2288
2289   // undef % X -> 0
2290   if (N0.getOpcode() == ISD::UNDEF)
2291     return DAG.getConstant(0, SDLoc(N), VT);
2292   // X % undef -> undef
2293   if (N1.getOpcode() == ISD::UNDEF)
2294     return N1;
2295
2296   return SDValue();
2297 }
2298
2299 SDValue DAGCombiner::visitUREM(SDNode *N) {
2300   SDValue N0 = N->getOperand(0);
2301   SDValue N1 = N->getOperand(1);
2302   EVT VT = N->getValueType(0);
2303
2304   // fold (urem c1, c2) -> c1%c2
2305   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2306   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2307   if (N0C && N1C && !N1C->isNullValue())
2308     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2309   // fold (urem x, pow2) -> (and x, pow2-1)
2310   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2311     SDLoc DL(N);
2312     return DAG.getNode(ISD::AND, DL, VT, N0,
2313                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2314   }
2315   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2316   if (N1.getOpcode() == ISD::SHL) {
2317     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2318       if (SHC->getAPIntValue().isPowerOf2()) {
2319         SDLoc DL(N);
2320         SDValue Add =
2321           DAG.getNode(ISD::ADD, DL, VT, N1,
2322                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2323                                  VT));
2324         AddToWorklist(Add.getNode());
2325         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2326       }
2327     }
2328   }
2329
2330   // If X/C can be simplified by the division-by-constant logic, lower
2331   // X%C to the equivalent of X-X/C*C.
2332   if (N1C && !N1C->isNullValue()) {
2333     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2334     AddToWorklist(Div.getNode());
2335     SDValue OptimizedDiv = combine(Div.getNode());
2336     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2337       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2338                                 OptimizedDiv, N1);
2339       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2340       AddToWorklist(Mul.getNode());
2341       return Sub;
2342     }
2343   }
2344
2345   // undef % X -> 0
2346   if (N0.getOpcode() == ISD::UNDEF)
2347     return DAG.getConstant(0, SDLoc(N), VT);
2348   // X % undef -> undef
2349   if (N1.getOpcode() == ISD::UNDEF)
2350     return N1;
2351
2352   return SDValue();
2353 }
2354
2355 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2356   SDValue N0 = N->getOperand(0);
2357   SDValue N1 = N->getOperand(1);
2358   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2359   EVT VT = N->getValueType(0);
2360   SDLoc DL(N);
2361
2362   // fold (mulhs x, 0) -> 0
2363   if (N1C && N1C->isNullValue())
2364     return N1;
2365   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2366   if (N1C && N1C->getAPIntValue() == 1) {
2367     SDLoc DL(N);
2368     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2369                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2370                                        DL,
2371                                        getShiftAmountTy(N0.getValueType())));
2372   }
2373   // fold (mulhs x, undef) -> 0
2374   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2375     return DAG.getConstant(0, SDLoc(N), VT);
2376
2377   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2378   // plus a shift.
2379   if (VT.isSimple() && !VT.isVector()) {
2380     MVT Simple = VT.getSimpleVT();
2381     unsigned SimpleSize = Simple.getSizeInBits();
2382     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2383     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2384       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2385       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2386       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2387       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2388             DAG.getConstant(SimpleSize, DL,
2389                             getShiftAmountTy(N1.getValueType())));
2390       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2391     }
2392   }
2393
2394   return SDValue();
2395 }
2396
2397 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2398   SDValue N0 = N->getOperand(0);
2399   SDValue N1 = N->getOperand(1);
2400   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2401   EVT VT = N->getValueType(0);
2402   SDLoc DL(N);
2403
2404   // fold (mulhu x, 0) -> 0
2405   if (N1C && N1C->isNullValue())
2406     return N1;
2407   // fold (mulhu x, 1) -> 0
2408   if (N1C && N1C->getAPIntValue() == 1)
2409     return DAG.getConstant(0, DL, N0.getValueType());
2410   // fold (mulhu x, undef) -> 0
2411   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2412     return DAG.getConstant(0, DL, VT);
2413
2414   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2415   // plus a shift.
2416   if (VT.isSimple() && !VT.isVector()) {
2417     MVT Simple = VT.getSimpleVT();
2418     unsigned SimpleSize = Simple.getSizeInBits();
2419     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2420     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2421       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2422       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2423       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2424       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2425             DAG.getConstant(SimpleSize, DL,
2426                             getShiftAmountTy(N1.getValueType())));
2427       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2428     }
2429   }
2430
2431   return SDValue();
2432 }
2433
2434 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2435 /// give the opcodes for the two computations that are being performed. Return
2436 /// true if a simplification was made.
2437 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2438                                                 unsigned HiOp) {
2439   // If the high half is not needed, just compute the low half.
2440   bool HiExists = N->hasAnyUseOfValue(1);
2441   if (!HiExists &&
2442       (!LegalOperations ||
2443        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2444     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2445     return CombineTo(N, Res, Res);
2446   }
2447
2448   // If the low half is not needed, just compute the high half.
2449   bool LoExists = N->hasAnyUseOfValue(0);
2450   if (!LoExists &&
2451       (!LegalOperations ||
2452        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2453     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2454     return CombineTo(N, Res, Res);
2455   }
2456
2457   // If both halves are used, return as it is.
2458   if (LoExists && HiExists)
2459     return SDValue();
2460
2461   // If the two computed results can be simplified separately, separate them.
2462   if (LoExists) {
2463     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2464     AddToWorklist(Lo.getNode());
2465     SDValue LoOpt = combine(Lo.getNode());
2466     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2467         (!LegalOperations ||
2468          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2469       return CombineTo(N, LoOpt, LoOpt);
2470   }
2471
2472   if (HiExists) {
2473     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2474     AddToWorklist(Hi.getNode());
2475     SDValue HiOpt = combine(Hi.getNode());
2476     if (HiOpt.getNode() && HiOpt != Hi &&
2477         (!LegalOperations ||
2478          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2479       return CombineTo(N, HiOpt, HiOpt);
2480   }
2481
2482   return SDValue();
2483 }
2484
2485 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2486   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2487   if (Res.getNode()) return Res;
2488
2489   EVT VT = N->getValueType(0);
2490   SDLoc DL(N);
2491
2492   // If the type is twice as wide is legal, transform the mulhu to a wider
2493   // multiply plus a shift.
2494   if (VT.isSimple() && !VT.isVector()) {
2495     MVT Simple = VT.getSimpleVT();
2496     unsigned SimpleSize = Simple.getSizeInBits();
2497     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2498     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2499       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2500       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2501       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2502       // Compute the high part as N1.
2503       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2504             DAG.getConstant(SimpleSize, DL,
2505                             getShiftAmountTy(Lo.getValueType())));
2506       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2507       // Compute the low part as N0.
2508       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2509       return CombineTo(N, Lo, Hi);
2510     }
2511   }
2512
2513   return SDValue();
2514 }
2515
2516 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2517   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2518   if (Res.getNode()) return Res;
2519
2520   EVT VT = N->getValueType(0);
2521   SDLoc DL(N);
2522
2523   // If the type is twice as wide is legal, transform the mulhu to a wider
2524   // multiply plus a shift.
2525   if (VT.isSimple() && !VT.isVector()) {
2526     MVT Simple = VT.getSimpleVT();
2527     unsigned SimpleSize = Simple.getSizeInBits();
2528     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2529     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2530       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2531       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2532       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2533       // Compute the high part as N1.
2534       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2535             DAG.getConstant(SimpleSize, DL,
2536                             getShiftAmountTy(Lo.getValueType())));
2537       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2538       // Compute the low part as N0.
2539       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2540       return CombineTo(N, Lo, Hi);
2541     }
2542   }
2543
2544   return SDValue();
2545 }
2546
2547 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2548   // (smulo x, 2) -> (saddo x, x)
2549   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2550     if (C2->getAPIntValue() == 2)
2551       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2552                          N->getOperand(0), N->getOperand(0));
2553
2554   return SDValue();
2555 }
2556
2557 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2558   // (umulo x, 2) -> (uaddo x, x)
2559   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2560     if (C2->getAPIntValue() == 2)
2561       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2562                          N->getOperand(0), N->getOperand(0));
2563
2564   return SDValue();
2565 }
2566
2567 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2568   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2569   if (Res.getNode()) return Res;
2570
2571   return SDValue();
2572 }
2573
2574 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2575   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2576   if (Res.getNode()) return Res;
2577
2578   return SDValue();
2579 }
2580
2581 /// If this is a binary operator with two operands of the same opcode, try to
2582 /// simplify it.
2583 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2584   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2585   EVT VT = N0.getValueType();
2586   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2587
2588   // Bail early if none of these transforms apply.
2589   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2590
2591   // For each of OP in AND/OR/XOR:
2592   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2593   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2594   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2595   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2596   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2597   //
2598   // do not sink logical op inside of a vector extend, since it may combine
2599   // into a vsetcc.
2600   EVT Op0VT = N0.getOperand(0).getValueType();
2601   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2602        N0.getOpcode() == ISD::SIGN_EXTEND ||
2603        N0.getOpcode() == ISD::BSWAP ||
2604        // Avoid infinite looping with PromoteIntBinOp.
2605        (N0.getOpcode() == ISD::ANY_EXTEND &&
2606         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2607        (N0.getOpcode() == ISD::TRUNCATE &&
2608         (!TLI.isZExtFree(VT, Op0VT) ||
2609          !TLI.isTruncateFree(Op0VT, VT)) &&
2610         TLI.isTypeLegal(Op0VT))) &&
2611       !VT.isVector() &&
2612       Op0VT == N1.getOperand(0).getValueType() &&
2613       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2614     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2615                                  N0.getOperand(0).getValueType(),
2616                                  N0.getOperand(0), N1.getOperand(0));
2617     AddToWorklist(ORNode.getNode());
2618     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2619   }
2620
2621   // For each of OP in SHL/SRL/SRA/AND...
2622   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2623   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2624   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2625   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2626        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2627       N0.getOperand(1) == N1.getOperand(1)) {
2628     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2629                                  N0.getOperand(0).getValueType(),
2630                                  N0.getOperand(0), N1.getOperand(0));
2631     AddToWorklist(ORNode.getNode());
2632     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2633                        ORNode, N0.getOperand(1));
2634   }
2635
2636   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2637   // Only perform this optimization after type legalization and before
2638   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2639   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2640   // we don't want to undo this promotion.
2641   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2642   // on scalars.
2643   if ((N0.getOpcode() == ISD::BITCAST ||
2644        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2645       Level == AfterLegalizeTypes) {
2646     SDValue In0 = N0.getOperand(0);
2647     SDValue In1 = N1.getOperand(0);
2648     EVT In0Ty = In0.getValueType();
2649     EVT In1Ty = In1.getValueType();
2650     SDLoc DL(N);
2651     // If both incoming values are integers, and the original types are the
2652     // same.
2653     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2654       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2655       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2656       AddToWorklist(Op.getNode());
2657       return BC;
2658     }
2659   }
2660
2661   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2662   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2663   // If both shuffles use the same mask, and both shuffle within a single
2664   // vector, then it is worthwhile to move the swizzle after the operation.
2665   // The type-legalizer generates this pattern when loading illegal
2666   // vector types from memory. In many cases this allows additional shuffle
2667   // optimizations.
2668   // There are other cases where moving the shuffle after the xor/and/or
2669   // is profitable even if shuffles don't perform a swizzle.
2670   // If both shuffles use the same mask, and both shuffles have the same first
2671   // or second operand, then it might still be profitable to move the shuffle
2672   // after the xor/and/or operation.
2673   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2674     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2675     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2676
2677     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2678            "Inputs to shuffles are not the same type");
2679
2680     // Check that both shuffles use the same mask. The masks are known to be of
2681     // the same length because the result vector type is the same.
2682     // Check also that shuffles have only one use to avoid introducing extra
2683     // instructions.
2684     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2685         SVN0->getMask().equals(SVN1->getMask())) {
2686       SDValue ShOp = N0->getOperand(1);
2687
2688       // Don't try to fold this node if it requires introducing a
2689       // build vector of all zeros that might be illegal at this stage.
2690       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2691         if (!LegalTypes)
2692           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2693         else
2694           ShOp = SDValue();
2695       }
2696
2697       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2698       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2699       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2700       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2701         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2702                                       N0->getOperand(0), N1->getOperand(0));
2703         AddToWorklist(NewNode.getNode());
2704         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2705                                     &SVN0->getMask()[0]);
2706       }
2707
2708       // Don't try to fold this node if it requires introducing a
2709       // build vector of all zeros that might be illegal at this stage.
2710       ShOp = N0->getOperand(0);
2711       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2712         if (!LegalTypes)
2713           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2714         else
2715           ShOp = SDValue();
2716       }
2717
2718       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2719       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2720       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2721       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2722         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2723                                       N0->getOperand(1), N1->getOperand(1));
2724         AddToWorklist(NewNode.getNode());
2725         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2726                                     &SVN0->getMask()[0]);
2727       }
2728     }
2729   }
2730
2731   return SDValue();
2732 }
2733
2734 /// This contains all DAGCombine rules which reduce two values combined by
2735 /// an And operation to a single value. This makes them reusable in the context
2736 /// of visitSELECT(). Rules involving constants are not included as
2737 /// visitSELECT() already handles those cases.
2738 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2739                                   SDNode *LocReference) {
2740   EVT VT = N1.getValueType();
2741
2742   // fold (and x, undef) -> 0
2743   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2744     return DAG.getConstant(0, SDLoc(LocReference), VT);
2745   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2746   SDValue LL, LR, RL, RR, CC0, CC1;
2747   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2748     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2749     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2750
2751     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2752         LL.getValueType().isInteger()) {
2753       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2754       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2755         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2756                                      LR.getValueType(), LL, RL);
2757         AddToWorklist(ORNode.getNode());
2758         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2759       }
2760       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2761       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2762         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2763                                       LR.getValueType(), LL, RL);
2764         AddToWorklist(ANDNode.getNode());
2765         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2766       }
2767       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2768       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2769         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2770                                      LR.getValueType(), LL, RL);
2771         AddToWorklist(ORNode.getNode());
2772         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2773       }
2774     }
2775     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2776     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2777         Op0 == Op1 && LL.getValueType().isInteger() &&
2778       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2779                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2780                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2781                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2782       SDLoc DL(N0);
2783       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2784                                     LL, DAG.getConstant(1, DL,
2785                                                         LL.getValueType()));
2786       AddToWorklist(ADDNode.getNode());
2787       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2788                           DAG.getConstant(2, DL, LL.getValueType()),
2789                           ISD::SETUGE);
2790     }
2791     // canonicalize equivalent to ll == rl
2792     if (LL == RR && LR == RL) {
2793       Op1 = ISD::getSetCCSwappedOperands(Op1);
2794       std::swap(RL, RR);
2795     }
2796     if (LL == RL && LR == RR) {
2797       bool isInteger = LL.getValueType().isInteger();
2798       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2799       if (Result != ISD::SETCC_INVALID &&
2800           (!LegalOperations ||
2801            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2802             TLI.isOperationLegal(ISD::SETCC,
2803                             getSetCCResultType(N0.getSimpleValueType())))))
2804         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2805                             LL, LR, Result);
2806     }
2807   }
2808
2809   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2810       VT.getSizeInBits() <= 64) {
2811     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2812       APInt ADDC = ADDI->getAPIntValue();
2813       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2814         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2815         // immediate for an add, but it is legal if its top c2 bits are set,
2816         // transform the ADD so the immediate doesn't need to be materialized
2817         // in a register.
2818         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2819           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2820                                              SRLI->getZExtValue());
2821           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2822             ADDC |= Mask;
2823             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2824               SDLoc DL(N0);
2825               SDValue NewAdd =
2826                 DAG.getNode(ISD::ADD, DL, VT,
2827                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2828               CombineTo(N0.getNode(), NewAdd);
2829               // Return N so it doesn't get rechecked!
2830               return SDValue(LocReference, 0);
2831             }
2832           }
2833         }
2834       }
2835     }
2836   }
2837
2838   return SDValue();
2839 }
2840
2841 SDValue DAGCombiner::visitAND(SDNode *N) {
2842   SDValue N0 = N->getOperand(0);
2843   SDValue N1 = N->getOperand(1);
2844   EVT VT = N1.getValueType();
2845
2846   // fold vector ops
2847   if (VT.isVector()) {
2848     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2849       return FoldedVOp;
2850
2851     // fold (and x, 0) -> 0, vector edition
2852     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2853       // do not return N0, because undef node may exist in N0
2854       return DAG.getConstant(
2855           APInt::getNullValue(
2856               N0.getValueType().getScalarType().getSizeInBits()),
2857           SDLoc(N), N0.getValueType());
2858     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2859       // do not return N1, because undef node may exist in N1
2860       return DAG.getConstant(
2861           APInt::getNullValue(
2862               N1.getValueType().getScalarType().getSizeInBits()),
2863           SDLoc(N), N1.getValueType());
2864
2865     // fold (and x, -1) -> x, vector edition
2866     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2867       return N1;
2868     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2869       return N0;
2870   }
2871
2872   // fold (and c1, c2) -> c1&c2
2873   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2874   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2875   if (N0C && N1C)
2876     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2877   // canonicalize constant to RHS
2878   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2879      !isConstantIntBuildVectorOrConstantInt(N1))
2880     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2881   // fold (and x, -1) -> x
2882   if (N1C && N1C->isAllOnesValue())
2883     return N0;
2884   // if (and x, c) is known to be zero, return 0
2885   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2886   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2887                                    APInt::getAllOnesValue(BitWidth)))
2888     return DAG.getConstant(0, SDLoc(N), VT);
2889   // reassociate and
2890   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2891     return RAND;
2892   // fold (and (or x, C), D) -> D if (C & D) == D
2893   if (N1C && N0.getOpcode() == ISD::OR)
2894     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2895       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2896         return N1;
2897   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2898   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2899     SDValue N0Op0 = N0.getOperand(0);
2900     APInt Mask = ~N1C->getAPIntValue();
2901     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2902     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2903       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2904                                  N0.getValueType(), N0Op0);
2905
2906       // Replace uses of the AND with uses of the Zero extend node.
2907       CombineTo(N, Zext);
2908
2909       // We actually want to replace all uses of the any_extend with the
2910       // zero_extend, to avoid duplicating things.  This will later cause this
2911       // AND to be folded.
2912       CombineTo(N0.getNode(), Zext);
2913       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2914     }
2915   }
2916   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2917   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2918   // already be zero by virtue of the width of the base type of the load.
2919   //
2920   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2921   // more cases.
2922   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2923        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2924       N0.getOpcode() == ISD::LOAD) {
2925     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2926                                          N0 : N0.getOperand(0) );
2927
2928     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2929     // This can be a pure constant or a vector splat, in which case we treat the
2930     // vector as a scalar and use the splat value.
2931     APInt Constant = APInt::getNullValue(1);
2932     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2933       Constant = C->getAPIntValue();
2934     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2935       APInt SplatValue, SplatUndef;
2936       unsigned SplatBitSize;
2937       bool HasAnyUndefs;
2938       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2939                                              SplatBitSize, HasAnyUndefs);
2940       if (IsSplat) {
2941         // Undef bits can contribute to a possible optimisation if set, so
2942         // set them.
2943         SplatValue |= SplatUndef;
2944
2945         // The splat value may be something like "0x00FFFFFF", which means 0 for
2946         // the first vector value and FF for the rest, repeating. We need a mask
2947         // that will apply equally to all members of the vector, so AND all the
2948         // lanes of the constant together.
2949         EVT VT = Vector->getValueType(0);
2950         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2951
2952         // If the splat value has been compressed to a bitlength lower
2953         // than the size of the vector lane, we need to re-expand it to
2954         // the lane size.
2955         if (BitWidth > SplatBitSize)
2956           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2957                SplatBitSize < BitWidth;
2958                SplatBitSize = SplatBitSize * 2)
2959             SplatValue |= SplatValue.shl(SplatBitSize);
2960
2961         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2962         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2963         if (SplatBitSize % BitWidth == 0) {
2964           Constant = APInt::getAllOnesValue(BitWidth);
2965           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2966             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2967         }
2968       }
2969     }
2970
2971     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2972     // actually legal and isn't going to get expanded, else this is a false
2973     // optimisation.
2974     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2975                                                     Load->getValueType(0),
2976                                                     Load->getMemoryVT());
2977
2978     // Resize the constant to the same size as the original memory access before
2979     // extension. If it is still the AllOnesValue then this AND is completely
2980     // unneeded.
2981     Constant =
2982       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2983
2984     bool B;
2985     switch (Load->getExtensionType()) {
2986     default: B = false; break;
2987     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2988     case ISD::ZEXTLOAD:
2989     case ISD::NON_EXTLOAD: B = true; break;
2990     }
2991
2992     if (B && Constant.isAllOnesValue()) {
2993       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2994       // preserve semantics once we get rid of the AND.
2995       SDValue NewLoad(Load, 0);
2996       if (Load->getExtensionType() == ISD::EXTLOAD) {
2997         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2998                               Load->getValueType(0), SDLoc(Load),
2999                               Load->getChain(), Load->getBasePtr(),
3000                               Load->getOffset(), Load->getMemoryVT(),
3001                               Load->getMemOperand());
3002         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
3003         if (Load->getNumValues() == 3) {
3004           // PRE/POST_INC loads have 3 values.
3005           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3006                            NewLoad.getValue(2) };
3007           CombineTo(Load, To, 3, true);
3008         } else {
3009           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3010         }
3011       }
3012
3013       // Fold the AND away, taking care not to fold to the old load node if we
3014       // replaced it.
3015       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3016
3017       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018     }
3019   }
3020
3021   // fold (and (load x), 255) -> (zextload x, i8)
3022   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3023   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3024   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3025               (N0.getOpcode() == ISD::ANY_EXTEND &&
3026                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3027     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3028     LoadSDNode *LN0 = HasAnyExt
3029       ? cast<LoadSDNode>(N0.getOperand(0))
3030       : cast<LoadSDNode>(N0);
3031     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3032         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3033       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3034       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3035         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3036         EVT LoadedVT = LN0->getMemoryVT();
3037         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3038
3039         if (ExtVT == LoadedVT &&
3040             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3041                                                     ExtVT))) {
3042
3043           SDValue NewLoad =
3044             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3045                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3046                            LN0->getMemOperand());
3047           AddToWorklist(N);
3048           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3049           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3050         }
3051
3052         // Do not change the width of a volatile load.
3053         // Do not generate loads of non-round integer types since these can
3054         // be expensive (and would be wrong if the type is not byte sized).
3055         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3056             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3057                                                     ExtVT))) {
3058           EVT PtrType = LN0->getOperand(1).getValueType();
3059
3060           unsigned Alignment = LN0->getAlignment();
3061           SDValue NewPtr = LN0->getBasePtr();
3062
3063           // For big endian targets, we need to add an offset to the pointer
3064           // to load the correct bytes.  For little endian systems, we merely
3065           // need to read fewer bytes from the same pointer.
3066           if (TLI.isBigEndian()) {
3067             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3068             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3069             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3070             SDLoc DL(LN0);
3071             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3072                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3073             Alignment = MinAlign(Alignment, PtrOff);
3074           }
3075
3076           AddToWorklist(NewPtr.getNode());
3077
3078           SDValue Load =
3079             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3080                            LN0->getChain(), NewPtr,
3081                            LN0->getPointerInfo(),
3082                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3083                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3084           AddToWorklist(N);
3085           CombineTo(LN0, Load, Load.getValue(1));
3086           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3087         }
3088       }
3089     }
3090   }
3091
3092   if (SDValue Combined = visitANDLike(N0, N1, N))
3093     return Combined;
3094
3095   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3096   if (N0.getOpcode() == N1.getOpcode()) {
3097     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3098     if (Tmp.getNode()) return Tmp;
3099   }
3100
3101   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3102   // fold (and (sra)) -> (and (srl)) when possible.
3103   if (!VT.isVector() &&
3104       SimplifyDemandedBits(SDValue(N, 0)))
3105     return SDValue(N, 0);
3106
3107   // fold (zext_inreg (extload x)) -> (zextload x)
3108   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3109     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3110     EVT MemVT = LN0->getMemoryVT();
3111     // If we zero all the possible extended bits, then we can turn this into
3112     // a zextload if we are running before legalize or the operation is legal.
3113     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3114     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3115                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3116         ((!LegalOperations && !LN0->isVolatile()) ||
3117          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3118       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3119                                        LN0->getChain(), LN0->getBasePtr(),
3120                                        MemVT, LN0->getMemOperand());
3121       AddToWorklist(N);
3122       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3123       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3124     }
3125   }
3126   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3127   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3128       N0.hasOneUse()) {
3129     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3130     EVT MemVT = LN0->getMemoryVT();
3131     // If we zero all the possible extended bits, then we can turn this into
3132     // a zextload if we are running before legalize or the operation is legal.
3133     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3134     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3135                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3136         ((!LegalOperations && !LN0->isVolatile()) ||
3137          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3138       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3139                                        LN0->getChain(), LN0->getBasePtr(),
3140                                        MemVT, LN0->getMemOperand());
3141       AddToWorklist(N);
3142       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3143       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3144     }
3145   }
3146   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3147   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3148     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3149                                        N0.getOperand(1), false);
3150     if (BSwap.getNode())
3151       return BSwap;
3152   }
3153
3154   return SDValue();
3155 }
3156
3157 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3158 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3159                                         bool DemandHighBits) {
3160   if (!LegalOperations)
3161     return SDValue();
3162
3163   EVT VT = N->getValueType(0);
3164   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3165     return SDValue();
3166   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3167     return SDValue();
3168
3169   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3170   bool LookPassAnd0 = false;
3171   bool LookPassAnd1 = false;
3172   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3173       std::swap(N0, N1);
3174   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3175       std::swap(N0, N1);
3176   if (N0.getOpcode() == ISD::AND) {
3177     if (!N0.getNode()->hasOneUse())
3178       return SDValue();
3179     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3180     if (!N01C || N01C->getZExtValue() != 0xFF00)
3181       return SDValue();
3182     N0 = N0.getOperand(0);
3183     LookPassAnd0 = true;
3184   }
3185
3186   if (N1.getOpcode() == ISD::AND) {
3187     if (!N1.getNode()->hasOneUse())
3188       return SDValue();
3189     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3190     if (!N11C || N11C->getZExtValue() != 0xFF)
3191       return SDValue();
3192     N1 = N1.getOperand(0);
3193     LookPassAnd1 = true;
3194   }
3195
3196   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3197     std::swap(N0, N1);
3198   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3199     return SDValue();
3200   if (!N0.getNode()->hasOneUse() ||
3201       !N1.getNode()->hasOneUse())
3202     return SDValue();
3203
3204   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3206   if (!N01C || !N11C)
3207     return SDValue();
3208   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3209     return SDValue();
3210
3211   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3212   SDValue N00 = N0->getOperand(0);
3213   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3214     if (!N00.getNode()->hasOneUse())
3215       return SDValue();
3216     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3217     if (!N001C || N001C->getZExtValue() != 0xFF)
3218       return SDValue();
3219     N00 = N00.getOperand(0);
3220     LookPassAnd0 = true;
3221   }
3222
3223   SDValue N10 = N1->getOperand(0);
3224   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3225     if (!N10.getNode()->hasOneUse())
3226       return SDValue();
3227     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3228     if (!N101C || N101C->getZExtValue() != 0xFF00)
3229       return SDValue();
3230     N10 = N10.getOperand(0);
3231     LookPassAnd1 = true;
3232   }
3233
3234   if (N00 != N10)
3235     return SDValue();
3236
3237   // Make sure everything beyond the low halfword gets set to zero since the SRL
3238   // 16 will clear the top bits.
3239   unsigned OpSizeInBits = VT.getSizeInBits();
3240   if (DemandHighBits && OpSizeInBits > 16) {
3241     // If the left-shift isn't masked out then the only way this is a bswap is
3242     // if all bits beyond the low 8 are 0. In that case the entire pattern
3243     // reduces to a left shift anyway: leave it for other parts of the combiner.
3244     if (!LookPassAnd0)
3245       return SDValue();
3246
3247     // However, if the right shift isn't masked out then it might be because
3248     // it's not needed. See if we can spot that too.
3249     if (!LookPassAnd1 &&
3250         !DAG.MaskedValueIsZero(
3251             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3252       return SDValue();
3253   }
3254
3255   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3256   if (OpSizeInBits > 16) {
3257     SDLoc DL(N);
3258     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3259                       DAG.getConstant(OpSizeInBits - 16, DL,
3260                                       getShiftAmountTy(VT)));
3261   }
3262   return Res;
3263 }
3264
3265 /// Return true if the specified node is an element that makes up a 32-bit
3266 /// packed halfword byteswap.
3267 /// ((x & 0x000000ff) << 8) |
3268 /// ((x & 0x0000ff00) >> 8) |
3269 /// ((x & 0x00ff0000) << 8) |
3270 /// ((x & 0xff000000) >> 8)
3271 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3272   if (!N.getNode()->hasOneUse())
3273     return false;
3274
3275   unsigned Opc = N.getOpcode();
3276   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3277     return false;
3278
3279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3280   if (!N1C)
3281     return false;
3282
3283   unsigned Num;
3284   switch (N1C->getZExtValue()) {
3285   default:
3286     return false;
3287   case 0xFF:       Num = 0; break;
3288   case 0xFF00:     Num = 1; break;
3289   case 0xFF0000:   Num = 2; break;
3290   case 0xFF000000: Num = 3; break;
3291   }
3292
3293   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3294   SDValue N0 = N.getOperand(0);
3295   if (Opc == ISD::AND) {
3296     if (Num == 0 || Num == 2) {
3297       // (x >> 8) & 0xff
3298       // (x >> 8) & 0xff0000
3299       if (N0.getOpcode() != ISD::SRL)
3300         return false;
3301       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3302       if (!C || C->getZExtValue() != 8)
3303         return false;
3304     } else {
3305       // (x << 8) & 0xff00
3306       // (x << 8) & 0xff000000
3307       if (N0.getOpcode() != ISD::SHL)
3308         return false;
3309       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3310       if (!C || C->getZExtValue() != 8)
3311         return false;
3312     }
3313   } else if (Opc == ISD::SHL) {
3314     // (x & 0xff) << 8
3315     // (x & 0xff0000) << 8
3316     if (Num != 0 && Num != 2)
3317       return false;
3318     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3319     if (!C || C->getZExtValue() != 8)
3320       return false;
3321   } else { // Opc == ISD::SRL
3322     // (x & 0xff00) >> 8
3323     // (x & 0xff000000) >> 8
3324     if (Num != 1 && Num != 3)
3325       return false;
3326     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3327     if (!C || C->getZExtValue() != 8)
3328       return false;
3329   }
3330
3331   if (Parts[Num])
3332     return false;
3333
3334   Parts[Num] = N0.getOperand(0).getNode();
3335   return true;
3336 }
3337
3338 /// Match a 32-bit packed halfword bswap. That is
3339 /// ((x & 0x000000ff) << 8) |
3340 /// ((x & 0x0000ff00) >> 8) |
3341 /// ((x & 0x00ff0000) << 8) |
3342 /// ((x & 0xff000000) >> 8)
3343 /// => (rotl (bswap x), 16)
3344 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3345   if (!LegalOperations)
3346     return SDValue();
3347
3348   EVT VT = N->getValueType(0);
3349   if (VT != MVT::i32)
3350     return SDValue();
3351   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3352     return SDValue();
3353
3354   // Look for either
3355   // (or (or (and), (and)), (or (and), (and)))
3356   // (or (or (or (and), (and)), (and)), (and))
3357   if (N0.getOpcode() != ISD::OR)
3358     return SDValue();
3359   SDValue N00 = N0.getOperand(0);
3360   SDValue N01 = N0.getOperand(1);
3361   SDNode *Parts[4] = {};
3362
3363   if (N1.getOpcode() == ISD::OR &&
3364       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3365     // (or (or (and), (and)), (or (and), (and)))
3366     SDValue N000 = N00.getOperand(0);
3367     if (!isBSwapHWordElement(N000, Parts))
3368       return SDValue();
3369
3370     SDValue N001 = N00.getOperand(1);
3371     if (!isBSwapHWordElement(N001, Parts))
3372       return SDValue();
3373     SDValue N010 = N01.getOperand(0);
3374     if (!isBSwapHWordElement(N010, Parts))
3375       return SDValue();
3376     SDValue N011 = N01.getOperand(1);
3377     if (!isBSwapHWordElement(N011, Parts))
3378       return SDValue();
3379   } else {
3380     // (or (or (or (and), (and)), (and)), (and))
3381     if (!isBSwapHWordElement(N1, Parts))
3382       return SDValue();
3383     if (!isBSwapHWordElement(N01, Parts))
3384       return SDValue();
3385     if (N00.getOpcode() != ISD::OR)
3386       return SDValue();
3387     SDValue N000 = N00.getOperand(0);
3388     if (!isBSwapHWordElement(N000, Parts))
3389       return SDValue();
3390     SDValue N001 = N00.getOperand(1);
3391     if (!isBSwapHWordElement(N001, Parts))
3392       return SDValue();
3393   }
3394
3395   // Make sure the parts are all coming from the same node.
3396   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3397     return SDValue();
3398
3399   SDLoc DL(N);
3400   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3401                               SDValue(Parts[0], 0));
3402
3403   // Result of the bswap should be rotated by 16. If it's not legal, then
3404   // do  (x << 16) | (x >> 16).
3405   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3406   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3407     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3408   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3409     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3410   return DAG.getNode(ISD::OR, DL, VT,
3411                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3412                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3413 }
3414
3415 /// This contains all DAGCombine rules which reduce two values combined by
3416 /// an Or operation to a single value \see visitANDLike().
3417 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3418   EVT VT = N1.getValueType();
3419   // fold (or x, undef) -> -1
3420   if (!LegalOperations &&
3421       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3422     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3423     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3424                            SDLoc(LocReference), VT);
3425   }
3426   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3427   SDValue LL, LR, RL, RR, CC0, CC1;
3428   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3429     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3430     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3431
3432     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3433         LL.getValueType().isInteger()) {
3434       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3435       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3436       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3437           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3438         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3439                                      LR.getValueType(), LL, RL);
3440         AddToWorklist(ORNode.getNode());
3441         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3442       }
3443       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3444       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3445       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3446           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3447         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3448                                       LR.getValueType(), LL, RL);
3449         AddToWorklist(ANDNode.getNode());
3450         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3451       }
3452     }
3453     // canonicalize equivalent to ll == rl
3454     if (LL == RR && LR == RL) {
3455       Op1 = ISD::getSetCCSwappedOperands(Op1);
3456       std::swap(RL, RR);
3457     }
3458     if (LL == RL && LR == RR) {
3459       bool isInteger = LL.getValueType().isInteger();
3460       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3461       if (Result != ISD::SETCC_INVALID &&
3462           (!LegalOperations ||
3463            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3464             TLI.isOperationLegal(ISD::SETCC,
3465               getSetCCResultType(N0.getValueType())))))
3466         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3467                             LL, LR, Result);
3468     }
3469   }
3470
3471   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3472   if (N0.getOpcode() == ISD::AND &&
3473       N1.getOpcode() == ISD::AND &&
3474       N0.getOperand(1).getOpcode() == ISD::Constant &&
3475       N1.getOperand(1).getOpcode() == ISD::Constant &&
3476       // Don't increase # computations.
3477       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3478     // We can only do this xform if we know that bits from X that are set in C2
3479     // but not in C1 are already zero.  Likewise for Y.
3480     const APInt &LHSMask =
3481       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3482     const APInt &RHSMask =
3483       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3484
3485     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3486         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3487       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3488                               N0.getOperand(0), N1.getOperand(0));
3489       SDLoc DL(LocReference);
3490       return DAG.getNode(ISD::AND, DL, VT, X,
3491                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3492     }
3493   }
3494
3495   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3496   if (N0.getOpcode() == ISD::AND &&
3497       N1.getOpcode() == ISD::AND &&
3498       N0.getOperand(0) == N1.getOperand(0) &&
3499       // Don't increase # computations.
3500       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3501     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3502                             N0.getOperand(1), N1.getOperand(1));
3503     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3504   }
3505
3506   return SDValue();
3507 }
3508
3509 SDValue DAGCombiner::visitOR(SDNode *N) {
3510   SDValue N0 = N->getOperand(0);
3511   SDValue N1 = N->getOperand(1);
3512   EVT VT = N1.getValueType();
3513
3514   // fold vector ops
3515   if (VT.isVector()) {
3516     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3517       return FoldedVOp;
3518
3519     // fold (or x, 0) -> x, vector edition
3520     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3521       return N1;
3522     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3523       return N0;
3524
3525     // fold (or x, -1) -> -1, vector edition
3526     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3527       // do not return N0, because undef node may exist in N0
3528       return DAG.getConstant(
3529           APInt::getAllOnesValue(
3530               N0.getValueType().getScalarType().getSizeInBits()),
3531           SDLoc(N), N0.getValueType());
3532     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3533       // do not return N1, because undef node may exist in N1
3534       return DAG.getConstant(
3535           APInt::getAllOnesValue(
3536               N1.getValueType().getScalarType().getSizeInBits()),
3537           SDLoc(N), N1.getValueType());
3538
3539     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3540     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3541     // Do this only if the resulting shuffle is legal.
3542     if (isa<ShuffleVectorSDNode>(N0) &&
3543         isa<ShuffleVectorSDNode>(N1) &&
3544         // Avoid folding a node with illegal type.
3545         TLI.isTypeLegal(VT) &&
3546         N0->getOperand(1) == N1->getOperand(1) &&
3547         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3548       bool CanFold = true;
3549       unsigned NumElts = VT.getVectorNumElements();
3550       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3551       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3552       // We construct two shuffle masks:
3553       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3554       // and N1 as the second operand.
3555       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3556       // and N0 as the second operand.
3557       // We do this because OR is commutable and therefore there might be
3558       // two ways to fold this node into a shuffle.
3559       SmallVector<int,4> Mask1;
3560       SmallVector<int,4> Mask2;
3561
3562       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3563         int M0 = SV0->getMaskElt(i);
3564         int M1 = SV1->getMaskElt(i);
3565
3566         // Both shuffle indexes are undef. Propagate Undef.
3567         if (M0 < 0 && M1 < 0) {
3568           Mask1.push_back(M0);
3569           Mask2.push_back(M0);
3570           continue;
3571         }
3572
3573         if (M0 < 0 || M1 < 0 ||
3574             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3575             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3576           CanFold = false;
3577           break;
3578         }
3579
3580         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3581         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3582       }
3583
3584       if (CanFold) {
3585         // Fold this sequence only if the resulting shuffle is 'legal'.
3586         if (TLI.isShuffleMaskLegal(Mask1, VT))
3587           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3588                                       N1->getOperand(0), &Mask1[0]);
3589         if (TLI.isShuffleMaskLegal(Mask2, VT))
3590           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3591                                       N0->getOperand(0), &Mask2[0]);
3592       }
3593     }
3594   }
3595
3596   // fold (or c1, c2) -> c1|c2
3597   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3598   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3599   if (N0C && N1C)
3600     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3601   // canonicalize constant to RHS
3602   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3603      !isConstantIntBuildVectorOrConstantInt(N1))
3604     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3605   // fold (or x, 0) -> x
3606   if (N1C && N1C->isNullValue())
3607     return N0;
3608   // fold (or x, -1) -> -1
3609   if (N1C && N1C->isAllOnesValue())
3610     return N1;
3611   // fold (or x, c) -> c iff (x & ~c) == 0
3612   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3613     return N1;
3614
3615   if (SDValue Combined = visitORLike(N0, N1, N))
3616     return Combined;
3617
3618   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3619   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3620   if (BSwap.getNode())
3621     return BSwap;
3622   BSwap = MatchBSwapHWordLow(N, N0, N1);
3623   if (BSwap.getNode())
3624     return BSwap;
3625
3626   // reassociate or
3627   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3628     return ROR;
3629   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3630   // iff (c1 & c2) == 0.
3631   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3632              isa<ConstantSDNode>(N0.getOperand(1))) {
3633     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3634     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3635       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3636                                                    N1C, C1))
3637         return DAG.getNode(
3638             ISD::AND, SDLoc(N), VT,
3639             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3640       return SDValue();
3641     }
3642   }
3643   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3644   if (N0.getOpcode() == N1.getOpcode()) {
3645     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3646     if (Tmp.getNode()) return Tmp;
3647   }
3648
3649   // See if this is some rotate idiom.
3650   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3651     return SDValue(Rot, 0);
3652
3653   // Simplify the operands using demanded-bits information.
3654   if (!VT.isVector() &&
3655       SimplifyDemandedBits(SDValue(N, 0)))
3656     return SDValue(N, 0);
3657
3658   return SDValue();
3659 }
3660
3661 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3662 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3663   if (Op.getOpcode() == ISD::AND) {
3664     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3665       Mask = Op.getOperand(1);
3666       Op = Op.getOperand(0);
3667     } else {
3668       return false;
3669     }
3670   }
3671
3672   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3673     Shift = Op;
3674     return true;
3675   }
3676
3677   return false;
3678 }
3679
3680 // Return true if we can prove that, whenever Neg and Pos are both in the
3681 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3682 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3683 //
3684 //     (or (shift1 X, Neg), (shift2 X, Pos))
3685 //
3686 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3687 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3688 // to consider shift amounts with defined behavior.
3689 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3690   // If OpSize is a power of 2 then:
3691   //
3692   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3693   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3694   //
3695   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3696   // for the stronger condition:
3697   //
3698   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3699   //
3700   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3701   // we can just replace Neg with Neg' for the rest of the function.
3702   //
3703   // In other cases we check for the even stronger condition:
3704   //
3705   //     Neg == OpSize - Pos                                    [B]
3706   //
3707   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3708   // behavior if Pos == 0 (and consequently Neg == OpSize).
3709   //
3710   // We could actually use [A] whenever OpSize is a power of 2, but the
3711   // only extra cases that it would match are those uninteresting ones
3712   // where Neg and Pos are never in range at the same time.  E.g. for
3713   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3714   // as well as (sub 32, Pos), but:
3715   //
3716   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3717   //
3718   // always invokes undefined behavior for 32-bit X.
3719   //
3720   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3721   unsigned MaskLoBits = 0;
3722   if (Neg.getOpcode() == ISD::AND &&
3723       isPowerOf2_64(OpSize) &&
3724       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3725       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3726     Neg = Neg.getOperand(0);
3727     MaskLoBits = Log2_64(OpSize);
3728   }
3729
3730   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3731   if (Neg.getOpcode() != ISD::SUB)
3732     return 0;
3733   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3734   if (!NegC)
3735     return 0;
3736   SDValue NegOp1 = Neg.getOperand(1);
3737
3738   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3739   // Pos'.  The truncation is redundant for the purpose of the equality.
3740   if (MaskLoBits &&
3741       Pos.getOpcode() == ISD::AND &&
3742       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3743       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3744     Pos = Pos.getOperand(0);
3745
3746   // The condition we need is now:
3747   //
3748   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3749   //
3750   // If NegOp1 == Pos then we need:
3751   //
3752   //              OpSize & Mask == NegC & Mask
3753   //
3754   // (because "x & Mask" is a truncation and distributes through subtraction).
3755   APInt Width;
3756   if (Pos == NegOp1)
3757     Width = NegC->getAPIntValue();
3758   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3759   // Then the condition we want to prove becomes:
3760   //
3761   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3762   //
3763   // which, again because "x & Mask" is a truncation, becomes:
3764   //
3765   //                NegC & Mask == (OpSize - PosC) & Mask
3766   //              OpSize & Mask == (NegC + PosC) & Mask
3767   else if (Pos.getOpcode() == ISD::ADD &&
3768            Pos.getOperand(0) == NegOp1 &&
3769            Pos.getOperand(1).getOpcode() == ISD::Constant)
3770     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3771              NegC->getAPIntValue());
3772   else
3773     return false;
3774
3775   // Now we just need to check that OpSize & Mask == Width & Mask.
3776   if (MaskLoBits)
3777     // Opsize & Mask is 0 since Mask is Opsize - 1.
3778     return Width.getLoBits(MaskLoBits) == 0;
3779   return Width == OpSize;
3780 }
3781
3782 // A subroutine of MatchRotate used once we have found an OR of two opposite
3783 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3784 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3785 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3786 // Neg with outer conversions stripped away.
3787 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3788                                        SDValue Neg, SDValue InnerPos,
3789                                        SDValue InnerNeg, unsigned PosOpcode,
3790                                        unsigned NegOpcode, SDLoc DL) {
3791   // fold (or (shl x, (*ext y)),
3792   //          (srl x, (*ext (sub 32, y)))) ->
3793   //   (rotl x, y) or (rotr x, (sub 32, y))
3794   //
3795   // fold (or (shl x, (*ext (sub 32, y))),
3796   //          (srl x, (*ext y))) ->
3797   //   (rotr x, y) or (rotl x, (sub 32, y))
3798   EVT VT = Shifted.getValueType();
3799   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3800     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3801     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3802                        HasPos ? Pos : Neg).getNode();
3803   }
3804
3805   return nullptr;
3806 }
3807
3808 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3809 // idioms for rotate, and if the target supports rotation instructions, generate
3810 // a rot[lr].
3811 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3812   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3813   EVT VT = LHS.getValueType();
3814   if (!TLI.isTypeLegal(VT)) return nullptr;
3815
3816   // The target must have at least one rotate flavor.
3817   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3818   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3819   if (!HasROTL && !HasROTR) return nullptr;
3820
3821   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3822   SDValue LHSShift;   // The shift.
3823   SDValue LHSMask;    // AND value if any.
3824   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3825     return nullptr; // Not part of a rotate.
3826
3827   SDValue RHSShift;   // The shift.
3828   SDValue RHSMask;    // AND value if any.
3829   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3830     return nullptr; // Not part of a rotate.
3831
3832   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3833     return nullptr;   // Not shifting the same value.
3834
3835   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3836     return nullptr;   // Shifts must disagree.
3837
3838   // Canonicalize shl to left side in a shl/srl pair.
3839   if (RHSShift.getOpcode() == ISD::SHL) {
3840     std::swap(LHS, RHS);
3841     std::swap(LHSShift, RHSShift);
3842     std::swap(LHSMask , RHSMask );
3843   }
3844
3845   unsigned OpSizeInBits = VT.getSizeInBits();
3846   SDValue LHSShiftArg = LHSShift.getOperand(0);
3847   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3848   SDValue RHSShiftArg = RHSShift.getOperand(0);
3849   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3850
3851   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3852   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3853   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3854       RHSShiftAmt.getOpcode() == ISD::Constant) {
3855     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3856     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3857     if ((LShVal + RShVal) != OpSizeInBits)
3858       return nullptr;
3859
3860     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3861                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3862
3863     // If there is an AND of either shifted operand, apply it to the result.
3864     if (LHSMask.getNode() || RHSMask.getNode()) {
3865       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3866
3867       if (LHSMask.getNode()) {
3868         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3869         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3870       }
3871       if (RHSMask.getNode()) {
3872         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3873         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3874       }
3875
3876       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3877     }
3878
3879     return Rot.getNode();
3880   }
3881
3882   // If there is a mask here, and we have a variable shift, we can't be sure
3883   // that we're masking out the right stuff.
3884   if (LHSMask.getNode() || RHSMask.getNode())
3885     return nullptr;
3886
3887   // If the shift amount is sign/zext/any-extended just peel it off.
3888   SDValue LExtOp0 = LHSShiftAmt;
3889   SDValue RExtOp0 = RHSShiftAmt;
3890   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3894       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3895        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3896        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3897        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3898     LExtOp0 = LHSShiftAmt.getOperand(0);
3899     RExtOp0 = RHSShiftAmt.getOperand(0);
3900   }
3901
3902   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3903                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3904   if (TryL)
3905     return TryL;
3906
3907   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3908                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3909   if (TryR)
3910     return TryR;
3911
3912   return nullptr;
3913 }
3914
3915 SDValue DAGCombiner::visitXOR(SDNode *N) {
3916   SDValue N0 = N->getOperand(0);
3917   SDValue N1 = N->getOperand(1);
3918   EVT VT = N0.getValueType();
3919
3920   // fold vector ops
3921   if (VT.isVector()) {
3922     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3923       return FoldedVOp;
3924
3925     // fold (xor x, 0) -> x, vector edition
3926     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3927       return N1;
3928     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3929       return N0;
3930   }
3931
3932   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3933   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3934     return DAG.getConstant(0, SDLoc(N), VT);
3935   // fold (xor x, undef) -> undef
3936   if (N0.getOpcode() == ISD::UNDEF)
3937     return N0;
3938   if (N1.getOpcode() == ISD::UNDEF)
3939     return N1;
3940   // fold (xor c1, c2) -> c1^c2
3941   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3942   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3943   if (N0C && N1C)
3944     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3945   // canonicalize constant to RHS
3946   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3947      !isConstantIntBuildVectorOrConstantInt(N1))
3948     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3949   // fold (xor x, 0) -> x
3950   if (N1C && N1C->isNullValue())
3951     return N0;
3952   // reassociate xor
3953   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3954     return RXOR;
3955
3956   // fold !(x cc y) -> (x !cc y)
3957   SDValue LHS, RHS, CC;
3958   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3959     bool isInt = LHS.getValueType().isInteger();
3960     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3961                                                isInt);
3962
3963     if (!LegalOperations ||
3964         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3965       switch (N0.getOpcode()) {
3966       default:
3967         llvm_unreachable("Unhandled SetCC Equivalent!");
3968       case ISD::SETCC:
3969         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3970       case ISD::SELECT_CC:
3971         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3972                                N0.getOperand(3), NotCC);
3973       }
3974     }
3975   }
3976
3977   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3978   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3979       N0.getNode()->hasOneUse() &&
3980       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3981     SDValue V = N0.getOperand(0);
3982     SDLoc DL(N0);
3983     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3984                     DAG.getConstant(1, DL, V.getValueType()));
3985     AddToWorklist(V.getNode());
3986     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3987   }
3988
3989   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3990   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3991       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3992     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3993     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3994       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3995       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3996       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3997       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3998       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3999     }
4000   }
4001   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
4002   if (N1C && N1C->isAllOnesValue() &&
4003       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4004     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4005     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4006       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4007       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4008       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4009       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4010       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4011     }
4012   }
4013   // fold (xor (and x, y), y) -> (and (not x), y)
4014   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4015       N0->getOperand(1) == N1) {
4016     SDValue X = N0->getOperand(0);
4017     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4018     AddToWorklist(NotX.getNode());
4019     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4020   }
4021   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4022   if (N1C && N0.getOpcode() == ISD::XOR) {
4023     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4024     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4025     if (N00C) {
4026       SDLoc DL(N);
4027       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4028                          DAG.getConstant(N1C->getAPIntValue() ^
4029                                          N00C->getAPIntValue(), DL, VT));
4030     }
4031     if (N01C) {
4032       SDLoc DL(N);
4033       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4034                          DAG.getConstant(N1C->getAPIntValue() ^
4035                                          N01C->getAPIntValue(), DL, VT));
4036     }
4037   }
4038   // fold (xor x, x) -> 0
4039   if (N0 == N1)
4040     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4041
4042   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4043   // Here is a concrete example of this equivalence:
4044   // i16   x ==  14
4045   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4046   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4047   //
4048   // =>
4049   //
4050   // i16     ~1      == 0b1111111111111110
4051   // i16 rol(~1, 14) == 0b1011111111111111
4052   //
4053   // Some additional tips to help conceptualize this transform:
4054   // - Try to see the operation as placing a single zero in a value of all ones.
4055   // - There exists no value for x which would allow the result to contain zero.
4056   // - Values of x larger than the bitwidth are undefined and do not require a
4057   //   consistent result.
4058   // - Pushing the zero left requires shifting one bits in from the right.
4059   // A rotate left of ~1 is a nice way of achieving the desired result.
4060   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4061     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4062       if (N0.getOpcode() == ISD::SHL)
4063         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4064           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4065             SDLoc DL(N);
4066             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4067                                N0.getOperand(1));
4068           }
4069
4070   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4071   if (N0.getOpcode() == N1.getOpcode()) {
4072     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4073     if (Tmp.getNode()) return Tmp;
4074   }
4075
4076   // Simplify the expression using non-local knowledge.
4077   if (!VT.isVector() &&
4078       SimplifyDemandedBits(SDValue(N, 0)))
4079     return SDValue(N, 0);
4080
4081   return SDValue();
4082 }
4083
4084 /// Handle transforms common to the three shifts, when the shift amount is a
4085 /// constant.
4086 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4087   // We can't and shouldn't fold opaque constants.
4088   if (Amt->isOpaque())
4089     return SDValue();
4090
4091   SDNode *LHS = N->getOperand(0).getNode();
4092   if (!LHS->hasOneUse()) return SDValue();
4093
4094   // We want to pull some binops through shifts, so that we have (and (shift))
4095   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4096   // thing happens with address calculations, so it's important to canonicalize
4097   // it.
4098   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4099
4100   switch (LHS->getOpcode()) {
4101   default: return SDValue();
4102   case ISD::OR:
4103   case ISD::XOR:
4104     HighBitSet = false; // We can only transform sra if the high bit is clear.
4105     break;
4106   case ISD::AND:
4107     HighBitSet = true;  // We can only transform sra if the high bit is set.
4108     break;
4109   case ISD::ADD:
4110     if (N->getOpcode() != ISD::SHL)
4111       return SDValue(); // only shl(add) not sr[al](add).
4112     HighBitSet = false; // We can only transform sra if the high bit is clear.
4113     break;
4114   }
4115
4116   // We require the RHS of the binop to be a constant and not opaque as well.
4117   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4118   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4119
4120   // FIXME: disable this unless the input to the binop is a shift by a constant.
4121   // If it is not a shift, it pessimizes some common cases like:
4122   //
4123   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4124   //    int bar(int *X, int i) { return X[i & 255]; }
4125   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4126   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4127        BinOpLHSVal->getOpcode() != ISD::SRA &&
4128        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4129       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4130     return SDValue();
4131
4132   EVT VT = N->getValueType(0);
4133
4134   // If this is a signed shift right, and the high bit is modified by the
4135   // logical operation, do not perform the transformation. The highBitSet
4136   // boolean indicates the value of the high bit of the constant which would
4137   // cause it to be modified for this operation.
4138   if (N->getOpcode() == ISD::SRA) {
4139     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4140     if (BinOpRHSSignSet != HighBitSet)
4141       return SDValue();
4142   }
4143
4144   if (!TLI.isDesirableToCommuteWithShift(LHS))
4145     return SDValue();
4146
4147   // Fold the constants, shifting the binop RHS by the shift amount.
4148   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4149                                N->getValueType(0),
4150                                LHS->getOperand(1), N->getOperand(1));
4151   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4152
4153   // Create the new shift.
4154   SDValue NewShift = DAG.getNode(N->getOpcode(),
4155                                  SDLoc(LHS->getOperand(0)),
4156                                  VT, LHS->getOperand(0), N->getOperand(1));
4157
4158   // Create the new binop.
4159   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4160 }
4161
4162 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4163   assert(N->getOpcode() == ISD::TRUNCATE);
4164   assert(N->getOperand(0).getOpcode() == ISD::AND);
4165
4166   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4167   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4168     SDValue N01 = N->getOperand(0).getOperand(1);
4169
4170     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4171       EVT TruncVT = N->getValueType(0);
4172       SDValue N00 = N->getOperand(0).getOperand(0);
4173       APInt TruncC = N01C->getAPIntValue();
4174       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4175       SDLoc DL(N);
4176
4177       return DAG.getNode(ISD::AND, DL, TruncVT,
4178                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4179                          DAG.getConstant(TruncC, DL, TruncVT));
4180     }
4181   }
4182
4183   return SDValue();
4184 }
4185
4186 SDValue DAGCombiner::visitRotate(SDNode *N) {
4187   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4188   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4189       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4190     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4191     if (NewOp1.getNode())
4192       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4193                          N->getOperand(0), NewOp1);
4194   }
4195   return SDValue();
4196 }
4197
4198 SDValue DAGCombiner::visitSHL(SDNode *N) {
4199   SDValue N0 = N->getOperand(0);
4200   SDValue N1 = N->getOperand(1);
4201   EVT VT = N0.getValueType();
4202   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4203
4204   // fold vector ops
4205   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4206   if (VT.isVector()) {
4207     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4208       return FoldedVOp;
4209
4210     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4211     // If setcc produces all-one true value then:
4212     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4213     if (N1CV && N1CV->isConstant()) {
4214       if (N0.getOpcode() == ISD::AND) {
4215         SDValue N00 = N0->getOperand(0);
4216         SDValue N01 = N0->getOperand(1);
4217         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4218
4219         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4220             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4221                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4222           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4223                                                      N01CV, N1CV))
4224             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4225         }
4226       } else {
4227         N1C = isConstOrConstSplat(N1);
4228       }
4229     }
4230   }
4231
4232   // fold (shl c1, c2) -> c1<<c2
4233   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4234   if (N0C && N1C)
4235     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4236   // fold (shl 0, x) -> 0
4237   if (N0C && N0C->isNullValue())
4238     return N0;
4239   // fold (shl x, c >= size(x)) -> undef
4240   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4241     return DAG.getUNDEF(VT);
4242   // fold (shl x, 0) -> x
4243   if (N1C && N1C->isNullValue())
4244     return N0;
4245   // fold (shl undef, x) -> 0
4246   if (N0.getOpcode() == ISD::UNDEF)
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // if (shl x, c) is known to be zero, return 0
4249   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4250                             APInt::getAllOnesValue(OpSizeInBits)))
4251     return DAG.getConstant(0, SDLoc(N), VT);
4252   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4253   if (N1.getOpcode() == ISD::TRUNCATE &&
4254       N1.getOperand(0).getOpcode() == ISD::AND) {
4255     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4256     if (NewOp1.getNode())
4257       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4258   }
4259
4260   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4261     return SDValue(N, 0);
4262
4263   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4264   if (N1C && N0.getOpcode() == ISD::SHL) {
4265     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4266       uint64_t c1 = N0C1->getZExtValue();
4267       uint64_t c2 = N1C->getZExtValue();
4268       SDLoc DL(N);
4269       if (c1 + c2 >= OpSizeInBits)
4270         return DAG.getConstant(0, DL, VT);
4271       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4272                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4273     }
4274   }
4275
4276   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4277   // For this to be valid, the second form must not preserve any of the bits
4278   // that are shifted out by the inner shift in the first form.  This means
4279   // the outer shift size must be >= the number of bits added by the ext.
4280   // As a corollary, we don't care what kind of ext it is.
4281   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4282               N0.getOpcode() == ISD::ANY_EXTEND ||
4283               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4284       N0.getOperand(0).getOpcode() == ISD::SHL) {
4285     SDValue N0Op0 = N0.getOperand(0);
4286     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4287       uint64_t c1 = N0Op0C1->getZExtValue();
4288       uint64_t c2 = N1C->getZExtValue();
4289       EVT InnerShiftVT = N0Op0.getValueType();
4290       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4291       if (c2 >= OpSizeInBits - InnerShiftSize) {
4292         SDLoc DL(N0);
4293         if (c1 + c2 >= OpSizeInBits)
4294           return DAG.getConstant(0, DL, VT);
4295         return DAG.getNode(ISD::SHL, DL, VT,
4296                            DAG.getNode(N0.getOpcode(), DL, VT,
4297                                        N0Op0->getOperand(0)),
4298                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4299       }
4300     }
4301   }
4302
4303   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4304   // Only fold this if the inner zext has no other uses to avoid increasing
4305   // the total number of instructions.
4306   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4307       N0.getOperand(0).getOpcode() == ISD::SRL) {
4308     SDValue N0Op0 = N0.getOperand(0);
4309     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4310       uint64_t c1 = N0Op0C1->getZExtValue();
4311       if (c1 < VT.getScalarSizeInBits()) {
4312         uint64_t c2 = N1C->getZExtValue();
4313         if (c1 == c2) {
4314           SDValue NewOp0 = N0.getOperand(0);
4315           EVT CountVT = NewOp0.getOperand(1).getValueType();
4316           SDLoc DL(N);
4317           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4318                                        NewOp0,
4319                                        DAG.getConstant(c2, DL, CountVT));
4320           AddToWorklist(NewSHL.getNode());
4321           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4322         }
4323       }
4324     }
4325   }
4326
4327   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4328   //                               (and (srl x, (sub c1, c2), MASK)
4329   // Only fold this if the inner shift has no other uses -- if it does, folding
4330   // this will increase the total number of instructions.
4331   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4332     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4333       uint64_t c1 = N0C1->getZExtValue();
4334       if (c1 < OpSizeInBits) {
4335         uint64_t c2 = N1C->getZExtValue();
4336         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4337         SDValue Shift;
4338         if (c2 > c1) {
4339           Mask = Mask.shl(c2 - c1);
4340           SDLoc DL(N);
4341           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4342                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4343         } else {
4344           Mask = Mask.lshr(c1 - c2);
4345           SDLoc DL(N);
4346           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4347                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4348         }
4349         SDLoc DL(N0);
4350         return DAG.getNode(ISD::AND, DL, VT, Shift,
4351                            DAG.getConstant(Mask, DL, VT));
4352       }
4353     }
4354   }
4355   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4356   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4357     unsigned BitSize = VT.getScalarSizeInBits();
4358     SDLoc DL(N);
4359     SDValue HiBitsMask =
4360       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4361                                             BitSize - N1C->getZExtValue()),
4362                       DL, VT);
4363     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4364                        HiBitsMask);
4365   }
4366
4367   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4368   // Variant of version done on multiply, except mul by a power of 2 is turned
4369   // into a shift.
4370   APInt Val;
4371   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4372       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4373        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4374     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4375     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4376     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4377   }
4378
4379   if (N1C) {
4380     SDValue NewSHL = visitShiftByConstant(N, N1C);
4381     if (NewSHL.getNode())
4382       return NewSHL;
4383   }
4384
4385   return SDValue();
4386 }
4387
4388 SDValue DAGCombiner::visitSRA(SDNode *N) {
4389   SDValue N0 = N->getOperand(0);
4390   SDValue N1 = N->getOperand(1);
4391   EVT VT = N0.getValueType();
4392   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4393
4394   // fold vector ops
4395   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4396   if (VT.isVector()) {
4397     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4398       return FoldedVOp;
4399
4400     N1C = isConstOrConstSplat(N1);
4401   }
4402
4403   // fold (sra c1, c2) -> (sra c1, c2)
4404   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4405   if (N0C && N1C)
4406     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4407   // fold (sra 0, x) -> 0
4408   if (N0C && N0C->isNullValue())
4409     return N0;
4410   // fold (sra -1, x) -> -1
4411   if (N0C && N0C->isAllOnesValue())
4412     return N0;
4413   // fold (sra x, (setge c, size(x))) -> undef
4414   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4415     return DAG.getUNDEF(VT);
4416   // fold (sra x, 0) -> x
4417   if (N1C && N1C->isNullValue())
4418     return N0;
4419   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4420   // sext_inreg.
4421   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4422     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4423     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4424     if (VT.isVector())
4425       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4426                                ExtVT, VT.getVectorNumElements());
4427     if ((!LegalOperations ||
4428          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4429       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4430                          N0.getOperand(0), DAG.getValueType(ExtVT));
4431   }
4432
4433   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4434   if (N1C && N0.getOpcode() == ISD::SRA) {
4435     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4436       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4437       if (Sum >= OpSizeInBits)
4438         Sum = OpSizeInBits - 1;
4439       SDLoc DL(N);
4440       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4441                          DAG.getConstant(Sum, DL, N1.getValueType()));
4442     }
4443   }
4444
4445   // fold (sra (shl X, m), (sub result_size, n))
4446   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4447   // result_size - n != m.
4448   // If truncate is free for the target sext(shl) is likely to result in better
4449   // code.
4450   if (N0.getOpcode() == ISD::SHL && N1C) {
4451     // Get the two constanst of the shifts, CN0 = m, CN = n.
4452     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4453     if (N01C) {
4454       LLVMContext &Ctx = *DAG.getContext();
4455       // Determine what the truncate's result bitsize and type would be.
4456       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4457
4458       if (VT.isVector())
4459         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4460
4461       // Determine the residual right-shift amount.
4462       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4463
4464       // If the shift is not a no-op (in which case this should be just a sign
4465       // extend already), the truncated to type is legal, sign_extend is legal
4466       // on that type, and the truncate to that type is both legal and free,
4467       // perform the transform.
4468       if ((ShiftAmt > 0) &&
4469           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4470           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4471           TLI.isTruncateFree(VT, TruncVT)) {
4472
4473         SDLoc DL(N);
4474         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4475             getShiftAmountTy(N0.getOperand(0).getValueType()));
4476         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4477                                     N0.getOperand(0), Amt);
4478         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4479                                     Shift);
4480         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4481                            N->getValueType(0), Trunc);
4482       }
4483     }
4484   }
4485
4486   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4487   if (N1.getOpcode() == ISD::TRUNCATE &&
4488       N1.getOperand(0).getOpcode() == ISD::AND) {
4489     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4490     if (NewOp1.getNode())
4491       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4492   }
4493
4494   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4495   //      if c1 is equal to the number of bits the trunc removes
4496   if (N0.getOpcode() == ISD::TRUNCATE &&
4497       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4498        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4499       N0.getOperand(0).hasOneUse() &&
4500       N0.getOperand(0).getOperand(1).hasOneUse() &&
4501       N1C) {
4502     SDValue N0Op0 = N0.getOperand(0);
4503     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4504       unsigned LargeShiftVal = LargeShift->getZExtValue();
4505       EVT LargeVT = N0Op0.getValueType();
4506
4507       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4508         SDLoc DL(N);
4509         SDValue Amt =
4510           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4511                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4512         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4513                                   N0Op0.getOperand(0), Amt);
4514         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4515       }
4516     }
4517   }
4518
4519   // Simplify, based on bits shifted out of the LHS.
4520   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4521     return SDValue(N, 0);
4522
4523
4524   // If the sign bit is known to be zero, switch this to a SRL.
4525   if (DAG.SignBitIsZero(N0))
4526     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4527
4528   if (N1C) {
4529     SDValue NewSRA = visitShiftByConstant(N, N1C);
4530     if (NewSRA.getNode())
4531       return NewSRA;
4532   }
4533
4534   return SDValue();
4535 }
4536
4537 SDValue DAGCombiner::visitSRL(SDNode *N) {
4538   SDValue N0 = N->getOperand(0);
4539   SDValue N1 = N->getOperand(1);
4540   EVT VT = N0.getValueType();
4541   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4542
4543   // fold vector ops
4544   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4545   if (VT.isVector()) {
4546     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4547       return FoldedVOp;
4548
4549     N1C = isConstOrConstSplat(N1);
4550   }
4551
4552   // fold (srl c1, c2) -> c1 >>u c2
4553   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4554   if (N0C && N1C)
4555     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4556   // fold (srl 0, x) -> 0
4557   if (N0C && N0C->isNullValue())
4558     return N0;
4559   // fold (srl x, c >= size(x)) -> undef
4560   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4561     return DAG.getUNDEF(VT);
4562   // fold (srl x, 0) -> x
4563   if (N1C && N1C->isNullValue())
4564     return N0;
4565   // if (srl x, c) is known to be zero, return 0
4566   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4567                                    APInt::getAllOnesValue(OpSizeInBits)))
4568     return DAG.getConstant(0, SDLoc(N), VT);
4569
4570   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4571   if (N1C && N0.getOpcode() == ISD::SRL) {
4572     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4573       uint64_t c1 = N01C->getZExtValue();
4574       uint64_t c2 = N1C->getZExtValue();
4575       SDLoc DL(N);
4576       if (c1 + c2 >= OpSizeInBits)
4577         return DAG.getConstant(0, DL, VT);
4578       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4579                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4580     }
4581   }
4582
4583   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4584   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4585       N0.getOperand(0).getOpcode() == ISD::SRL &&
4586       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4587     uint64_t c1 =
4588       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4589     uint64_t c2 = N1C->getZExtValue();
4590     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4591     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4592     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4593     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4594     if (c1 + OpSizeInBits == InnerShiftSize) {
4595       SDLoc DL(N0);
4596       if (c1 + c2 >= InnerShiftSize)
4597         return DAG.getConstant(0, DL, VT);
4598       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4599                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4600                                      N0.getOperand(0)->getOperand(0),
4601                                      DAG.getConstant(c1 + c2, DL,
4602                                                      ShiftCountVT)));
4603     }
4604   }
4605
4606   // fold (srl (shl x, c), c) -> (and x, cst2)
4607   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4608     unsigned BitSize = N0.getScalarValueSizeInBits();
4609     if (BitSize <= 64) {
4610       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4611       SDLoc DL(N);
4612       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4613                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4614     }
4615   }
4616
4617   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4618   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4619     // Shifting in all undef bits?
4620     EVT SmallVT = N0.getOperand(0).getValueType();
4621     unsigned BitSize = SmallVT.getScalarSizeInBits();
4622     if (N1C->getZExtValue() >= BitSize)
4623       return DAG.getUNDEF(VT);
4624
4625     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4626       uint64_t ShiftAmt = N1C->getZExtValue();
4627       SDLoc DL0(N0);
4628       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4629                                        N0.getOperand(0),
4630                           DAG.getConstant(ShiftAmt, DL0,
4631                                           getShiftAmountTy(SmallVT)));
4632       AddToWorklist(SmallShift.getNode());
4633       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4634       SDLoc DL(N);
4635       return DAG.getNode(ISD::AND, DL, VT,
4636                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4637                          DAG.getConstant(Mask, DL, VT));
4638     }
4639   }
4640
4641   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4642   // bit, which is unmodified by sra.
4643   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4644     if (N0.getOpcode() == ISD::SRA)
4645       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4646   }
4647
4648   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4649   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4650       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4651     APInt KnownZero, KnownOne;
4652     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4653
4654     // If any of the input bits are KnownOne, then the input couldn't be all
4655     // zeros, thus the result of the srl will always be zero.
4656     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4657
4658     // If all of the bits input the to ctlz node are known to be zero, then
4659     // the result of the ctlz is "32" and the result of the shift is one.
4660     APInt UnknownBits = ~KnownZero;
4661     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4662
4663     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4664     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4665       // Okay, we know that only that the single bit specified by UnknownBits
4666       // could be set on input to the CTLZ node. If this bit is set, the SRL
4667       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4668       // to an SRL/XOR pair, which is likely to simplify more.
4669       unsigned ShAmt = UnknownBits.countTrailingZeros();
4670       SDValue Op = N0.getOperand(0);
4671
4672       if (ShAmt) {
4673         SDLoc DL(N0);
4674         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4675                   DAG.getConstant(ShAmt, DL,
4676                                   getShiftAmountTy(Op.getValueType())));
4677         AddToWorklist(Op.getNode());
4678       }
4679
4680       SDLoc DL(N);
4681       return DAG.getNode(ISD::XOR, DL, VT,
4682                          Op, DAG.getConstant(1, DL, VT));
4683     }
4684   }
4685
4686   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4687   if (N1.getOpcode() == ISD::TRUNCATE &&
4688       N1.getOperand(0).getOpcode() == ISD::AND) {
4689     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4690     if (NewOp1.getNode())
4691       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4692   }
4693
4694   // fold operands of srl based on knowledge that the low bits are not
4695   // demanded.
4696   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4697     return SDValue(N, 0);
4698
4699   if (N1C) {
4700     SDValue NewSRL = visitShiftByConstant(N, N1C);
4701     if (NewSRL.getNode())
4702       return NewSRL;
4703   }
4704
4705   // Attempt to convert a srl of a load into a narrower zero-extending load.
4706   SDValue NarrowLoad = ReduceLoadWidth(N);
4707   if (NarrowLoad.getNode())
4708     return NarrowLoad;
4709
4710   // Here is a common situation. We want to optimize:
4711   //
4712   //   %a = ...
4713   //   %b = and i32 %a, 2
4714   //   %c = srl i32 %b, 1
4715   //   brcond i32 %c ...
4716   //
4717   // into
4718   //
4719   //   %a = ...
4720   //   %b = and %a, 2
4721   //   %c = setcc eq %b, 0
4722   //   brcond %c ...
4723   //
4724   // However when after the source operand of SRL is optimized into AND, the SRL
4725   // itself may not be optimized further. Look for it and add the BRCOND into
4726   // the worklist.
4727   if (N->hasOneUse()) {
4728     SDNode *Use = *N->use_begin();
4729     if (Use->getOpcode() == ISD::BRCOND)
4730       AddToWorklist(Use);
4731     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4732       // Also look pass the truncate.
4733       Use = *Use->use_begin();
4734       if (Use->getOpcode() == ISD::BRCOND)
4735         AddToWorklist(Use);
4736     }
4737   }
4738
4739   return SDValue();
4740 }
4741
4742 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4743   SDValue N0 = N->getOperand(0);
4744   EVT VT = N->getValueType(0);
4745
4746   // fold (ctlz c1) -> c2
4747   if (isa<ConstantSDNode>(N0))
4748     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4749   return SDValue();
4750 }
4751
4752 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4753   SDValue N0 = N->getOperand(0);
4754   EVT VT = N->getValueType(0);
4755
4756   // fold (ctlz_zero_undef c1) -> c2
4757   if (isa<ConstantSDNode>(N0))
4758     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4759   return SDValue();
4760 }
4761
4762 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4763   SDValue N0 = N->getOperand(0);
4764   EVT VT = N->getValueType(0);
4765
4766   // fold (cttz c1) -> c2
4767   if (isa<ConstantSDNode>(N0))
4768     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4769   return SDValue();
4770 }
4771
4772 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4773   SDValue N0 = N->getOperand(0);
4774   EVT VT = N->getValueType(0);
4775
4776   // fold (cttz_zero_undef c1) -> c2
4777   if (isa<ConstantSDNode>(N0))
4778     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4779   return SDValue();
4780 }
4781
4782 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4783   SDValue N0 = N->getOperand(0);
4784   EVT VT = N->getValueType(0);
4785
4786   // fold (ctpop c1) -> c2
4787   if (isa<ConstantSDNode>(N0))
4788     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4789   return SDValue();
4790 }
4791
4792
4793 /// \brief Generate Min/Max node
4794 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4795                                    SDValue True, SDValue False,
4796                                    ISD::CondCode CC, const TargetLowering &TLI,
4797                                    SelectionDAG &DAG) {
4798   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4799     return SDValue();
4800
4801   switch (CC) {
4802   case ISD::SETOLT:
4803   case ISD::SETOLE:
4804   case ISD::SETLT:
4805   case ISD::SETLE:
4806   case ISD::SETULT:
4807   case ISD::SETULE: {
4808     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4809     if (TLI.isOperationLegal(Opcode, VT))
4810       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4811     return SDValue();
4812   }
4813   case ISD::SETOGT:
4814   case ISD::SETOGE:
4815   case ISD::SETGT:
4816   case ISD::SETGE:
4817   case ISD::SETUGT:
4818   case ISD::SETUGE: {
4819     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4820     if (TLI.isOperationLegal(Opcode, VT))
4821       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4822     return SDValue();
4823   }
4824   default:
4825     return SDValue();
4826   }
4827 }
4828
4829 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4830   SDValue N0 = N->getOperand(0);
4831   SDValue N1 = N->getOperand(1);
4832   SDValue N2 = N->getOperand(2);
4833   EVT VT = N->getValueType(0);
4834   EVT VT0 = N0.getValueType();
4835
4836   // fold (select C, X, X) -> X
4837   if (N1 == N2)
4838     return N1;
4839   // fold (select true, X, Y) -> X
4840   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4841   if (N0C && !N0C->isNullValue())
4842     return N1;
4843   // fold (select false, X, Y) -> Y
4844   if (N0C && N0C->isNullValue())
4845     return N2;
4846   // fold (select C, 1, X) -> (or C, X)
4847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4848   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4849     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4850   // fold (select C, 0, 1) -> (xor C, 1)
4851   // We can't do this reliably if integer based booleans have different contents
4852   // to floating point based booleans. This is because we can't tell whether we
4853   // have an integer-based boolean or a floating-point-based boolean unless we
4854   // can find the SETCC that produced it and inspect its operands. This is
4855   // fairly easy if C is the SETCC node, but it can potentially be
4856   // undiscoverable (or not reasonably discoverable). For example, it could be
4857   // in another basic block or it could require searching a complicated
4858   // expression.
4859   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4860   if (VT.isInteger() &&
4861       (VT0 == MVT::i1 || (VT0.isInteger() &&
4862                           TLI.getBooleanContents(false, false) ==
4863                               TLI.getBooleanContents(false, true) &&
4864                           TLI.getBooleanContents(false, false) ==
4865                               TargetLowering::ZeroOrOneBooleanContent)) &&
4866       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4867     SDValue XORNode;
4868     if (VT == VT0) {
4869       SDLoc DL(N);
4870       return DAG.getNode(ISD::XOR, DL, VT0,
4871                          N0, DAG.getConstant(1, DL, VT0));
4872     }
4873     SDLoc DL0(N0);
4874     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4875                           N0, DAG.getConstant(1, DL0, VT0));
4876     AddToWorklist(XORNode.getNode());
4877     if (VT.bitsGT(VT0))
4878       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4879     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4880   }
4881   // fold (select C, 0, X) -> (and (not C), X)
4882   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4883     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4884     AddToWorklist(NOTNode.getNode());
4885     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4886   }
4887   // fold (select C, X, 1) -> (or (not C), X)
4888   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4889     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4890     AddToWorklist(NOTNode.getNode());
4891     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4892   }
4893   // fold (select C, X, 0) -> (and C, X)
4894   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4895     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4896   // fold (select X, X, Y) -> (or X, Y)
4897   // fold (select X, 1, Y) -> (or X, Y)
4898   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4899     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4900   // fold (select X, Y, X) -> (and X, Y)
4901   // fold (select X, Y, 0) -> (and X, Y)
4902   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4903     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4904
4905   // If we can fold this based on the true/false value, do so.
4906   if (SimplifySelectOps(N, N1, N2))
4907     return SDValue(N, 0);  // Don't revisit N.
4908
4909   // fold selects based on a setcc into other things, such as min/max/abs
4910   if (N0.getOpcode() == ISD::SETCC) {
4911     // select x, y (fcmp lt x, y) -> fminnum x, y
4912     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4913     //
4914     // This is OK if we don't care about what happens if either operand is a
4915     // NaN.
4916     //
4917
4918     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4919     // no signed zeros as well as no nans.
4920     const TargetOptions &Options = DAG.getTarget().Options;
4921     if (Options.UnsafeFPMath &&
4922         VT.isFloatingPoint() && N0.hasOneUse() &&
4923         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4924       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4925
4926       SDValue FMinMax =
4927           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4928                               N1, N2, CC, TLI, DAG);
4929       if (FMinMax)
4930         return FMinMax;
4931     }
4932
4933     if ((!LegalOperations &&
4934          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4935         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4936       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4937                          N0.getOperand(0), N0.getOperand(1),
4938                          N1, N2, N0.getOperand(2));
4939     return SimplifySelect(SDLoc(N), N0, N1, N2);
4940   }
4941
4942   if (VT0 == MVT::i1) {
4943     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4944       // select (and Cond0, Cond1), X, Y
4945       //   -> select Cond0, (select Cond1, X, Y), Y
4946       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4947         SDValue Cond0 = N0->getOperand(0);
4948         SDValue Cond1 = N0->getOperand(1);
4949         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4950                                           N1.getValueType(), Cond1, N1, N2);
4951         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4952                            InnerSelect, N2);
4953       }
4954       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4955       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4956         SDValue Cond0 = N0->getOperand(0);
4957         SDValue Cond1 = N0->getOperand(1);
4958         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4959                                           N1.getValueType(), Cond1, N1, N2);
4960         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4961                            InnerSelect);
4962       }
4963     }
4964
4965     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4966     if (N1->getOpcode() == ISD::SELECT) {
4967       SDValue N1_0 = N1->getOperand(0);
4968       SDValue N1_1 = N1->getOperand(1);
4969       SDValue N1_2 = N1->getOperand(2);
4970       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4971         // Create the actual and node if we can generate good code for it.
4972         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4973           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4974                                     N0, N1_0);
4975           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4976                              N1_1, N2);
4977         }
4978         // Otherwise see if we can optimize the "and" to a better pattern.
4979         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4980           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4981                              N1_1, N2);
4982       }
4983     }
4984     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4985     if (N2->getOpcode() == ISD::SELECT) {
4986       SDValue N2_0 = N2->getOperand(0);
4987       SDValue N2_1 = N2->getOperand(1);
4988       SDValue N2_2 = N2->getOperand(2);
4989       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4990         // Create the actual or node if we can generate good code for it.
4991         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4992           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4993                                    N0, N2_0);
4994           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4995                              N1, N2_2);
4996         }
4997         // Otherwise see if we can optimize to a better pattern.
4998         if (SDValue Combined = visitORLike(N0, N2_0, N))
4999           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
5000                              N1, N2_2);
5001       }
5002     }
5003   }
5004
5005   return SDValue();
5006 }
5007
5008 static
5009 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5010   SDLoc DL(N);
5011   EVT LoVT, HiVT;
5012   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5013
5014   // Split the inputs.
5015   SDValue Lo, Hi, LL, LH, RL, RH;
5016   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5017   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5018
5019   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5020   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5021
5022   return std::make_pair(Lo, Hi);
5023 }
5024
5025 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5026 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5027 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5028   SDLoc dl(N);
5029   SDValue Cond = N->getOperand(0);
5030   SDValue LHS = N->getOperand(1);
5031   SDValue RHS = N->getOperand(2);
5032   EVT VT = N->getValueType(0);
5033   int NumElems = VT.getVectorNumElements();
5034   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5035          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5036          Cond.getOpcode() == ISD::BUILD_VECTOR);
5037
5038   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5039   // binary ones here.
5040   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5041     return SDValue();
5042
5043   // We're sure we have an even number of elements due to the
5044   // concat_vectors we have as arguments to vselect.
5045   // Skip BV elements until we find one that's not an UNDEF
5046   // After we find an UNDEF element, keep looping until we get to half the
5047   // length of the BV and see if all the non-undef nodes are the same.
5048   ConstantSDNode *BottomHalf = nullptr;
5049   for (int i = 0; i < NumElems / 2; ++i) {
5050     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5051       continue;
5052
5053     if (BottomHalf == nullptr)
5054       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5055     else if (Cond->getOperand(i).getNode() != BottomHalf)
5056       return SDValue();
5057   }
5058
5059   // Do the same for the second half of the BuildVector
5060   ConstantSDNode *TopHalf = nullptr;
5061   for (int i = NumElems / 2; i < NumElems; ++i) {
5062     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5063       continue;
5064
5065     if (TopHalf == nullptr)
5066       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5067     else if (Cond->getOperand(i).getNode() != TopHalf)
5068       return SDValue();
5069   }
5070
5071   assert(TopHalf && BottomHalf &&
5072          "One half of the selector was all UNDEFs and the other was all the "
5073          "same value. This should have been addressed before this function.");
5074   return DAG.getNode(
5075       ISD::CONCAT_VECTORS, dl, VT,
5076       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5077       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5078 }
5079
5080 SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
5081
5082   if (Level >= AfterLegalizeTypes)
5083     return SDValue();
5084
5085   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
5086   SDValue Mask = MSC->getMask();
5087   SDValue Data  = MSC->getValue();
5088   SDLoc DL(N);
5089
5090   // If the MSCATTER data type requires splitting and the mask is provided by a
5091   // SETCC, then split both nodes and its operands before legalization. This
5092   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5093   // and enables future optimizations (e.g. min/max pattern matching on X86).
5094   if (Mask.getOpcode() != ISD::SETCC)
5095     return SDValue();
5096
5097   // Check if any splitting is required.
5098   if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5099       TargetLowering::TypeSplitVector)
5100     return SDValue();
5101   SDValue MaskLo, MaskHi, Lo, Hi;
5102   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5103
5104   EVT LoVT, HiVT;
5105   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MSC->getValueType(0));
5106
5107   SDValue Chain = MSC->getChain();
5108
5109   EVT MemoryVT = MSC->getMemoryVT();
5110   unsigned Alignment = MSC->getOriginalAlignment();
5111
5112   EVT LoMemVT, HiMemVT;
5113   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5114
5115   SDValue DataLo, DataHi;
5116   std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5117
5118   SDValue BasePtr = MSC->getBasePtr();
5119   SDValue IndexLo, IndexHi;
5120   std::tie(IndexLo, IndexHi) = DAG.SplitVector(MSC->getIndex(), DL);
5121
5122   MachineMemOperand *MMO = DAG.getMachineFunction().
5123     getMachineMemOperand(MSC->getPointerInfo(), 
5124                           MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5125                           Alignment, MSC->getAAInfo(), MSC->getRanges());
5126
5127   SDValue OpsLo[] = { Chain, DataLo, MaskLo, BasePtr, IndexLo };
5128   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
5129                             DL, OpsLo, MMO);
5130
5131   SDValue OpsHi[] = {Chain, DataHi, MaskHi, BasePtr, IndexHi};
5132   Hi = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
5133                             DL, OpsHi, MMO);
5134
5135   AddToWorklist(Lo.getNode());
5136   AddToWorklist(Hi.getNode());
5137
5138   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5139 }
5140
5141 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5142
5143   if (Level >= AfterLegalizeTypes)
5144     return SDValue();
5145
5146   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5147   SDValue Mask = MST->getMask();
5148   SDValue Data  = MST->getValue();
5149   SDLoc DL(N);
5150
5151   // If the MSTORE data type requires splitting and the mask is provided by a
5152   // SETCC, then split both nodes and its operands before legalization. This
5153   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5154   // and enables future optimizations (e.g. min/max pattern matching on X86).
5155   if (Mask.getOpcode() == ISD::SETCC) {
5156
5157     // Check if any splitting is required.
5158     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5159         TargetLowering::TypeSplitVector)
5160       return SDValue();
5161
5162     SDValue MaskLo, MaskHi, Lo, Hi;
5163     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5164
5165     EVT LoVT, HiVT;
5166     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5167
5168     SDValue Chain = MST->getChain();
5169     SDValue Ptr   = MST->getBasePtr();
5170
5171     EVT MemoryVT = MST->getMemoryVT();
5172     unsigned Alignment = MST->getOriginalAlignment();
5173
5174     // if Alignment is equal to the vector size,
5175     // take the half of it for the second part
5176     unsigned SecondHalfAlignment =
5177       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5178          Alignment/2 : Alignment;
5179
5180     EVT LoMemVT, HiMemVT;
5181     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5182
5183     SDValue DataLo, DataHi;
5184     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5185
5186     MachineMemOperand *MMO = DAG.getMachineFunction().
5187       getMachineMemOperand(MST->getPointerInfo(),
5188                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5189                            Alignment, MST->getAAInfo(), MST->getRanges());
5190
5191     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5192                             MST->isTruncatingStore());
5193
5194     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5195     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5196                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5197
5198     MMO = DAG.getMachineFunction().
5199       getMachineMemOperand(MST->getPointerInfo(),
5200                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5201                            SecondHalfAlignment, MST->getAAInfo(),
5202                            MST->getRanges());
5203
5204     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5205                             MST->isTruncatingStore());
5206
5207     AddToWorklist(Lo.getNode());
5208     AddToWorklist(Hi.getNode());
5209
5210     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5211   }
5212   return SDValue();
5213 }
5214
5215 SDValue DAGCombiner::visitMGATHER(SDNode *N) {
5216
5217   if (Level >= AfterLegalizeTypes)
5218     return SDValue();
5219
5220   MaskedGatherSDNode *MGT = dyn_cast<MaskedGatherSDNode>(N);
5221   SDValue Mask = MGT->getMask();
5222   SDLoc DL(N);
5223
5224   // If the MGATHER result requires splitting and the mask is provided by a
5225   // SETCC, then split both nodes and its operands before legalization. This
5226   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5227   // and enables future optimizations (e.g. min/max pattern matching on X86).
5228
5229   if (Mask.getOpcode() != ISD::SETCC)
5230     return SDValue();
5231
5232   EVT VT = N->getValueType(0);
5233
5234   // Check if any splitting is required.
5235   if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5236       TargetLowering::TypeSplitVector)
5237     return SDValue();
5238
5239   SDValue MaskLo, MaskHi, Lo, Hi;
5240   std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5241
5242   SDValue Src0 = MGT->getValue();
5243   SDValue Src0Lo, Src0Hi;
5244   std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5245
5246   EVT LoVT, HiVT;
5247   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(VT);
5248
5249   SDValue Chain = MGT->getChain();
5250   EVT MemoryVT = MGT->getMemoryVT();
5251   unsigned Alignment = MGT->getOriginalAlignment();
5252
5253   EVT LoMemVT, HiMemVT;
5254   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5255
5256   SDValue BasePtr = MGT->getBasePtr();
5257   SDValue Index = MGT->getIndex();
5258   SDValue IndexLo, IndexHi;
5259   std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
5260
5261   MachineMemOperand *MMO = DAG.getMachineFunction().
5262     getMachineMemOperand(MGT->getPointerInfo(), 
5263                           MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5264                           Alignment, MGT->getAAInfo(), MGT->getRanges());
5265
5266   SDValue OpsLo[] = { Chain, Src0Lo, MaskLo, BasePtr, IndexLo };
5267   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, DL, OpsLo,
5268                             MMO);
5269
5270   SDValue OpsHi[] = {Chain, Src0Hi, MaskHi, BasePtr, IndexHi};
5271   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, DL, OpsHi,
5272                             MMO);
5273
5274   AddToWorklist(Lo.getNode());
5275   AddToWorklist(Hi.getNode());
5276
5277   // Build a factor node to remember that this load is independent of the
5278   // other one.
5279   Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5280                       Hi.getValue(1));
5281
5282   // Legalized the chain result - switch anything that used the old chain to
5283   // use the new one.
5284   DAG.ReplaceAllUsesOfValueWith(SDValue(MGT, 1), Chain);
5285
5286   SDValue GatherRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5287
5288   SDValue RetOps[] = { GatherRes, Chain };
5289   return DAG.getMergeValues(RetOps, DL);
5290 }
5291
5292 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5293
5294   if (Level >= AfterLegalizeTypes)
5295     return SDValue();
5296
5297   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5298   SDValue Mask = MLD->getMask();
5299   SDLoc DL(N);
5300
5301   // If the MLOAD result requires splitting and the mask is provided by a
5302   // SETCC, then split both nodes and its operands before legalization. This
5303   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5304   // and enables future optimizations (e.g. min/max pattern matching on X86).
5305
5306   if (Mask.getOpcode() == ISD::SETCC) {
5307     EVT VT = N->getValueType(0);
5308
5309     // Check if any splitting is required.
5310     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5311         TargetLowering::TypeSplitVector)
5312       return SDValue();
5313
5314     SDValue MaskLo, MaskHi, Lo, Hi;
5315     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5316
5317     SDValue Src0 = MLD->getSrc0();
5318     SDValue Src0Lo, Src0Hi;
5319     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5320
5321     EVT LoVT, HiVT;
5322     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5323
5324     SDValue Chain = MLD->getChain();
5325     SDValue Ptr   = MLD->getBasePtr();
5326     EVT MemoryVT = MLD->getMemoryVT();
5327     unsigned Alignment = MLD->getOriginalAlignment();
5328
5329     // if Alignment is equal to the vector size,
5330     // take the half of it for the second part
5331     unsigned SecondHalfAlignment =
5332       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5333          Alignment/2 : Alignment;
5334
5335     EVT LoMemVT, HiMemVT;
5336     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5337
5338     MachineMemOperand *MMO = DAG.getMachineFunction().
5339     getMachineMemOperand(MLD->getPointerInfo(),
5340                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5341                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5342
5343     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5344                            ISD::NON_EXTLOAD);
5345
5346     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5347     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5348                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5349
5350     MMO = DAG.getMachineFunction().
5351     getMachineMemOperand(MLD->getPointerInfo(),
5352                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5353                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5354
5355     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5356                            ISD::NON_EXTLOAD);
5357
5358     AddToWorklist(Lo.getNode());
5359     AddToWorklist(Hi.getNode());
5360
5361     // Build a factor node to remember that this load is independent of the
5362     // other one.
5363     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5364                         Hi.getValue(1));
5365
5366     // Legalized the chain result - switch anything that used the old chain to
5367     // use the new one.
5368     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5369
5370     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5371
5372     SDValue RetOps[] = { LoadRes, Chain };
5373     return DAG.getMergeValues(RetOps, DL);
5374   }
5375   return SDValue();
5376 }
5377
5378 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5379   SDValue N0 = N->getOperand(0);
5380   SDValue N1 = N->getOperand(1);
5381   SDValue N2 = N->getOperand(2);
5382   SDLoc DL(N);
5383
5384   // Canonicalize integer abs.
5385   // vselect (setg[te] X,  0),  X, -X ->
5386   // vselect (setgt    X, -1),  X, -X ->
5387   // vselect (setl[te] X,  0), -X,  X ->
5388   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5389   if (N0.getOpcode() == ISD::SETCC) {
5390     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5391     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5392     bool isAbs = false;
5393     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5394
5395     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5396          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5397         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5398       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5399     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5400              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5401       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5402
5403     if (isAbs) {
5404       EVT VT = LHS.getValueType();
5405       SDValue Shift = DAG.getNode(
5406           ISD::SRA, DL, VT, LHS,
5407           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5408       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5409       AddToWorklist(Shift.getNode());
5410       AddToWorklist(Add.getNode());
5411       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5412     }
5413   }
5414
5415   if (SimplifySelectOps(N, N1, N2))
5416     return SDValue(N, 0);  // Don't revisit N.
5417
5418   // If the VSELECT result requires splitting and the mask is provided by a
5419   // SETCC, then split both nodes and its operands before legalization. This
5420   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5421   // and enables future optimizations (e.g. min/max pattern matching on X86).
5422   if (N0.getOpcode() == ISD::SETCC) {
5423     EVT VT = N->getValueType(0);
5424
5425     // Check if any splitting is required.
5426     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5427         TargetLowering::TypeSplitVector)
5428       return SDValue();
5429
5430     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5431     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5432     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5433     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5434
5435     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5436     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5437
5438     // Add the new VSELECT nodes to the work list in case they need to be split
5439     // again.
5440     AddToWorklist(Lo.getNode());
5441     AddToWorklist(Hi.getNode());
5442
5443     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5444   }
5445
5446   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5447   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5448     return N1;
5449   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5450   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5451     return N2;
5452
5453   // The ConvertSelectToConcatVector function is assuming both the above
5454   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5455   // and addressed.
5456   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5457       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5458       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5459     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5460     if (CV.getNode())
5461       return CV;
5462   }
5463
5464   return SDValue();
5465 }
5466
5467 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5468   SDValue N0 = N->getOperand(0);
5469   SDValue N1 = N->getOperand(1);
5470   SDValue N2 = N->getOperand(2);
5471   SDValue N3 = N->getOperand(3);
5472   SDValue N4 = N->getOperand(4);
5473   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5474
5475   // fold select_cc lhs, rhs, x, x, cc -> x
5476   if (N2 == N3)
5477     return N2;
5478
5479   // Determine if the condition we're dealing with is constant
5480   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5481                               N0, N1, CC, SDLoc(N), false);
5482   if (SCC.getNode()) {
5483     AddToWorklist(SCC.getNode());
5484
5485     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5486       if (!SCCC->isNullValue())
5487         return N2;    // cond always true -> true val
5488       else
5489         return N3;    // cond always false -> false val
5490     } else if (SCC->getOpcode() == ISD::UNDEF) {
5491       // When the condition is UNDEF, just return the first operand. This is
5492       // coherent the DAG creation, no setcc node is created in this case
5493       return N2;
5494     } else if (SCC.getOpcode() == ISD::SETCC) {
5495       // Fold to a simpler select_cc
5496       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5497                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5498                          SCC.getOperand(2));
5499     }
5500   }
5501
5502   // If we can fold this based on the true/false value, do so.
5503   if (SimplifySelectOps(N, N2, N3))
5504     return SDValue(N, 0);  // Don't revisit N.
5505
5506   // fold select_cc into other things, such as min/max/abs
5507   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5508 }
5509
5510 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5511   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5512                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5513                        SDLoc(N));
5514 }
5515
5516 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5517 // dag node into a ConstantSDNode or a build_vector of constants.
5518 // This function is called by the DAGCombiner when visiting sext/zext/aext
5519 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5520 // Vector extends are not folded if operations are legal; this is to
5521 // avoid introducing illegal build_vector dag nodes.
5522 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5523                                          SelectionDAG &DAG, bool LegalTypes,
5524                                          bool LegalOperations) {
5525   unsigned Opcode = N->getOpcode();
5526   SDValue N0 = N->getOperand(0);
5527   EVT VT = N->getValueType(0);
5528
5529   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5530          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5531
5532   // fold (sext c1) -> c1
5533   // fold (zext c1) -> c1
5534   // fold (aext c1) -> c1
5535   if (isa<ConstantSDNode>(N0))
5536     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5537
5538   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5539   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5540   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5541   EVT SVT = VT.getScalarType();
5542   if (!(VT.isVector() &&
5543       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5544       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5545     return nullptr;
5546
5547   // We can fold this node into a build_vector.
5548   unsigned VTBits = SVT.getSizeInBits();
5549   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5550   unsigned ShAmt = VTBits - EVTBits;
5551   SmallVector<SDValue, 8> Elts;
5552   unsigned NumElts = N0->getNumOperands();
5553   SDLoc DL(N);
5554
5555   for (unsigned i=0; i != NumElts; ++i) {
5556     SDValue Op = N0->getOperand(i);
5557     if (Op->getOpcode() == ISD::UNDEF) {
5558       Elts.push_back(DAG.getUNDEF(SVT));
5559       continue;
5560     }
5561
5562     SDLoc DL(Op);
5563     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5564     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5565     if (Opcode == ISD::SIGN_EXTEND)
5566       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5567                                      DL, SVT));
5568     else
5569       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5570                                      DL, SVT));
5571   }
5572
5573   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5574 }
5575
5576 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5577 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5578 // transformation. Returns true if extension are possible and the above
5579 // mentioned transformation is profitable.
5580 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5581                                     unsigned ExtOpc,
5582                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5583                                     const TargetLowering &TLI) {
5584   bool HasCopyToRegUses = false;
5585   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5586   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5587                             UE = N0.getNode()->use_end();
5588        UI != UE; ++UI) {
5589     SDNode *User = *UI;
5590     if (User == N)
5591       continue;
5592     if (UI.getUse().getResNo() != N0.getResNo())
5593       continue;
5594     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5595     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5596       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5597       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5598         // Sign bits will be lost after a zext.
5599         return false;
5600       bool Add = false;
5601       for (unsigned i = 0; i != 2; ++i) {
5602         SDValue UseOp = User->getOperand(i);
5603         if (UseOp == N0)
5604           continue;
5605         if (!isa<ConstantSDNode>(UseOp))
5606           return false;
5607         Add = true;
5608       }
5609       if (Add)
5610         ExtendNodes.push_back(User);
5611       continue;
5612     }
5613     // If truncates aren't free and there are users we can't
5614     // extend, it isn't worthwhile.
5615     if (!isTruncFree)
5616       return false;
5617     // Remember if this value is live-out.
5618     if (User->getOpcode() == ISD::CopyToReg)
5619       HasCopyToRegUses = true;
5620   }
5621
5622   if (HasCopyToRegUses) {
5623     bool BothLiveOut = false;
5624     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5625          UI != UE; ++UI) {
5626       SDUse &Use = UI.getUse();
5627       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5628         BothLiveOut = true;
5629         break;
5630       }
5631     }
5632     if (BothLiveOut)
5633       // Both unextended and extended values are live out. There had better be
5634       // a good reason for the transformation.
5635       return ExtendNodes.size();
5636   }
5637   return true;
5638 }
5639
5640 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5641                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5642                                   ISD::NodeType ExtType) {
5643   // Extend SetCC uses if necessary.
5644   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5645     SDNode *SetCC = SetCCs[i];
5646     SmallVector<SDValue, 4> Ops;
5647
5648     for (unsigned j = 0; j != 2; ++j) {
5649       SDValue SOp = SetCC->getOperand(j);
5650       if (SOp == Trunc)
5651         Ops.push_back(ExtLoad);
5652       else
5653         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5654     }
5655
5656     Ops.push_back(SetCC->getOperand(2));
5657     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5658   }
5659 }
5660
5661 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5662 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5663   SDValue N0 = N->getOperand(0);
5664   EVT DstVT = N->getValueType(0);
5665   EVT SrcVT = N0.getValueType();
5666
5667   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5668           N->getOpcode() == ISD::ZERO_EXTEND) &&
5669          "Unexpected node type (not an extend)!");
5670
5671   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5672   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5673   //   (v8i32 (sext (v8i16 (load x))))
5674   // into:
5675   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5676   //                          (v4i32 (sextload (x + 16)))))
5677   // Where uses of the original load, i.e.:
5678   //   (v8i16 (load x))
5679   // are replaced with:
5680   //   (v8i16 (truncate
5681   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5682   //                            (v4i32 (sextload (x + 16)))))))
5683   //
5684   // This combine is only applicable to illegal, but splittable, vectors.
5685   // All legal types, and illegal non-vector types, are handled elsewhere.
5686   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5687   //
5688   if (N0->getOpcode() != ISD::LOAD)
5689     return SDValue();
5690
5691   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5692
5693   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5694       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5695       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5696     return SDValue();
5697
5698   SmallVector<SDNode *, 4> SetCCs;
5699   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5700     return SDValue();
5701
5702   ISD::LoadExtType ExtType =
5703       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5704
5705   // Try to split the vector types to get down to legal types.
5706   EVT SplitSrcVT = SrcVT;
5707   EVT SplitDstVT = DstVT;
5708   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5709          SplitSrcVT.getVectorNumElements() > 1) {
5710     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5711     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5712   }
5713
5714   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5715     return SDValue();
5716
5717   SDLoc DL(N);
5718   const unsigned NumSplits =
5719       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5720   const unsigned Stride = SplitSrcVT.getStoreSize();
5721   SmallVector<SDValue, 4> Loads;
5722   SmallVector<SDValue, 4> Chains;
5723
5724   SDValue BasePtr = LN0->getBasePtr();
5725   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5726     const unsigned Offset = Idx * Stride;
5727     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5728
5729     SDValue SplitLoad = DAG.getExtLoad(
5730         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5731         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5732         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5733         Align, LN0->getAAInfo());
5734
5735     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5736                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5737
5738     Loads.push_back(SplitLoad.getValue(0));
5739     Chains.push_back(SplitLoad.getValue(1));
5740   }
5741
5742   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5743   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5744
5745   CombineTo(N, NewValue);
5746
5747   // Replace uses of the original load (before extension)
5748   // with a truncate of the concatenated sextloaded vectors.
5749   SDValue Trunc =
5750       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5751   CombineTo(N0.getNode(), Trunc, NewChain);
5752   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5753                   (ISD::NodeType)N->getOpcode());
5754   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5755 }
5756
5757 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5758   SDValue N0 = N->getOperand(0);
5759   EVT VT = N->getValueType(0);
5760
5761   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5762                                               LegalOperations))
5763     return SDValue(Res, 0);
5764
5765   // fold (sext (sext x)) -> (sext x)
5766   // fold (sext (aext x)) -> (sext x)
5767   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5768     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5769                        N0.getOperand(0));
5770
5771   if (N0.getOpcode() == ISD::TRUNCATE) {
5772     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5773     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5774     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5775     if (NarrowLoad.getNode()) {
5776       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5777       if (NarrowLoad.getNode() != N0.getNode()) {
5778         CombineTo(N0.getNode(), NarrowLoad);
5779         // CombineTo deleted the truncate, if needed, but not what's under it.
5780         AddToWorklist(oye);
5781       }
5782       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5783     }
5784
5785     // See if the value being truncated is already sign extended.  If so, just
5786     // eliminate the trunc/sext pair.
5787     SDValue Op = N0.getOperand(0);
5788     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5789     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5790     unsigned DestBits = VT.getScalarType().getSizeInBits();
5791     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5792
5793     if (OpBits == DestBits) {
5794       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5795       // bits, it is already ready.
5796       if (NumSignBits > DestBits-MidBits)
5797         return Op;
5798     } else if (OpBits < DestBits) {
5799       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5800       // bits, just sext from i32.
5801       if (NumSignBits > OpBits-MidBits)
5802         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5803     } else {
5804       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5805       // bits, just truncate to i32.
5806       if (NumSignBits > OpBits-MidBits)
5807         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5808     }
5809
5810     // fold (sext (truncate x)) -> (sextinreg x).
5811     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5812                                                  N0.getValueType())) {
5813       if (OpBits < DestBits)
5814         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5815       else if (OpBits > DestBits)
5816         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5817       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5818                          DAG.getValueType(N0.getValueType()));
5819     }
5820   }
5821
5822   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5823   // Only generate vector extloads when 1) they're legal, and 2) they are
5824   // deemed desirable by the target.
5825   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5826       ((!LegalOperations && !VT.isVector() &&
5827         !cast<LoadSDNode>(N0)->isVolatile()) ||
5828        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5829     bool DoXform = true;
5830     SmallVector<SDNode*, 4> SetCCs;
5831     if (!N0.hasOneUse())
5832       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5833     if (VT.isVector())
5834       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5835     if (DoXform) {
5836       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5837       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5838                                        LN0->getChain(),
5839                                        LN0->getBasePtr(), N0.getValueType(),
5840                                        LN0->getMemOperand());
5841       CombineTo(N, ExtLoad);
5842       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5843                                   N0.getValueType(), ExtLoad);
5844       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5845       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5846                       ISD::SIGN_EXTEND);
5847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5848     }
5849   }
5850
5851   // fold (sext (load x)) to multiple smaller sextloads.
5852   // Only on illegal but splittable vectors.
5853   if (SDValue ExtLoad = CombineExtLoad(N))
5854     return ExtLoad;
5855
5856   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5857   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5858   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5859       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5860     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5861     EVT MemVT = LN0->getMemoryVT();
5862     if ((!LegalOperations && !LN0->isVolatile()) ||
5863         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5864       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5865                                        LN0->getChain(),
5866                                        LN0->getBasePtr(), MemVT,
5867                                        LN0->getMemOperand());
5868       CombineTo(N, ExtLoad);
5869       CombineTo(N0.getNode(),
5870                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5871                             N0.getValueType(), ExtLoad),
5872                 ExtLoad.getValue(1));
5873       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5874     }
5875   }
5876
5877   // fold (sext (and/or/xor (load x), cst)) ->
5878   //      (and/or/xor (sextload x), (sext cst))
5879   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5880        N0.getOpcode() == ISD::XOR) &&
5881       isa<LoadSDNode>(N0.getOperand(0)) &&
5882       N0.getOperand(1).getOpcode() == ISD::Constant &&
5883       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5884       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5885     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5886     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5887       bool DoXform = true;
5888       SmallVector<SDNode*, 4> SetCCs;
5889       if (!N0.hasOneUse())
5890         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5891                                           SetCCs, TLI);
5892       if (DoXform) {
5893         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5894                                          LN0->getChain(), LN0->getBasePtr(),
5895                                          LN0->getMemoryVT(),
5896                                          LN0->getMemOperand());
5897         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5898         Mask = Mask.sext(VT.getSizeInBits());
5899         SDLoc DL(N);
5900         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5901                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5902         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5903                                     SDLoc(N0.getOperand(0)),
5904                                     N0.getOperand(0).getValueType(), ExtLoad);
5905         CombineTo(N, And);
5906         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5907         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5908                         ISD::SIGN_EXTEND);
5909         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5910       }
5911     }
5912   }
5913
5914   if (N0.getOpcode() == ISD::SETCC) {
5915     EVT N0VT = N0.getOperand(0).getValueType();
5916     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5917     // Only do this before legalize for now.
5918     if (VT.isVector() && !LegalOperations &&
5919         TLI.getBooleanContents(N0VT) ==
5920             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5921       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5922       // of the same size as the compared operands. Only optimize sext(setcc())
5923       // if this is the case.
5924       EVT SVT = getSetCCResultType(N0VT);
5925
5926       // We know that the # elements of the results is the same as the
5927       // # elements of the compare (and the # elements of the compare result
5928       // for that matter).  Check to see that they are the same size.  If so,
5929       // we know that the element size of the sext'd result matches the
5930       // element size of the compare operands.
5931       if (VT.getSizeInBits() == SVT.getSizeInBits())
5932         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5933                              N0.getOperand(1),
5934                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5935
5936       // If the desired elements are smaller or larger than the source
5937       // elements we can use a matching integer vector type and then
5938       // truncate/sign extend
5939       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5940       if (SVT == MatchingVectorType) {
5941         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5942                                N0.getOperand(0), N0.getOperand(1),
5943                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5944         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5945       }
5946     }
5947
5948     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5949     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5950     SDLoc DL(N);
5951     SDValue NegOne =
5952       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5953     SDValue SCC =
5954       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5955                        NegOne, DAG.getConstant(0, DL, VT),
5956                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5957     if (SCC.getNode()) return SCC;
5958
5959     if (!VT.isVector()) {
5960       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5961       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5962         SDLoc DL(N);
5963         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5964         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5965                                      N0.getOperand(0), N0.getOperand(1), CC);
5966         return DAG.getSelect(DL, VT, SetCC,
5967                              NegOne, DAG.getConstant(0, DL, VT));
5968       }
5969     }
5970   }
5971
5972   // fold (sext x) -> (zext x) if the sign bit is known zero.
5973   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5974       DAG.SignBitIsZero(N0))
5975     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5976
5977   return SDValue();
5978 }
5979
5980 // isTruncateOf - If N is a truncate of some other value, return true, record
5981 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5982 // This function computes KnownZero to avoid a duplicated call to
5983 // computeKnownBits in the caller.
5984 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5985                          APInt &KnownZero) {
5986   APInt KnownOne;
5987   if (N->getOpcode() == ISD::TRUNCATE) {
5988     Op = N->getOperand(0);
5989     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5990     return true;
5991   }
5992
5993   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5994       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5995     return false;
5996
5997   SDValue Op0 = N->getOperand(0);
5998   SDValue Op1 = N->getOperand(1);
5999   assert(Op0.getValueType() == Op1.getValueType());
6000
6001   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
6002   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
6003   if (COp0 && COp0->isNullValue())
6004     Op = Op1;
6005   else if (COp1 && COp1->isNullValue())
6006     Op = Op0;
6007   else
6008     return false;
6009
6010   DAG.computeKnownBits(Op, KnownZero, KnownOne);
6011
6012   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
6013     return false;
6014
6015   return true;
6016 }
6017
6018 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
6019   SDValue N0 = N->getOperand(0);
6020   EVT VT = N->getValueType(0);
6021
6022   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6023                                               LegalOperations))
6024     return SDValue(Res, 0);
6025
6026   // fold (zext (zext x)) -> (zext x)
6027   // fold (zext (aext x)) -> (zext x)
6028   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
6029     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
6030                        N0.getOperand(0));
6031
6032   // fold (zext (truncate x)) -> (zext x) or
6033   //      (zext (truncate x)) -> (truncate x)
6034   // This is valid when the truncated bits of x are already zero.
6035   // FIXME: We should extend this to work for vectors too.
6036   SDValue Op;
6037   APInt KnownZero;
6038   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
6039     APInt TruncatedBits =
6040       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
6041       APInt(Op.getValueSizeInBits(), 0) :
6042       APInt::getBitsSet(Op.getValueSizeInBits(),
6043                         N0.getValueSizeInBits(),
6044                         std::min(Op.getValueSizeInBits(),
6045                                  VT.getSizeInBits()));
6046     if (TruncatedBits == (KnownZero & TruncatedBits)) {
6047       if (VT.bitsGT(Op.getValueType()))
6048         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
6049       if (VT.bitsLT(Op.getValueType()))
6050         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6051
6052       return Op;
6053     }
6054   }
6055
6056   // fold (zext (truncate (load x))) -> (zext (smaller load x))
6057   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
6058   if (N0.getOpcode() == ISD::TRUNCATE) {
6059     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6060     if (NarrowLoad.getNode()) {
6061       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6062       if (NarrowLoad.getNode() != N0.getNode()) {
6063         CombineTo(N0.getNode(), NarrowLoad);
6064         // CombineTo deleted the truncate, if needed, but not what's under it.
6065         AddToWorklist(oye);
6066       }
6067       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6068     }
6069   }
6070
6071   // fold (zext (truncate x)) -> (and x, mask)
6072   if (N0.getOpcode() == ISD::TRUNCATE &&
6073       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
6074
6075     // fold (zext (truncate (load x))) -> (zext (smaller load x))
6076     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
6077     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6078     if (NarrowLoad.getNode()) {
6079       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6080       if (NarrowLoad.getNode() != N0.getNode()) {
6081         CombineTo(N0.getNode(), NarrowLoad);
6082         // CombineTo deleted the truncate, if needed, but not what's under it.
6083         AddToWorklist(oye);
6084       }
6085       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6086     }
6087
6088     SDValue Op = N0.getOperand(0);
6089     if (Op.getValueType().bitsLT(VT)) {
6090       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
6091       AddToWorklist(Op.getNode());
6092     } else if (Op.getValueType().bitsGT(VT)) {
6093       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
6094       AddToWorklist(Op.getNode());
6095     }
6096     return DAG.getZeroExtendInReg(Op, SDLoc(N),
6097                                   N0.getValueType().getScalarType());
6098   }
6099
6100   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
6101   // if either of the casts is not free.
6102   if (N0.getOpcode() == ISD::AND &&
6103       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6104       N0.getOperand(1).getOpcode() == ISD::Constant &&
6105       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6106                            N0.getValueType()) ||
6107        !TLI.isZExtFree(N0.getValueType(), VT))) {
6108     SDValue X = N0.getOperand(0).getOperand(0);
6109     if (X.getValueType().bitsLT(VT)) {
6110       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
6111     } else if (X.getValueType().bitsGT(VT)) {
6112       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6113     }
6114     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6115     Mask = Mask.zext(VT.getSizeInBits());
6116     SDLoc DL(N);
6117     return DAG.getNode(ISD::AND, DL, VT,
6118                        X, DAG.getConstant(Mask, DL, VT));
6119   }
6120
6121   // fold (zext (load x)) -> (zext (truncate (zextload x)))
6122   // Only generate vector extloads when 1) they're legal, and 2) they are
6123   // deemed desirable by the target.
6124   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6125       ((!LegalOperations && !VT.isVector() &&
6126         !cast<LoadSDNode>(N0)->isVolatile()) ||
6127        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
6128     bool DoXform = true;
6129     SmallVector<SDNode*, 4> SetCCs;
6130     if (!N0.hasOneUse())
6131       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
6132     if (VT.isVector())
6133       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
6134     if (DoXform) {
6135       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6136       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6137                                        LN0->getChain(),
6138                                        LN0->getBasePtr(), N0.getValueType(),
6139                                        LN0->getMemOperand());
6140       CombineTo(N, ExtLoad);
6141       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6142                                   N0.getValueType(), ExtLoad);
6143       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6144
6145       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6146                       ISD::ZERO_EXTEND);
6147       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6148     }
6149   }
6150
6151   // fold (zext (load x)) to multiple smaller zextloads.
6152   // Only on illegal but splittable vectors.
6153   if (SDValue ExtLoad = CombineExtLoad(N))
6154     return ExtLoad;
6155
6156   // fold (zext (and/or/xor (load x), cst)) ->
6157   //      (and/or/xor (zextload x), (zext cst))
6158   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6159        N0.getOpcode() == ISD::XOR) &&
6160       isa<LoadSDNode>(N0.getOperand(0)) &&
6161       N0.getOperand(1).getOpcode() == ISD::Constant &&
6162       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6163       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6164     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6165     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6166       bool DoXform = true;
6167       SmallVector<SDNode*, 4> SetCCs;
6168       if (!N0.hasOneUse())
6169         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6170                                           SetCCs, TLI);
6171       if (DoXform) {
6172         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6173                                          LN0->getChain(), LN0->getBasePtr(),
6174                                          LN0->getMemoryVT(),
6175                                          LN0->getMemOperand());
6176         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6177         Mask = Mask.zext(VT.getSizeInBits());
6178         SDLoc DL(N);
6179         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6180                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6181         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6182                                     SDLoc(N0.getOperand(0)),
6183                                     N0.getOperand(0).getValueType(), ExtLoad);
6184         CombineTo(N, And);
6185         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6186         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6187                         ISD::ZERO_EXTEND);
6188         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6189       }
6190     }
6191   }
6192
6193   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6194   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6195   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6196       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6197     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6198     EVT MemVT = LN0->getMemoryVT();
6199     if ((!LegalOperations && !LN0->isVolatile()) ||
6200         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6201       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6202                                        LN0->getChain(),
6203                                        LN0->getBasePtr(), MemVT,
6204                                        LN0->getMemOperand());
6205       CombineTo(N, ExtLoad);
6206       CombineTo(N0.getNode(),
6207                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6208                             ExtLoad),
6209                 ExtLoad.getValue(1));
6210       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6211     }
6212   }
6213
6214   if (N0.getOpcode() == ISD::SETCC) {
6215     if (!LegalOperations && VT.isVector() &&
6216         N0.getValueType().getVectorElementType() == MVT::i1) {
6217       EVT N0VT = N0.getOperand(0).getValueType();
6218       if (getSetCCResultType(N0VT) == N0.getValueType())
6219         return SDValue();
6220
6221       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6222       // Only do this before legalize for now.
6223       EVT EltVT = VT.getVectorElementType();
6224       SDLoc DL(N);
6225       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6226                                     DAG.getConstant(1, DL, EltVT));
6227       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6228         // We know that the # elements of the results is the same as the
6229         // # elements of the compare (and the # elements of the compare result
6230         // for that matter).  Check to see that they are the same size.  If so,
6231         // we know that the element size of the sext'd result matches the
6232         // element size of the compare operands.
6233         return DAG.getNode(ISD::AND, DL, VT,
6234                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6235                                          N0.getOperand(1),
6236                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6237                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6238                                        OneOps));
6239
6240       // If the desired elements are smaller or larger than the source
6241       // elements we can use a matching integer vector type and then
6242       // truncate/sign extend
6243       EVT MatchingElementType =
6244         EVT::getIntegerVT(*DAG.getContext(),
6245                           N0VT.getScalarType().getSizeInBits());
6246       EVT MatchingVectorType =
6247         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6248                          N0VT.getVectorNumElements());
6249       SDValue VsetCC =
6250         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6251                       N0.getOperand(1),
6252                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6253       return DAG.getNode(ISD::AND, DL, VT,
6254                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6255                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6256     }
6257
6258     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6259     SDLoc DL(N);
6260     SDValue SCC =
6261       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6262                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6263                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6264     if (SCC.getNode()) return SCC;
6265   }
6266
6267   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6268   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6269       isa<ConstantSDNode>(N0.getOperand(1)) &&
6270       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6271       N0.hasOneUse()) {
6272     SDValue ShAmt = N0.getOperand(1);
6273     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6274     if (N0.getOpcode() == ISD::SHL) {
6275       SDValue InnerZExt = N0.getOperand(0);
6276       // If the original shl may be shifting out bits, do not perform this
6277       // transformation.
6278       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6279         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6280       if (ShAmtVal > KnownZeroBits)
6281         return SDValue();
6282     }
6283
6284     SDLoc DL(N);
6285
6286     // Ensure that the shift amount is wide enough for the shifted value.
6287     if (VT.getSizeInBits() >= 256)
6288       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6289
6290     return DAG.getNode(N0.getOpcode(), DL, VT,
6291                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6292                        ShAmt);
6293   }
6294
6295   return SDValue();
6296 }
6297
6298 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6299   SDValue N0 = N->getOperand(0);
6300   EVT VT = N->getValueType(0);
6301
6302   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6303                                               LegalOperations))
6304     return SDValue(Res, 0);
6305
6306   // fold (aext (aext x)) -> (aext x)
6307   // fold (aext (zext x)) -> (zext x)
6308   // fold (aext (sext x)) -> (sext x)
6309   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6310       N0.getOpcode() == ISD::ZERO_EXTEND ||
6311       N0.getOpcode() == ISD::SIGN_EXTEND)
6312     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6313
6314   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6315   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6316   if (N0.getOpcode() == ISD::TRUNCATE) {
6317     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6318     if (NarrowLoad.getNode()) {
6319       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6320       if (NarrowLoad.getNode() != N0.getNode()) {
6321         CombineTo(N0.getNode(), NarrowLoad);
6322         // CombineTo deleted the truncate, if needed, but not what's under it.
6323         AddToWorklist(oye);
6324       }
6325       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6326     }
6327   }
6328
6329   // fold (aext (truncate x))
6330   if (N0.getOpcode() == ISD::TRUNCATE) {
6331     SDValue TruncOp = N0.getOperand(0);
6332     if (TruncOp.getValueType() == VT)
6333       return TruncOp; // x iff x size == zext size.
6334     if (TruncOp.getValueType().bitsGT(VT))
6335       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6336     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6337   }
6338
6339   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6340   // if the trunc is not free.
6341   if (N0.getOpcode() == ISD::AND &&
6342       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6343       N0.getOperand(1).getOpcode() == ISD::Constant &&
6344       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6345                           N0.getValueType())) {
6346     SDValue X = N0.getOperand(0).getOperand(0);
6347     if (X.getValueType().bitsLT(VT)) {
6348       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6349     } else if (X.getValueType().bitsGT(VT)) {
6350       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6351     }
6352     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6353     Mask = Mask.zext(VT.getSizeInBits());
6354     SDLoc DL(N);
6355     return DAG.getNode(ISD::AND, DL, VT,
6356                        X, DAG.getConstant(Mask, DL, VT));
6357   }
6358
6359   // fold (aext (load x)) -> (aext (truncate (extload x)))
6360   // None of the supported targets knows how to perform load and any_ext
6361   // on vectors in one instruction.  We only perform this transformation on
6362   // scalars.
6363   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6364       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6365       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6366     bool DoXform = true;
6367     SmallVector<SDNode*, 4> SetCCs;
6368     if (!N0.hasOneUse())
6369       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6370     if (DoXform) {
6371       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6372       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6373                                        LN0->getChain(),
6374                                        LN0->getBasePtr(), N0.getValueType(),
6375                                        LN0->getMemOperand());
6376       CombineTo(N, ExtLoad);
6377       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6378                                   N0.getValueType(), ExtLoad);
6379       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6380       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6381                       ISD::ANY_EXTEND);
6382       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6383     }
6384   }
6385
6386   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6387   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6388   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6389   if (N0.getOpcode() == ISD::LOAD &&
6390       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6391       N0.hasOneUse()) {
6392     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6393     ISD::LoadExtType ExtType = LN0->getExtensionType();
6394     EVT MemVT = LN0->getMemoryVT();
6395     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6396       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6397                                        VT, LN0->getChain(), LN0->getBasePtr(),
6398                                        MemVT, LN0->getMemOperand());
6399       CombineTo(N, ExtLoad);
6400       CombineTo(N0.getNode(),
6401                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6402                             N0.getValueType(), ExtLoad),
6403                 ExtLoad.getValue(1));
6404       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6405     }
6406   }
6407
6408   if (N0.getOpcode() == ISD::SETCC) {
6409     // For vectors:
6410     // aext(setcc) -> vsetcc
6411     // aext(setcc) -> truncate(vsetcc)
6412     // aext(setcc) -> aext(vsetcc)
6413     // Only do this before legalize for now.
6414     if (VT.isVector() && !LegalOperations) {
6415       EVT N0VT = N0.getOperand(0).getValueType();
6416         // We know that the # elements of the results is the same as the
6417         // # elements of the compare (and the # elements of the compare result
6418         // for that matter).  Check to see that they are the same size.  If so,
6419         // we know that the element size of the sext'd result matches the
6420         // element size of the compare operands.
6421       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6422         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6423                              N0.getOperand(1),
6424                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6425       // If the desired elements are smaller or larger than the source
6426       // elements we can use a matching integer vector type and then
6427       // truncate/any extend
6428       else {
6429         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6430         SDValue VsetCC =
6431           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6432                         N0.getOperand(1),
6433                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6434         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6435       }
6436     }
6437
6438     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6439     SDLoc DL(N);
6440     SDValue SCC =
6441       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6442                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6443                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6444     if (SCC.getNode())
6445       return SCC;
6446   }
6447
6448   return SDValue();
6449 }
6450
6451 /// See if the specified operand can be simplified with the knowledge that only
6452 /// the bits specified by Mask are used.  If so, return the simpler operand,
6453 /// otherwise return a null SDValue.
6454 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6455   switch (V.getOpcode()) {
6456   default: break;
6457   case ISD::Constant: {
6458     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6459     assert(CV && "Const value should be ConstSDNode.");
6460     const APInt &CVal = CV->getAPIntValue();
6461     APInt NewVal = CVal & Mask;
6462     if (NewVal != CVal)
6463       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6464     break;
6465   }
6466   case ISD::OR:
6467   case ISD::XOR:
6468     // If the LHS or RHS don't contribute bits to the or, drop them.
6469     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6470       return V.getOperand(1);
6471     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6472       return V.getOperand(0);
6473     break;
6474   case ISD::SRL:
6475     // Only look at single-use SRLs.
6476     if (!V.getNode()->hasOneUse())
6477       break;
6478     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6479       // See if we can recursively simplify the LHS.
6480       unsigned Amt = RHSC->getZExtValue();
6481
6482       // Watch out for shift count overflow though.
6483       if (Amt >= Mask.getBitWidth()) break;
6484       APInt NewMask = Mask << Amt;
6485       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6486       if (SimplifyLHS.getNode())
6487         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6488                            SimplifyLHS, V.getOperand(1));
6489     }
6490   }
6491   return SDValue();
6492 }
6493
6494 /// If the result of a wider load is shifted to right of N  bits and then
6495 /// truncated to a narrower type and where N is a multiple of number of bits of
6496 /// the narrower type, transform it to a narrower load from address + N / num of
6497 /// bits of new type. If the result is to be extended, also fold the extension
6498 /// to form a extending load.
6499 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6500   unsigned Opc = N->getOpcode();
6501
6502   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6503   SDValue N0 = N->getOperand(0);
6504   EVT VT = N->getValueType(0);
6505   EVT ExtVT = VT;
6506
6507   // This transformation isn't valid for vector loads.
6508   if (VT.isVector())
6509     return SDValue();
6510
6511   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6512   // extended to VT.
6513   if (Opc == ISD::SIGN_EXTEND_INREG) {
6514     ExtType = ISD::SEXTLOAD;
6515     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6516   } else if (Opc == ISD::SRL) {
6517     // Another special-case: SRL is basically zero-extending a narrower value.
6518     ExtType = ISD::ZEXTLOAD;
6519     N0 = SDValue(N, 0);
6520     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6521     if (!N01) return SDValue();
6522     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6523                               VT.getSizeInBits() - N01->getZExtValue());
6524   }
6525   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6526     return SDValue();
6527
6528   unsigned EVTBits = ExtVT.getSizeInBits();
6529
6530   // Do not generate loads of non-round integer types since these can
6531   // be expensive (and would be wrong if the type is not byte sized).
6532   if (!ExtVT.isRound())
6533     return SDValue();
6534
6535   unsigned ShAmt = 0;
6536   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6537     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6538       ShAmt = N01->getZExtValue();
6539       // Is the shift amount a multiple of size of VT?
6540       if ((ShAmt & (EVTBits-1)) == 0) {
6541         N0 = N0.getOperand(0);
6542         // Is the load width a multiple of size of VT?
6543         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6544           return SDValue();
6545       }
6546
6547       // At this point, we must have a load or else we can't do the transform.
6548       if (!isa<LoadSDNode>(N0)) return SDValue();
6549
6550       // Because a SRL must be assumed to *need* to zero-extend the high bits
6551       // (as opposed to anyext the high bits), we can't combine the zextload
6552       // lowering of SRL and an sextload.
6553       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6554         return SDValue();
6555
6556       // If the shift amount is larger than the input type then we're not
6557       // accessing any of the loaded bytes.  If the load was a zextload/extload
6558       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6559       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6560         return SDValue();
6561     }
6562   }
6563
6564   // If the load is shifted left (and the result isn't shifted back right),
6565   // we can fold the truncate through the shift.
6566   unsigned ShLeftAmt = 0;
6567   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6568       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6569     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6570       ShLeftAmt = N01->getZExtValue();
6571       N0 = N0.getOperand(0);
6572     }
6573   }
6574
6575   // If we haven't found a load, we can't narrow it.  Don't transform one with
6576   // multiple uses, this would require adding a new load.
6577   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6578     return SDValue();
6579
6580   // Don't change the width of a volatile load.
6581   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6582   if (LN0->isVolatile())
6583     return SDValue();
6584
6585   // Verify that we are actually reducing a load width here.
6586   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6587     return SDValue();
6588
6589   // For the transform to be legal, the load must produce only two values
6590   // (the value loaded and the chain).  Don't transform a pre-increment
6591   // load, for example, which produces an extra value.  Otherwise the
6592   // transformation is not equivalent, and the downstream logic to replace
6593   // uses gets things wrong.
6594   if (LN0->getNumValues() > 2)
6595     return SDValue();
6596
6597   // If the load that we're shrinking is an extload and we're not just
6598   // discarding the extension we can't simply shrink the load. Bail.
6599   // TODO: It would be possible to merge the extensions in some cases.
6600   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6601       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6602     return SDValue();
6603
6604   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6605     return SDValue();
6606
6607   EVT PtrType = N0.getOperand(1).getValueType();
6608
6609   if (PtrType == MVT::Untyped || PtrType.isExtended())
6610     // It's not possible to generate a constant of extended or untyped type.
6611     return SDValue();
6612
6613   // For big endian targets, we need to adjust the offset to the pointer to
6614   // load the correct bytes.
6615   if (TLI.isBigEndian()) {
6616     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6617     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6618     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6619   }
6620
6621   uint64_t PtrOff = ShAmt / 8;
6622   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6623   SDLoc DL(LN0);
6624   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6625                                PtrType, LN0->getBasePtr(),
6626                                DAG.getConstant(PtrOff, DL, PtrType));
6627   AddToWorklist(NewPtr.getNode());
6628
6629   SDValue Load;
6630   if (ExtType == ISD::NON_EXTLOAD)
6631     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6632                         LN0->getPointerInfo().getWithOffset(PtrOff),
6633                         LN0->isVolatile(), LN0->isNonTemporal(),
6634                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6635   else
6636     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6637                           LN0->getPointerInfo().getWithOffset(PtrOff),
6638                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6639                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6640
6641   // Replace the old load's chain with the new load's chain.
6642   WorklistRemover DeadNodes(*this);
6643   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6644
6645   // Shift the result left, if we've swallowed a left shift.
6646   SDValue Result = Load;
6647   if (ShLeftAmt != 0) {
6648     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6649     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6650       ShImmTy = VT;
6651     // If the shift amount is as large as the result size (but, presumably,
6652     // no larger than the source) then the useful bits of the result are
6653     // zero; we can't simply return the shortened shift, because the result
6654     // of that operation is undefined.
6655     SDLoc DL(N0);
6656     if (ShLeftAmt >= VT.getSizeInBits())
6657       Result = DAG.getConstant(0, DL, VT);
6658     else
6659       Result = DAG.getNode(ISD::SHL, DL, VT,
6660                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6661   }
6662
6663   // Return the new loaded value.
6664   return Result;
6665 }
6666
6667 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6668   SDValue N0 = N->getOperand(0);
6669   SDValue N1 = N->getOperand(1);
6670   EVT VT = N->getValueType(0);
6671   EVT EVT = cast<VTSDNode>(N1)->getVT();
6672   unsigned VTBits = VT.getScalarType().getSizeInBits();
6673   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6674
6675   // fold (sext_in_reg c1) -> c1
6676   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6677     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6678
6679   // If the input is already sign extended, just drop the extension.
6680   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6681     return N0;
6682
6683   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6684   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6685       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6686     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6687                        N0.getOperand(0), N1);
6688
6689   // fold (sext_in_reg (sext x)) -> (sext x)
6690   // fold (sext_in_reg (aext x)) -> (sext x)
6691   // if x is small enough.
6692   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6693     SDValue N00 = N0.getOperand(0);
6694     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6695         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6696       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6697   }
6698
6699   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6700   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6701     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6702
6703   // fold operands of sext_in_reg based on knowledge that the top bits are not
6704   // demanded.
6705   if (SimplifyDemandedBits(SDValue(N, 0)))
6706     return SDValue(N, 0);
6707
6708   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6709   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6710   SDValue NarrowLoad = ReduceLoadWidth(N);
6711   if (NarrowLoad.getNode())
6712     return NarrowLoad;
6713
6714   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6715   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6716   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6717   if (N0.getOpcode() == ISD::SRL) {
6718     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6719       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6720         // We can turn this into an SRA iff the input to the SRL is already sign
6721         // extended enough.
6722         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6723         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6724           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6725                              N0.getOperand(0), N0.getOperand(1));
6726       }
6727   }
6728
6729   // fold (sext_inreg (extload x)) -> (sextload x)
6730   if (ISD::isEXTLoad(N0.getNode()) &&
6731       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6732       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6733       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6734        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6735     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6736     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6737                                      LN0->getChain(),
6738                                      LN0->getBasePtr(), EVT,
6739                                      LN0->getMemOperand());
6740     CombineTo(N, ExtLoad);
6741     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6742     AddToWorklist(ExtLoad.getNode());
6743     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6744   }
6745   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6746   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6747       N0.hasOneUse() &&
6748       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6749       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6750        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6751     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6752     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6753                                      LN0->getChain(),
6754                                      LN0->getBasePtr(), EVT,
6755                                      LN0->getMemOperand());
6756     CombineTo(N, ExtLoad);
6757     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6758     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6759   }
6760
6761   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6762   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6763     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6764                                        N0.getOperand(1), false);
6765     if (BSwap.getNode())
6766       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6767                          BSwap, N1);
6768   }
6769
6770   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6771   // into a build_vector.
6772   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6773     SmallVector<SDValue, 8> Elts;
6774     unsigned NumElts = N0->getNumOperands();
6775     unsigned ShAmt = VTBits - EVTBits;
6776
6777     for (unsigned i = 0; i != NumElts; ++i) {
6778       SDValue Op = N0->getOperand(i);
6779       if (Op->getOpcode() == ISD::UNDEF) {
6780         Elts.push_back(Op);
6781         continue;
6782       }
6783
6784       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6785       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6786       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6787                                      SDLoc(Op), Op.getValueType()));
6788     }
6789
6790     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6791   }
6792
6793   return SDValue();
6794 }
6795
6796 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6797   SDValue N0 = N->getOperand(0);
6798   EVT VT = N->getValueType(0);
6799   bool isLE = TLI.isLittleEndian();
6800
6801   // noop truncate
6802   if (N0.getValueType() == N->getValueType(0))
6803     return N0;
6804   // fold (truncate c1) -> c1
6805   if (isConstantIntBuildVectorOrConstantInt(N0))
6806     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6807   // fold (truncate (truncate x)) -> (truncate x)
6808   if (N0.getOpcode() == ISD::TRUNCATE)
6809     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6810   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6811   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6812       N0.getOpcode() == ISD::SIGN_EXTEND ||
6813       N0.getOpcode() == ISD::ANY_EXTEND) {
6814     if (N0.getOperand(0).getValueType().bitsLT(VT))
6815       // if the source is smaller than the dest, we still need an extend
6816       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6817                          N0.getOperand(0));
6818     if (N0.getOperand(0).getValueType().bitsGT(VT))
6819       // if the source is larger than the dest, than we just need the truncate
6820       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6821     // if the source and dest are the same type, we can drop both the extend
6822     // and the truncate.
6823     return N0.getOperand(0);
6824   }
6825
6826   // Fold extract-and-trunc into a narrow extract. For example:
6827   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6828   //   i32 y = TRUNCATE(i64 x)
6829   //        -- becomes --
6830   //   v16i8 b = BITCAST (v2i64 val)
6831   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6832   //
6833   // Note: We only run this optimization after type legalization (which often
6834   // creates this pattern) and before operation legalization after which
6835   // we need to be more careful about the vector instructions that we generate.
6836   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6837       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6838
6839     EVT VecTy = N0.getOperand(0).getValueType();
6840     EVT ExTy = N0.getValueType();
6841     EVT TrTy = N->getValueType(0);
6842
6843     unsigned NumElem = VecTy.getVectorNumElements();
6844     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6845
6846     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6847     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6848
6849     SDValue EltNo = N0->getOperand(1);
6850     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6851       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6852       EVT IndexTy = TLI.getVectorIdxTy();
6853       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6854
6855       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6856                               NVT, N0.getOperand(0));
6857
6858       SDLoc DL(N);
6859       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6860                          DL, TrTy, V,
6861                          DAG.getConstant(Index, DL, IndexTy));
6862     }
6863   }
6864
6865   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6866   if (N0.getOpcode() == ISD::SELECT) {
6867     EVT SrcVT = N0.getValueType();
6868     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6869         TLI.isTruncateFree(SrcVT, VT)) {
6870       SDLoc SL(N0);
6871       SDValue Cond = N0.getOperand(0);
6872       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6873       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6874       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6875     }
6876   }
6877
6878   // Fold a series of buildvector, bitcast, and truncate if possible.
6879   // For example fold
6880   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6881   //   (2xi32 (buildvector x, y)).
6882   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6883       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6884       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6885       N0.getOperand(0).hasOneUse()) {
6886
6887     SDValue BuildVect = N0.getOperand(0);
6888     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6889     EVT TruncVecEltTy = VT.getVectorElementType();
6890
6891     // Check that the element types match.
6892     if (BuildVectEltTy == TruncVecEltTy) {
6893       // Now we only need to compute the offset of the truncated elements.
6894       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6895       unsigned TruncVecNumElts = VT.getVectorNumElements();
6896       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6897
6898       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6899              "Invalid number of elements");
6900
6901       SmallVector<SDValue, 8> Opnds;
6902       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6903         Opnds.push_back(BuildVect.getOperand(i));
6904
6905       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6906     }
6907   }
6908
6909   // See if we can simplify the input to this truncate through knowledge that
6910   // only the low bits are being used.
6911   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6912   // Currently we only perform this optimization on scalars because vectors
6913   // may have different active low bits.
6914   if (!VT.isVector()) {
6915     SDValue Shorter =
6916       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6917                                                VT.getSizeInBits()));
6918     if (Shorter.getNode())
6919       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6920   }
6921   // fold (truncate (load x)) -> (smaller load x)
6922   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6923   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6924     SDValue Reduced = ReduceLoadWidth(N);
6925     if (Reduced.getNode())
6926       return Reduced;
6927     // Handle the case where the load remains an extending load even
6928     // after truncation.
6929     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6930       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6931       if (!LN0->isVolatile() &&
6932           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6933         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6934                                          VT, LN0->getChain(), LN0->getBasePtr(),
6935                                          LN0->getMemoryVT(),
6936                                          LN0->getMemOperand());
6937         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6938         return NewLoad;
6939       }
6940     }
6941   }
6942   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6943   // where ... are all 'undef'.
6944   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6945     SmallVector<EVT, 8> VTs;
6946     SDValue V;
6947     unsigned Idx = 0;
6948     unsigned NumDefs = 0;
6949
6950     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6951       SDValue X = N0.getOperand(i);
6952       if (X.getOpcode() != ISD::UNDEF) {
6953         V = X;
6954         Idx = i;
6955         NumDefs++;
6956       }
6957       // Stop if more than one members are non-undef.
6958       if (NumDefs > 1)
6959         break;
6960       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6961                                      VT.getVectorElementType(),
6962                                      X.getValueType().getVectorNumElements()));
6963     }
6964
6965     if (NumDefs == 0)
6966       return DAG.getUNDEF(VT);
6967
6968     if (NumDefs == 1) {
6969       assert(V.getNode() && "The single defined operand is empty!");
6970       SmallVector<SDValue, 8> Opnds;
6971       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6972         if (i != Idx) {
6973           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6974           continue;
6975         }
6976         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6977         AddToWorklist(NV.getNode());
6978         Opnds.push_back(NV);
6979       }
6980       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6981     }
6982   }
6983
6984   // Simplify the operands using demanded-bits information.
6985   if (!VT.isVector() &&
6986       SimplifyDemandedBits(SDValue(N, 0)))
6987     return SDValue(N, 0);
6988
6989   return SDValue();
6990 }
6991
6992 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6993   SDValue Elt = N->getOperand(i);
6994   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6995     return Elt.getNode();
6996   return Elt.getOperand(Elt.getResNo()).getNode();
6997 }
6998
6999 /// build_pair (load, load) -> load
7000 /// if load locations are consecutive.
7001 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
7002   assert(N->getOpcode() == ISD::BUILD_PAIR);
7003
7004   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
7005   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
7006   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
7007       LD1->getAddressSpace() != LD2->getAddressSpace())
7008     return SDValue();
7009   EVT LD1VT = LD1->getValueType(0);
7010
7011   if (ISD::isNON_EXTLoad(LD2) &&
7012       LD2->hasOneUse() &&
7013       // If both are volatile this would reduce the number of volatile loads.
7014       // If one is volatile it might be ok, but play conservative and bail out.
7015       !LD1->isVolatile() &&
7016       !LD2->isVolatile() &&
7017       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
7018     unsigned Align = LD1->getAlignment();
7019     unsigned NewAlign = TLI.getDataLayout()->
7020       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7021
7022     if (NewAlign <= Align &&
7023         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
7024       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
7025                          LD1->getBasePtr(), LD1->getPointerInfo(),
7026                          false, false, false, Align);
7027   }
7028
7029   return SDValue();
7030 }
7031
7032 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
7033   SDValue N0 = N->getOperand(0);
7034   EVT VT = N->getValueType(0);
7035
7036   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
7037   // Only do this before legalize, since afterward the target may be depending
7038   // on the bitconvert.
7039   // First check to see if this is all constant.
7040   if (!LegalTypes &&
7041       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
7042       VT.isVector()) {
7043     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
7044
7045     EVT DestEltVT = N->getValueType(0).getVectorElementType();
7046     assert(!DestEltVT.isVector() &&
7047            "Element type of vector ValueType must not be vector!");
7048     if (isSimple)
7049       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
7050   }
7051
7052   // If the input is a constant, let getNode fold it.
7053   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
7054     // If we can't allow illegal operations, we need to check that this is just
7055     // a fp -> int or int -> conversion and that the resulting operation will
7056     // be legal.
7057     if (!LegalOperations ||
7058         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
7059          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
7060         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
7061          TLI.isOperationLegal(ISD::Constant, VT)))
7062       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
7063   }
7064
7065   // (conv (conv x, t1), t2) -> (conv x, t2)
7066   if (N0.getOpcode() == ISD::BITCAST)
7067     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
7068                        N0.getOperand(0));
7069
7070   // fold (conv (load x)) -> (load (conv*)x)
7071   // If the resultant load doesn't need a higher alignment than the original!
7072   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7073       // Do not change the width of a volatile load.
7074       !cast<LoadSDNode>(N0)->isVolatile() &&
7075       // Do not remove the cast if the types differ in endian layout.
7076       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
7077       TLI.hasBigEndianPartOrdering(VT) &&
7078       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
7079       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
7080     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7081     unsigned Align = TLI.getDataLayout()->
7082       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
7083     unsigned OrigAlign = LN0->getAlignment();
7084
7085     if (Align <= OrigAlign) {
7086       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
7087                                  LN0->getBasePtr(), LN0->getPointerInfo(),
7088                                  LN0->isVolatile(), LN0->isNonTemporal(),
7089                                  LN0->isInvariant(), OrigAlign,
7090                                  LN0->getAAInfo());
7091       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
7092       return Load;
7093     }
7094   }
7095
7096   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
7097   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
7098   // This often reduces constant pool loads.
7099   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
7100        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
7101       N0.getNode()->hasOneUse() && VT.isInteger() &&
7102       !VT.isVector() && !N0.getValueType().isVector()) {
7103     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
7104                                   N0.getOperand(0));
7105     AddToWorklist(NewConv.getNode());
7106
7107     SDLoc DL(N);
7108     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7109     if (N0.getOpcode() == ISD::FNEG)
7110       return DAG.getNode(ISD::XOR, DL, VT,
7111                          NewConv, DAG.getConstant(SignBit, DL, VT));
7112     assert(N0.getOpcode() == ISD::FABS);
7113     return DAG.getNode(ISD::AND, DL, VT,
7114                        NewConv, DAG.getConstant(~SignBit, DL, VT));
7115   }
7116
7117   // fold (bitconvert (fcopysign cst, x)) ->
7118   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
7119   // Note that we don't handle (copysign x, cst) because this can always be
7120   // folded to an fneg or fabs.
7121   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
7122       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
7123       VT.isInteger() && !VT.isVector()) {
7124     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
7125     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
7126     if (isTypeLegal(IntXVT)) {
7127       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7128                               IntXVT, N0.getOperand(1));
7129       AddToWorklist(X.getNode());
7130
7131       // If X has a different width than the result/lhs, sext it or truncate it.
7132       unsigned VTWidth = VT.getSizeInBits();
7133       if (OrigXWidth < VTWidth) {
7134         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
7135         AddToWorklist(X.getNode());
7136       } else if (OrigXWidth > VTWidth) {
7137         // To get the sign bit in the right place, we have to shift it right
7138         // before truncating.
7139         SDLoc DL(X);
7140         X = DAG.getNode(ISD::SRL, DL,
7141                         X.getValueType(), X,
7142                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7143                                         X.getValueType()));
7144         AddToWorklist(X.getNode());
7145         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7146         AddToWorklist(X.getNode());
7147       }
7148
7149       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7150       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7151                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7152       AddToWorklist(X.getNode());
7153
7154       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7155                                 VT, N0.getOperand(0));
7156       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7157                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7158       AddToWorklist(Cst.getNode());
7159
7160       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7161     }
7162   }
7163
7164   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7165   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7166     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7167     if (CombineLD.getNode())
7168       return CombineLD;
7169   }
7170
7171   // Remove double bitcasts from shuffles - this is often a legacy of
7172   // XformToShuffleWithZero being used to combine bitmaskings (of
7173   // float vectors bitcast to integer vectors) into shuffles.
7174   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7175   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7176       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7177       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7178       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7179     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7180
7181     // If operands are a bitcast, peek through if it casts the original VT.
7182     // If operands are a UNDEF or constant, just bitcast back to original VT.
7183     auto PeekThroughBitcast = [&](SDValue Op) {
7184       if (Op.getOpcode() == ISD::BITCAST &&
7185           Op.getOperand(0)->getValueType(0) == VT)
7186         return SDValue(Op.getOperand(0));
7187       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7188           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7189         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7190       return SDValue();
7191     };
7192
7193     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7194     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7195     if (!(SV0 && SV1))
7196       return SDValue();
7197
7198     int MaskScale =
7199         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7200     SmallVector<int, 8> NewMask;
7201     for (int M : SVN->getMask())
7202       for (int i = 0; i != MaskScale; ++i)
7203         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7204
7205     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7206     if (!LegalMask) {
7207       std::swap(SV0, SV1);
7208       ShuffleVectorSDNode::commuteMask(NewMask);
7209       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7210     }
7211
7212     if (LegalMask)
7213       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7214   }
7215
7216   return SDValue();
7217 }
7218
7219 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7220   EVT VT = N->getValueType(0);
7221   return CombineConsecutiveLoads(N, VT);
7222 }
7223
7224 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7225 /// operands. DstEltVT indicates the destination element value type.
7226 SDValue DAGCombiner::
7227 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7228   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7229
7230   // If this is already the right type, we're done.
7231   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7232
7233   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7234   unsigned DstBitSize = DstEltVT.getSizeInBits();
7235
7236   // If this is a conversion of N elements of one type to N elements of another
7237   // type, convert each element.  This handles FP<->INT cases.
7238   if (SrcBitSize == DstBitSize) {
7239     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7240                               BV->getValueType(0).getVectorNumElements());
7241
7242     // Due to the FP element handling below calling this routine recursively,
7243     // we can end up with a scalar-to-vector node here.
7244     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7245       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7246                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7247                                      DstEltVT, BV->getOperand(0)));
7248
7249     SmallVector<SDValue, 8> Ops;
7250     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7251       SDValue Op = BV->getOperand(i);
7252       // If the vector element type is not legal, the BUILD_VECTOR operands
7253       // are promoted and implicitly truncated.  Make that explicit here.
7254       if (Op.getValueType() != SrcEltVT)
7255         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7256       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7257                                 DstEltVT, Op));
7258       AddToWorklist(Ops.back().getNode());
7259     }
7260     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7261   }
7262
7263   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7264   // handle annoying details of growing/shrinking FP values, we convert them to
7265   // int first.
7266   if (SrcEltVT.isFloatingPoint()) {
7267     // Convert the input float vector to a int vector where the elements are the
7268     // same sizes.
7269     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7270     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7271     SrcEltVT = IntVT;
7272   }
7273
7274   // Now we know the input is an integer vector.  If the output is a FP type,
7275   // convert to integer first, then to FP of the right size.
7276   if (DstEltVT.isFloatingPoint()) {
7277     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7278     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7279
7280     // Next, convert to FP elements of the same size.
7281     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7282   }
7283
7284   SDLoc DL(BV);
7285
7286   // Okay, we know the src/dst types are both integers of differing types.
7287   // Handling growing first.
7288   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7289   if (SrcBitSize < DstBitSize) {
7290     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7291
7292     SmallVector<SDValue, 8> Ops;
7293     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7294          i += NumInputsPerOutput) {
7295       bool isLE = TLI.isLittleEndian();
7296       APInt NewBits = APInt(DstBitSize, 0);
7297       bool EltIsUndef = true;
7298       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7299         // Shift the previously computed bits over.
7300         NewBits <<= SrcBitSize;
7301         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7302         if (Op.getOpcode() == ISD::UNDEF) continue;
7303         EltIsUndef = false;
7304
7305         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7306                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7307       }
7308
7309       if (EltIsUndef)
7310         Ops.push_back(DAG.getUNDEF(DstEltVT));
7311       else
7312         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7313     }
7314
7315     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7316     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7317   }
7318
7319   // Finally, this must be the case where we are shrinking elements: each input
7320   // turns into multiple outputs.
7321   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7322   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7323                             NumOutputsPerInput*BV->getNumOperands());
7324   SmallVector<SDValue, 8> Ops;
7325
7326   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7327     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7328       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7329       continue;
7330     }
7331
7332     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7333                   getAPIntValue().zextOrTrunc(SrcBitSize);
7334
7335     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7336       APInt ThisVal = OpVal.trunc(DstBitSize);
7337       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7338       OpVal = OpVal.lshr(DstBitSize);
7339     }
7340
7341     // For big endian targets, swap the order of the pieces of each element.
7342     if (TLI.isBigEndian())
7343       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7344   }
7345
7346   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7347 }
7348
7349 /// Try to perform FMA combining on a given FADD node.
7350 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7351   SDValue N0 = N->getOperand(0);
7352   SDValue N1 = N->getOperand(1);
7353   EVT VT = N->getValueType(0);
7354   SDLoc SL(N);
7355
7356   const TargetOptions &Options = DAG.getTarget().Options;
7357   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7358                        Options.UnsafeFPMath);
7359
7360   // Floating-point multiply-add with intermediate rounding.
7361   bool HasFMAD = (LegalOperations &&
7362                   TLI.isOperationLegal(ISD::FMAD, VT));
7363
7364   // Floating-point multiply-add without intermediate rounding.
7365   bool HasFMA = ((!LegalOperations ||
7366                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7367                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7368                  UnsafeFPMath);
7369
7370   // No valid opcode, do not combine.
7371   if (!HasFMAD && !HasFMA)
7372     return SDValue();
7373
7374   // Always prefer FMAD to FMA for precision.
7375   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7376   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7377   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7378
7379   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7380   if (N0.getOpcode() == ISD::FMUL &&
7381       (Aggressive || N0->hasOneUse())) {
7382     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7383                        N0.getOperand(0), N0.getOperand(1), N1);
7384   }
7385
7386   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7387   // Note: Commutes FADD operands.
7388   if (N1.getOpcode() == ISD::FMUL &&
7389       (Aggressive || N1->hasOneUse())) {
7390     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7391                        N1.getOperand(0), N1.getOperand(1), N0);
7392   }
7393
7394   // Look through FP_EXTEND nodes to do more combining.
7395   if (UnsafeFPMath && LookThroughFPExt) {
7396     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7397     if (N0.getOpcode() == ISD::FP_EXTEND) {
7398       SDValue N00 = N0.getOperand(0);
7399       if (N00.getOpcode() == ISD::FMUL)
7400         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7401                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7402                                        N00.getOperand(0)),
7403                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7404                                        N00.getOperand(1)), N1);
7405     }
7406
7407     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7408     // Note: Commutes FADD operands.
7409     if (N1.getOpcode() == ISD::FP_EXTEND) {
7410       SDValue N10 = N1.getOperand(0);
7411       if (N10.getOpcode() == ISD::FMUL)
7412         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7413                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7414                                        N10.getOperand(0)),
7415                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7416                                        N10.getOperand(1)), N0);
7417     }
7418   }
7419
7420   // More folding opportunities when target permits.
7421   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7422     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7423     if (N0.getOpcode() == PreferredFusedOpcode &&
7424         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7425       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7426                          N0.getOperand(0), N0.getOperand(1),
7427                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7428                                      N0.getOperand(2).getOperand(0),
7429                                      N0.getOperand(2).getOperand(1),
7430                                      N1));
7431     }
7432
7433     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7434     if (N1->getOpcode() == PreferredFusedOpcode &&
7435         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7436       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7437                          N1.getOperand(0), N1.getOperand(1),
7438                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7439                                      N1.getOperand(2).getOperand(0),
7440                                      N1.getOperand(2).getOperand(1),
7441                                      N0));
7442     }
7443
7444     if (UnsafeFPMath && LookThroughFPExt) {
7445       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7446       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7447       auto FoldFAddFMAFPExtFMul = [&] (
7448           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7449         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7450                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7451                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7452                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7453                                        Z));
7454       };
7455       if (N0.getOpcode() == PreferredFusedOpcode) {
7456         SDValue N02 = N0.getOperand(2);
7457         if (N02.getOpcode() == ISD::FP_EXTEND) {
7458           SDValue N020 = N02.getOperand(0);
7459           if (N020.getOpcode() == ISD::FMUL)
7460             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7461                                         N020.getOperand(0), N020.getOperand(1),
7462                                         N1);
7463         }
7464       }
7465
7466       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7467       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7468       // FIXME: This turns two single-precision and one double-precision
7469       // operation into two double-precision operations, which might not be
7470       // interesting for all targets, especially GPUs.
7471       auto FoldFAddFPExtFMAFMul = [&] (
7472           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7473         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7474                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7475                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7476                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7477                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7478                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7479                                        Z));
7480       };
7481       if (N0.getOpcode() == ISD::FP_EXTEND) {
7482         SDValue N00 = N0.getOperand(0);
7483         if (N00.getOpcode() == PreferredFusedOpcode) {
7484           SDValue N002 = N00.getOperand(2);
7485           if (N002.getOpcode() == ISD::FMUL)
7486             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7487                                         N002.getOperand(0), N002.getOperand(1),
7488                                         N1);
7489         }
7490       }
7491
7492       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7493       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7494       if (N1.getOpcode() == PreferredFusedOpcode) {
7495         SDValue N12 = N1.getOperand(2);
7496         if (N12.getOpcode() == ISD::FP_EXTEND) {
7497           SDValue N120 = N12.getOperand(0);
7498           if (N120.getOpcode() == ISD::FMUL)
7499             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7500                                         N120.getOperand(0), N120.getOperand(1),
7501                                         N0);
7502         }
7503       }
7504
7505       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7506       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7507       // FIXME: This turns two single-precision and one double-precision
7508       // operation into two double-precision operations, which might not be
7509       // interesting for all targets, especially GPUs.
7510       if (N1.getOpcode() == ISD::FP_EXTEND) {
7511         SDValue N10 = N1.getOperand(0);
7512         if (N10.getOpcode() == PreferredFusedOpcode) {
7513           SDValue N102 = N10.getOperand(2);
7514           if (N102.getOpcode() == ISD::FMUL)
7515             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7516                                         N102.getOperand(0), N102.getOperand(1),
7517                                         N0);
7518         }
7519       }
7520     }
7521   }
7522
7523   return SDValue();
7524 }
7525
7526 /// Try to perform FMA combining on a given FSUB node.
7527 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7528   SDValue N0 = N->getOperand(0);
7529   SDValue N1 = N->getOperand(1);
7530   EVT VT = N->getValueType(0);
7531   SDLoc SL(N);
7532
7533   const TargetOptions &Options = DAG.getTarget().Options;
7534   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7535                        Options.UnsafeFPMath);
7536
7537   // Floating-point multiply-add with intermediate rounding.
7538   bool HasFMAD = (LegalOperations &&
7539                   TLI.isOperationLegal(ISD::FMAD, VT));
7540
7541   // Floating-point multiply-add without intermediate rounding.
7542   bool HasFMA = ((!LegalOperations ||
7543                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7544                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7545                  UnsafeFPMath);
7546
7547   // No valid opcode, do not combine.
7548   if (!HasFMAD && !HasFMA)
7549     return SDValue();
7550
7551   // Always prefer FMAD to FMA for precision.
7552   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7553   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7554   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7555
7556   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7557   if (N0.getOpcode() == ISD::FMUL &&
7558       (Aggressive || N0->hasOneUse())) {
7559     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                        N0.getOperand(0), N0.getOperand(1),
7561                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7562   }
7563
7564   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7565   // Note: Commutes FSUB operands.
7566   if (N1.getOpcode() == ISD::FMUL &&
7567       (Aggressive || N1->hasOneUse()))
7568     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7569                        DAG.getNode(ISD::FNEG, SL, VT,
7570                                    N1.getOperand(0)),
7571                        N1.getOperand(1), N0);
7572
7573   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7574   if (N0.getOpcode() == ISD::FNEG &&
7575       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7576       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7577     SDValue N00 = N0.getOperand(0).getOperand(0);
7578     SDValue N01 = N0.getOperand(0).getOperand(1);
7579     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7580                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7581                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7582   }
7583
7584   // Look through FP_EXTEND nodes to do more combining.
7585   if (UnsafeFPMath && LookThroughFPExt) {
7586     // fold (fsub (fpext (fmul x, y)), z)
7587     //   -> (fma (fpext x), (fpext y), (fneg z))
7588     if (N0.getOpcode() == ISD::FP_EXTEND) {
7589       SDValue N00 = N0.getOperand(0);
7590       if (N00.getOpcode() == ISD::FMUL)
7591         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7592                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7593                                        N00.getOperand(0)),
7594                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7595                                        N00.getOperand(1)),
7596                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7597     }
7598
7599     // fold (fsub x, (fpext (fmul y, z)))
7600     //   -> (fma (fneg (fpext y)), (fpext z), x)
7601     // Note: Commutes FSUB operands.
7602     if (N1.getOpcode() == ISD::FP_EXTEND) {
7603       SDValue N10 = N1.getOperand(0);
7604       if (N10.getOpcode() == ISD::FMUL)
7605         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7606                            DAG.getNode(ISD::FNEG, SL, VT,
7607                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7608                                                    N10.getOperand(0))),
7609                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7610                                        N10.getOperand(1)),
7611                            N0);
7612     }
7613
7614     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7615     //   -> (fneg (fma (fpext x), (fpext y), z))
7616     // Note: This could be removed with appropriate canonicalization of the
7617     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7618     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7619     // from implementing the canonicalization in visitFSUB.
7620     if (N0.getOpcode() == ISD::FP_EXTEND) {
7621       SDValue N00 = N0.getOperand(0);
7622       if (N00.getOpcode() == ISD::FNEG) {
7623         SDValue N000 = N00.getOperand(0);
7624         if (N000.getOpcode() == ISD::FMUL) {
7625           return DAG.getNode(ISD::FNEG, SL, VT,
7626                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7627                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7628                                                      N000.getOperand(0)),
7629                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7630                                                      N000.getOperand(1)),
7631                                          N1));
7632         }
7633       }
7634     }
7635
7636     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7637     //   -> (fneg (fma (fpext x)), (fpext y), z)
7638     // Note: This could be removed with appropriate canonicalization of the
7639     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7640     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7641     // from implementing the canonicalization in visitFSUB.
7642     if (N0.getOpcode() == ISD::FNEG) {
7643       SDValue N00 = N0.getOperand(0);
7644       if (N00.getOpcode() == ISD::FP_EXTEND) {
7645         SDValue N000 = N00.getOperand(0);
7646         if (N000.getOpcode() == ISD::FMUL) {
7647           return DAG.getNode(ISD::FNEG, SL, VT,
7648                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7649                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7650                                                      N000.getOperand(0)),
7651                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7652                                                      N000.getOperand(1)),
7653                                          N1));
7654         }
7655       }
7656     }
7657
7658   }
7659
7660   // More folding opportunities when target permits.
7661   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7662     // fold (fsub (fma x, y, (fmul u, v)), z)
7663     //   -> (fma x, y (fma u, v, (fneg z)))
7664     if (N0.getOpcode() == PreferredFusedOpcode &&
7665         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7666       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7667                          N0.getOperand(0), N0.getOperand(1),
7668                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7669                                      N0.getOperand(2).getOperand(0),
7670                                      N0.getOperand(2).getOperand(1),
7671                                      DAG.getNode(ISD::FNEG, SL, VT,
7672                                                  N1)));
7673     }
7674
7675     // fold (fsub x, (fma y, z, (fmul u, v)))
7676     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7677     if (N1.getOpcode() == PreferredFusedOpcode &&
7678         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7679       SDValue N20 = N1.getOperand(2).getOperand(0);
7680       SDValue N21 = N1.getOperand(2).getOperand(1);
7681       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7682                          DAG.getNode(ISD::FNEG, SL, VT,
7683                                      N1.getOperand(0)),
7684                          N1.getOperand(1),
7685                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7686                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7687
7688                                      N21, N0));
7689     }
7690
7691     if (UnsafeFPMath && LookThroughFPExt) {
7692       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7693       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7694       if (N0.getOpcode() == PreferredFusedOpcode) {
7695         SDValue N02 = N0.getOperand(2);
7696         if (N02.getOpcode() == ISD::FP_EXTEND) {
7697           SDValue N020 = N02.getOperand(0);
7698           if (N020.getOpcode() == ISD::FMUL)
7699             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7700                                N0.getOperand(0), N0.getOperand(1),
7701                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7702                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7703                                                        N020.getOperand(0)),
7704                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7705                                                        N020.getOperand(1)),
7706                                            DAG.getNode(ISD::FNEG, SL, VT,
7707                                                        N1)));
7708         }
7709       }
7710
7711       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7712       //   -> (fma (fpext x), (fpext y),
7713       //           (fma (fpext u), (fpext v), (fneg z)))
7714       // FIXME: This turns two single-precision and one double-precision
7715       // operation into two double-precision operations, which might not be
7716       // interesting for all targets, especially GPUs.
7717       if (N0.getOpcode() == ISD::FP_EXTEND) {
7718         SDValue N00 = N0.getOperand(0);
7719         if (N00.getOpcode() == PreferredFusedOpcode) {
7720           SDValue N002 = N00.getOperand(2);
7721           if (N002.getOpcode() == ISD::FMUL)
7722             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7723                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7724                                            N00.getOperand(0)),
7725                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7726                                            N00.getOperand(1)),
7727                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7728                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7729                                                        N002.getOperand(0)),
7730                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7731                                                        N002.getOperand(1)),
7732                                            DAG.getNode(ISD::FNEG, SL, VT,
7733                                                        N1)));
7734         }
7735       }
7736
7737       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7738       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7739       if (N1.getOpcode() == PreferredFusedOpcode &&
7740         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7741         SDValue N120 = N1.getOperand(2).getOperand(0);
7742         if (N120.getOpcode() == ISD::FMUL) {
7743           SDValue N1200 = N120.getOperand(0);
7744           SDValue N1201 = N120.getOperand(1);
7745           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7746                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7747                              N1.getOperand(1),
7748                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7749                                          DAG.getNode(ISD::FNEG, SL, VT,
7750                                              DAG.getNode(ISD::FP_EXTEND, SL,
7751                                                          VT, N1200)),
7752                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7753                                                      N1201),
7754                                          N0));
7755         }
7756       }
7757
7758       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7759       //   -> (fma (fneg (fpext y)), (fpext z),
7760       //           (fma (fneg (fpext u)), (fpext v), x))
7761       // FIXME: This turns two single-precision and one double-precision
7762       // operation into two double-precision operations, which might not be
7763       // interesting for all targets, especially GPUs.
7764       if (N1.getOpcode() == ISD::FP_EXTEND &&
7765         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7766         SDValue N100 = N1.getOperand(0).getOperand(0);
7767         SDValue N101 = N1.getOperand(0).getOperand(1);
7768         SDValue N102 = N1.getOperand(0).getOperand(2);
7769         if (N102.getOpcode() == ISD::FMUL) {
7770           SDValue N1020 = N102.getOperand(0);
7771           SDValue N1021 = N102.getOperand(1);
7772           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7773                              DAG.getNode(ISD::FNEG, SL, VT,
7774                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7775                                                      N100)),
7776                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7777                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7778                                          DAG.getNode(ISD::FNEG, SL, VT,
7779                                              DAG.getNode(ISD::FP_EXTEND, SL,
7780                                                          VT, N1020)),
7781                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7782                                                      N1021),
7783                                          N0));
7784         }
7785       }
7786     }
7787   }
7788
7789   return SDValue();
7790 }
7791
7792 SDValue DAGCombiner::visitFADD(SDNode *N) {
7793   SDValue N0 = N->getOperand(0);
7794   SDValue N1 = N->getOperand(1);
7795   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7796   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7797   EVT VT = N->getValueType(0);
7798   SDLoc DL(N);
7799   const TargetOptions &Options = DAG.getTarget().Options;
7800
7801   // fold vector ops
7802   if (VT.isVector())
7803     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7804       return FoldedVOp;
7805
7806   // fold (fadd c1, c2) -> c1 + c2
7807   if (N0CFP && N1CFP)
7808     return DAG.getNode(ISD::FADD, DL, VT, N0, N1);
7809
7810   // canonicalize constant to RHS
7811   if (N0CFP && !N1CFP)
7812     return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
7813
7814   // fold (fadd A, (fneg B)) -> (fsub A, B)
7815   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7816       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7817     return DAG.getNode(ISD::FSUB, DL, VT, N0,
7818                        GetNegatedExpression(N1, DAG, LegalOperations));
7819
7820   // fold (fadd (fneg A), B) -> (fsub B, A)
7821   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7822       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7823     return DAG.getNode(ISD::FSUB, DL, VT, N1,
7824                        GetNegatedExpression(N0, DAG, LegalOperations));
7825
7826   // If 'unsafe math' is enabled, fold lots of things.
7827   if (Options.UnsafeFPMath) {
7828     // No FP constant should be created after legalization as Instruction
7829     // Selection pass has a hard time dealing with FP constants.
7830     bool AllowNewConst = (Level < AfterLegalizeDAG);
7831
7832     // fold (fadd A, 0) -> A
7833     if (N1CFP && N1CFP->getValueAPF().isZero())
7834       return N0;
7835
7836     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7837     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7838         isa<ConstantFPSDNode>(N0.getOperand(1)))
7839       return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0),
7840                          DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1));
7841
7842     // If allowed, fold (fadd (fneg x), x) -> 0.0
7843     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7844       return DAG.getConstantFP(0.0, DL, VT);
7845
7846     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7847     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7848       return DAG.getConstantFP(0.0, DL, VT);
7849
7850     // We can fold chains of FADD's of the same value into multiplications.
7851     // This transform is not safe in general because we are reducing the number
7852     // of rounding steps.
7853     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7854       if (N0.getOpcode() == ISD::FMUL) {
7855         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7856         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7857
7858         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7859         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7860           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7861                                        DAG.getConstantFP(1.0, DL, VT));
7862           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7863         }
7864
7865         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7866         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7867             N1.getOperand(0) == N1.getOperand(1) &&
7868             N0.getOperand(0) == N1.getOperand(0)) {
7869           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP01, 0),
7870                                        DAG.getConstantFP(2.0, DL, VT));
7871           return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
7872         }
7873       }
7874
7875       if (N1.getOpcode() == ISD::FMUL) {
7876         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7877         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7878
7879         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7880         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7881           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7882                                        DAG.getConstantFP(1.0, DL, VT));
7883           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7884         }
7885
7886         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7887         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7888             N0.getOperand(0) == N0.getOperand(1) &&
7889             N1.getOperand(0) == N0.getOperand(0)) {
7890           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, SDValue(CFP11, 0),
7891                                        DAG.getConstantFP(2.0, DL, VT));
7892           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7893         }
7894       }
7895
7896       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7897         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7898         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7899         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7900             (N0.getOperand(0) == N1)) {
7901           return DAG.getNode(ISD::FMUL, DL, VT,
7902                              N1, DAG.getConstantFP(3.0, DL, VT));
7903         }
7904       }
7905
7906       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7907         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7908         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7909         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7910             N1.getOperand(0) == N0) {
7911           return DAG.getNode(ISD::FMUL, DL, VT,
7912                              N0, DAG.getConstantFP(3.0, DL, VT));
7913         }
7914       }
7915
7916       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7917       if (AllowNewConst &&
7918           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7919           N0.getOperand(0) == N0.getOperand(1) &&
7920           N1.getOperand(0) == N1.getOperand(1) &&
7921           N0.getOperand(0) == N1.getOperand(0)) {
7922         return DAG.getNode(ISD::FMUL, DL, VT,
7923                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7924       }
7925     }
7926   } // enable-unsafe-fp-math
7927
7928   // FADD -> FMA combines:
7929   SDValue Fused = visitFADDForFMACombine(N);
7930   if (Fused) {
7931     AddToWorklist(Fused.getNode());
7932     return Fused;
7933   }
7934
7935   return SDValue();
7936 }
7937
7938 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7939   SDValue N0 = N->getOperand(0);
7940   SDValue N1 = N->getOperand(1);
7941   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7942   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7943   EVT VT = N->getValueType(0);
7944   SDLoc dl(N);
7945   const TargetOptions &Options = DAG.getTarget().Options;
7946
7947   // fold vector ops
7948   if (VT.isVector())
7949     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7950       return FoldedVOp;
7951
7952   // fold (fsub c1, c2) -> c1-c2
7953   if (N0CFP && N1CFP)
7954     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7955
7956   // fold (fsub A, (fneg B)) -> (fadd A, B)
7957   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7958     return DAG.getNode(ISD::FADD, dl, VT, N0,
7959                        GetNegatedExpression(N1, DAG, LegalOperations));
7960
7961   // If 'unsafe math' is enabled, fold lots of things.
7962   if (Options.UnsafeFPMath) {
7963     // (fsub A, 0) -> A
7964     if (N1CFP && N1CFP->getValueAPF().isZero())
7965       return N0;
7966
7967     // (fsub 0, B) -> -B
7968     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7969       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7970         return GetNegatedExpression(N1, DAG, LegalOperations);
7971       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7972         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7973     }
7974
7975     // (fsub x, x) -> 0.0
7976     if (N0 == N1)
7977       return DAG.getConstantFP(0.0f, dl, VT);
7978
7979     // (fsub x, (fadd x, y)) -> (fneg y)
7980     // (fsub x, (fadd y, x)) -> (fneg y)
7981     if (N1.getOpcode() == ISD::FADD) {
7982       SDValue N10 = N1->getOperand(0);
7983       SDValue N11 = N1->getOperand(1);
7984
7985       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7986         return GetNegatedExpression(N11, DAG, LegalOperations);
7987
7988       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7989         return GetNegatedExpression(N10, DAG, LegalOperations);
7990     }
7991   }
7992
7993   // FSUB -> FMA combines:
7994   SDValue Fused = visitFSUBForFMACombine(N);
7995   if (Fused) {
7996     AddToWorklist(Fused.getNode());
7997     return Fused;
7998   }
7999
8000   return SDValue();
8001 }
8002
8003 SDValue DAGCombiner::visitFMUL(SDNode *N) {
8004   SDValue N0 = N->getOperand(0);
8005   SDValue N1 = N->getOperand(1);
8006   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
8007   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
8008   EVT VT = N->getValueType(0);
8009   SDLoc DL(N);
8010   const TargetOptions &Options = DAG.getTarget().Options;
8011
8012   // fold vector ops
8013   if (VT.isVector()) {
8014     // This just handles C1 * C2 for vectors. Other vector folds are below.
8015     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8016       return FoldedVOp;
8017   }
8018
8019   // fold (fmul c1, c2) -> c1*c2
8020   if (N0CFP && N1CFP)
8021     return DAG.getNode(ISD::FMUL, DL, VT, N0, N1);
8022
8023   // canonicalize constant to RHS
8024   if (isConstantFPBuildVectorOrConstantFP(N0) &&
8025      !isConstantFPBuildVectorOrConstantFP(N1))
8026     return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
8027
8028   // fold (fmul A, 1.0) -> A
8029   if (N1CFP && N1CFP->isExactlyValue(1.0))
8030     return N0;
8031
8032   if (Options.UnsafeFPMath) {
8033     // fold (fmul A, 0) -> 0
8034     if (N1CFP && N1CFP->getValueAPF().isZero())
8035       return N1;
8036
8037     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
8038     if (N0.getOpcode() == ISD::FMUL) {
8039       // Fold scalars or any vector constants (not just splats).
8040       // This fold is done in general by InstCombine, but extra fmul insts
8041       // may have been generated during lowering.
8042       SDValue N00 = N0.getOperand(0);
8043       SDValue N01 = N0.getOperand(1);
8044       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
8045       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
8046       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
8047       
8048       // Check 1: Make sure that the first operand of the inner multiply is NOT
8049       // a constant. Otherwise, we may induce infinite looping.
8050       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
8051         // Check 2: Make sure that the second operand of the inner multiply and
8052         // the second operand of the outer multiply are constants.
8053         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
8054             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
8055           SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
8056           return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
8057         }
8058       }
8059     }
8060
8061     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
8062     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
8063     // during an early run of DAGCombiner can prevent folding with fmuls
8064     // inserted during lowering.
8065     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
8066       const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
8067       SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
8068       return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
8069     }
8070   }
8071
8072   // fold (fmul X, 2.0) -> (fadd X, X)
8073   if (N1CFP && N1CFP->isExactlyValue(+2.0))
8074     return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
8075
8076   // fold (fmul X, -1.0) -> (fneg X)
8077   if (N1CFP && N1CFP->isExactlyValue(-1.0))
8078     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8079       return DAG.getNode(ISD::FNEG, DL, VT, N0);
8080
8081   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
8082   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8083     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8084       // Both can be negated for free, check to see if at least one is cheaper
8085       // negated.
8086       if (LHSNeg == 2 || RHSNeg == 2)
8087         return DAG.getNode(ISD::FMUL, DL, VT,
8088                            GetNegatedExpression(N0, DAG, LegalOperations),
8089                            GetNegatedExpression(N1, DAG, LegalOperations));
8090     }
8091   }
8092
8093   return SDValue();
8094 }
8095
8096 SDValue DAGCombiner::visitFMA(SDNode *N) {
8097   SDValue N0 = N->getOperand(0);
8098   SDValue N1 = N->getOperand(1);
8099   SDValue N2 = N->getOperand(2);
8100   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8101   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8102   EVT VT = N->getValueType(0);
8103   SDLoc dl(N);
8104   const TargetOptions &Options = DAG.getTarget().Options;
8105
8106   // Constant fold FMA.
8107   if (isa<ConstantFPSDNode>(N0) &&
8108       isa<ConstantFPSDNode>(N1) &&
8109       isa<ConstantFPSDNode>(N2)) {
8110     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8111   }
8112
8113   if (Options.UnsafeFPMath) {
8114     if (N0CFP && N0CFP->isZero())
8115       return N2;
8116     if (N1CFP && N1CFP->isZero())
8117       return N2;
8118   }
8119   if (N0CFP && N0CFP->isExactlyValue(1.0))
8120     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8121   if (N1CFP && N1CFP->isExactlyValue(1.0))
8122     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8123
8124   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8125   if (N0CFP && !N1CFP)
8126     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8127
8128   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8129   if (Options.UnsafeFPMath && N1CFP &&
8130       N2.getOpcode() == ISD::FMUL &&
8131       N0 == N2.getOperand(0) &&
8132       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8133     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8134                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8135   }
8136
8137
8138   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8139   if (Options.UnsafeFPMath &&
8140       N0.getOpcode() == ISD::FMUL && N1CFP &&
8141       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8142     return DAG.getNode(ISD::FMA, dl, VT,
8143                        N0.getOperand(0),
8144                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8145                        N2);
8146   }
8147
8148   // (fma x, 1, y) -> (fadd x, y)
8149   // (fma x, -1, y) -> (fadd (fneg x), y)
8150   if (N1CFP) {
8151     if (N1CFP->isExactlyValue(1.0))
8152       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8153
8154     if (N1CFP->isExactlyValue(-1.0) &&
8155         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8156       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8157       AddToWorklist(RHSNeg.getNode());
8158       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8159     }
8160   }
8161
8162   // (fma x, c, x) -> (fmul x, (c+1))
8163   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8164     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8165                        DAG.getNode(ISD::FADD, dl, VT,
8166                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8167
8168   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8169   if (Options.UnsafeFPMath && N1CFP &&
8170       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8171     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8172                        DAG.getNode(ISD::FADD, dl, VT,
8173                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8174
8175
8176   return SDValue();
8177 }
8178
8179 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8180   SDValue N0 = N->getOperand(0);
8181   SDValue N1 = N->getOperand(1);
8182   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8183   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8184   EVT VT = N->getValueType(0);
8185   SDLoc DL(N);
8186   const TargetOptions &Options = DAG.getTarget().Options;
8187
8188   // fold vector ops
8189   if (VT.isVector())
8190     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8191       return FoldedVOp;
8192
8193   // fold (fdiv c1, c2) -> c1/c2
8194   if (N0CFP && N1CFP)
8195     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8196
8197   if (Options.UnsafeFPMath) {
8198     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8199     if (N1CFP) {
8200       // Compute the reciprocal 1.0 / c2.
8201       APFloat N1APF = N1CFP->getValueAPF();
8202       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8203       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8204       // Only do the transform if the reciprocal is a legal fp immediate that
8205       // isn't too nasty (eg NaN, denormal, ...).
8206       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8207           (!LegalOperations ||
8208            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8209            // backend)... we should handle this gracefully after Legalize.
8210            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8211            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8212            TLI.isFPImmLegal(Recip, VT)))
8213         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8214                            DAG.getConstantFP(Recip, DL, VT));
8215     }
8216
8217     // If this FDIV is part of a reciprocal square root, it may be folded
8218     // into a target-specific square root estimate instruction.
8219     if (N1.getOpcode() == ISD::FSQRT) {
8220       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8221         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8222       }
8223     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8224                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8225       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8226         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8227         AddToWorklist(RV.getNode());
8228         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8229       }
8230     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8231                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8232       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8233         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8234         AddToWorklist(RV.getNode());
8235         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8236       }
8237     } else if (N1.getOpcode() == ISD::FMUL) {
8238       // Look through an FMUL. Even though this won't remove the FDIV directly,
8239       // it's still worthwhile to get rid of the FSQRT if possible.
8240       SDValue SqrtOp;
8241       SDValue OtherOp;
8242       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8243         SqrtOp = N1.getOperand(0);
8244         OtherOp = N1.getOperand(1);
8245       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8246         SqrtOp = N1.getOperand(1);
8247         OtherOp = N1.getOperand(0);
8248       }
8249       if (SqrtOp.getNode()) {
8250         // We found a FSQRT, so try to make this fold:
8251         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8252         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8253           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8254           AddToWorklist(RV.getNode());
8255           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8256         }
8257       }
8258     }
8259
8260     // Fold into a reciprocal estimate and multiply instead of a real divide.
8261     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8262       AddToWorklist(RV.getNode());
8263       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8264     }
8265   }
8266
8267   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8268   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8269     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8270       // Both can be negated for free, check to see if at least one is cheaper
8271       // negated.
8272       if (LHSNeg == 2 || RHSNeg == 2)
8273         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8274                            GetNegatedExpression(N0, DAG, LegalOperations),
8275                            GetNegatedExpression(N1, DAG, LegalOperations));
8276     }
8277   }
8278
8279   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8280   // reciprocal.
8281   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8282   // Notice that this is not always beneficial. One reason is different target
8283   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8284   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8285   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8286   if (Options.UnsafeFPMath) {
8287     // Skip if current node is a reciprocal.
8288     if (N0CFP && N0CFP->isExactlyValue(1.0))
8289       return SDValue();
8290
8291     SmallVector<SDNode *, 4> Users;
8292     // Find all FDIV users of the same divisor.
8293     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8294                               UE = N1.getNode()->use_end();
8295          UI != UE; ++UI) {
8296       SDNode *User = UI.getUse().getUser();
8297       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8298         Users.push_back(User);
8299     }
8300
8301     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8302       SDLoc DL(N);
8303       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8304       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8305
8306       // Dividend / Divisor -> Dividend * Reciprocal
8307       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8308         if ((*I)->getOperand(0) != FPOne) {
8309           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8310                                         (*I)->getOperand(0), Reciprocal);
8311           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8312         }
8313       }
8314       return SDValue();
8315     }
8316   }
8317
8318   return SDValue();
8319 }
8320
8321 SDValue DAGCombiner::visitFREM(SDNode *N) {
8322   SDValue N0 = N->getOperand(0);
8323   SDValue N1 = N->getOperand(1);
8324   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8325   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8326   EVT VT = N->getValueType(0);
8327
8328   // fold (frem c1, c2) -> fmod(c1,c2)
8329   if (N0CFP && N1CFP)
8330     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8331
8332   return SDValue();
8333 }
8334
8335 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8336   if (DAG.getTarget().Options.UnsafeFPMath &&
8337       !TLI.isFsqrtCheap()) {
8338     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8339     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8340       EVT VT = RV.getValueType();
8341       SDLoc DL(N);
8342       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8343       AddToWorklist(RV.getNode());
8344
8345       // Unfortunately, RV is now NaN if the input was exactly 0.
8346       // Select out this case and force the answer to 0.
8347       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8348       SDValue ZeroCmp =
8349         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8350                      N->getOperand(0), Zero, ISD::SETEQ);
8351       AddToWorklist(ZeroCmp.getNode());
8352       AddToWorklist(RV.getNode());
8353
8354       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8355                        DL, VT, ZeroCmp, Zero, RV);
8356       return RV;
8357     }
8358   }
8359   return SDValue();
8360 }
8361
8362 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8363   SDValue N0 = N->getOperand(0);
8364   SDValue N1 = N->getOperand(1);
8365   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8366   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8367   EVT VT = N->getValueType(0);
8368
8369   if (N0CFP && N1CFP)  // Constant fold
8370     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8371
8372   if (N1CFP) {
8373     const APFloat& V = N1CFP->getValueAPF();
8374     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8375     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8376     if (!V.isNegative()) {
8377       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8378         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8379     } else {
8380       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8381         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8382                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8383     }
8384   }
8385
8386   // copysign(fabs(x), y) -> copysign(x, y)
8387   // copysign(fneg(x), y) -> copysign(x, y)
8388   // copysign(copysign(x,z), y) -> copysign(x, y)
8389   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8390       N0.getOpcode() == ISD::FCOPYSIGN)
8391     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8392                        N0.getOperand(0), N1);
8393
8394   // copysign(x, abs(y)) -> abs(x)
8395   if (N1.getOpcode() == ISD::FABS)
8396     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8397
8398   // copysign(x, copysign(y,z)) -> copysign(x, z)
8399   if (N1.getOpcode() == ISD::FCOPYSIGN)
8400     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8401                        N0, N1.getOperand(1));
8402
8403   // copysign(x, fp_extend(y)) -> copysign(x, y)
8404   // copysign(x, fp_round(y)) -> copysign(x, y)
8405   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8406     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8407                        N0, N1.getOperand(0));
8408
8409   return SDValue();
8410 }
8411
8412 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8413   SDValue N0 = N->getOperand(0);
8414   EVT VT = N->getValueType(0);
8415   EVT OpVT = N0.getValueType();
8416
8417   // fold (sint_to_fp c1) -> c1fp
8418   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8419       // ...but only if the target supports immediate floating-point values
8420       (!LegalOperations ||
8421        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8422     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8423
8424   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8425   // but UINT_TO_FP is legal on this target, try to convert.
8426   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8427       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8428     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8429     if (DAG.SignBitIsZero(N0))
8430       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8431   }
8432
8433   // The next optimizations are desirable only if SELECT_CC can be lowered.
8434   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8435     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8436     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8437         !VT.isVector() &&
8438         (!LegalOperations ||
8439          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8440       SDLoc DL(N);
8441       SDValue Ops[] =
8442         { N0.getOperand(0), N0.getOperand(1),
8443           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8444           N0.getOperand(2) };
8445       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8446     }
8447
8448     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8449     //      (select_cc x, y, 1.0, 0.0,, cc)
8450     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8451         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8452         (!LegalOperations ||
8453          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8454       SDLoc DL(N);
8455       SDValue Ops[] =
8456         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8457           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8458           N0.getOperand(0).getOperand(2) };
8459       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8460     }
8461   }
8462
8463   return SDValue();
8464 }
8465
8466 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8467   SDValue N0 = N->getOperand(0);
8468   EVT VT = N->getValueType(0);
8469   EVT OpVT = N0.getValueType();
8470
8471   // fold (uint_to_fp c1) -> c1fp
8472   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8473       // ...but only if the target supports immediate floating-point values
8474       (!LegalOperations ||
8475        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8476     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8477
8478   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8479   // but SINT_TO_FP is legal on this target, try to convert.
8480   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8481       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8482     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8483     if (DAG.SignBitIsZero(N0))
8484       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8485   }
8486
8487   // The next optimizations are desirable only if SELECT_CC can be lowered.
8488   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8489     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8490
8491     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8492         (!LegalOperations ||
8493          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8494       SDLoc DL(N);
8495       SDValue Ops[] =
8496         { N0.getOperand(0), N0.getOperand(1),
8497           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8498           N0.getOperand(2) };
8499       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8500     }
8501   }
8502
8503   return SDValue();
8504 }
8505
8506 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8507 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8508   SDValue N0 = N->getOperand(0);
8509   EVT VT = N->getValueType(0);
8510
8511   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8512     return SDValue();
8513
8514   SDValue Src = N0.getOperand(0);
8515   EVT SrcVT = Src.getValueType();
8516   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8517   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8518
8519   // We can safely assume the conversion won't overflow the output range,
8520   // because (for example) (uint8_t)18293.f is undefined behavior.
8521
8522   // Since we can assume the conversion won't overflow, our decision as to
8523   // whether the input will fit in the float should depend on the minimum
8524   // of the input range and output range.
8525
8526   // This means this is also safe for a signed input and unsigned output, since
8527   // a negative input would lead to undefined behavior.
8528   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8529   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8530   unsigned ActualSize = std::min(InputSize, OutputSize);
8531   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8532
8533   // We can only fold away the float conversion if the input range can be
8534   // represented exactly in the float range.
8535   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8536     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8537       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8538                                                        : ISD::ZERO_EXTEND;
8539       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8540     }
8541     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8542       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8543     if (SrcVT == VT)
8544       return Src;
8545     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8546   }
8547   return SDValue();
8548 }
8549
8550 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8551   SDValue N0 = N->getOperand(0);
8552   EVT VT = N->getValueType(0);
8553
8554   // fold (fp_to_sint c1fp) -> c1
8555   if (isConstantFPBuildVectorOrConstantFP(N0))
8556     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8557
8558   return FoldIntToFPToInt(N, DAG);
8559 }
8560
8561 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8562   SDValue N0 = N->getOperand(0);
8563   EVT VT = N->getValueType(0);
8564
8565   // fold (fp_to_uint c1fp) -> c1
8566   if (isConstantFPBuildVectorOrConstantFP(N0))
8567     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8568
8569   return FoldIntToFPToInt(N, DAG);
8570 }
8571
8572 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8573   SDValue N0 = N->getOperand(0);
8574   SDValue N1 = N->getOperand(1);
8575   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8576   EVT VT = N->getValueType(0);
8577
8578   // fold (fp_round c1fp) -> c1fp
8579   if (N0CFP)
8580     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8581
8582   // fold (fp_round (fp_extend x)) -> x
8583   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8584     return N0.getOperand(0);
8585
8586   // fold (fp_round (fp_round x)) -> (fp_round x)
8587   if (N0.getOpcode() == ISD::FP_ROUND) {
8588     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8589     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8590     // If the first fp_round isn't a value preserving truncation, it might
8591     // introduce a tie in the second fp_round, that wouldn't occur in the
8592     // single-step fp_round we want to fold to.
8593     // In other words, double rounding isn't the same as rounding.
8594     // Also, this is a value preserving truncation iff both fp_round's are.
8595     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8596       SDLoc DL(N);
8597       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8598                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8599     }
8600   }
8601
8602   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8603   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8604     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8605                               N0.getOperand(0), N1);
8606     AddToWorklist(Tmp.getNode());
8607     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8608                        Tmp, N0.getOperand(1));
8609   }
8610
8611   return SDValue();
8612 }
8613
8614 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8615   SDValue N0 = N->getOperand(0);
8616   EVT VT = N->getValueType(0);
8617   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8618   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8619
8620   // fold (fp_round_inreg c1fp) -> c1fp
8621   if (N0CFP && isTypeLegal(EVT)) {
8622     SDLoc DL(N);
8623     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8624     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8625   }
8626
8627   return SDValue();
8628 }
8629
8630 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8631   SDValue N0 = N->getOperand(0);
8632   EVT VT = N->getValueType(0);
8633
8634   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8635   if (N->hasOneUse() &&
8636       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8637     return SDValue();
8638
8639   // fold (fp_extend c1fp) -> c1fp
8640   if (isConstantFPBuildVectorOrConstantFP(N0))
8641     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8642
8643   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8644   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8645       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8646     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8647
8648   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8649   // value of X.
8650   if (N0.getOpcode() == ISD::FP_ROUND
8651       && N0.getNode()->getConstantOperandVal(1) == 1) {
8652     SDValue In = N0.getOperand(0);
8653     if (In.getValueType() == VT) return In;
8654     if (VT.bitsLT(In.getValueType()))
8655       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8656                          In, N0.getOperand(1));
8657     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8658   }
8659
8660   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8661   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8662        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8663     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8664     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8665                                      LN0->getChain(),
8666                                      LN0->getBasePtr(), N0.getValueType(),
8667                                      LN0->getMemOperand());
8668     CombineTo(N, ExtLoad);
8669     CombineTo(N0.getNode(),
8670               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8671                           N0.getValueType(), ExtLoad,
8672                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8673               ExtLoad.getValue(1));
8674     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8675   }
8676
8677   return SDValue();
8678 }
8679
8680 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8681   SDValue N0 = N->getOperand(0);
8682   EVT VT = N->getValueType(0);
8683
8684   // fold (fceil c1) -> fceil(c1)
8685   if (isConstantFPBuildVectorOrConstantFP(N0))
8686     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8687
8688   return SDValue();
8689 }
8690
8691 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8692   SDValue N0 = N->getOperand(0);
8693   EVT VT = N->getValueType(0);
8694
8695   // fold (ftrunc c1) -> ftrunc(c1)
8696   if (isConstantFPBuildVectorOrConstantFP(N0))
8697     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8698
8699   return SDValue();
8700 }
8701
8702 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8703   SDValue N0 = N->getOperand(0);
8704   EVT VT = N->getValueType(0);
8705
8706   // fold (ffloor c1) -> ffloor(c1)
8707   if (isConstantFPBuildVectorOrConstantFP(N0))
8708     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8709
8710   return SDValue();
8711 }
8712
8713 // FIXME: FNEG and FABS have a lot in common; refactor.
8714 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8715   SDValue N0 = N->getOperand(0);
8716   EVT VT = N->getValueType(0);
8717
8718   // Constant fold FNEG.
8719   if (isConstantFPBuildVectorOrConstantFP(N0))
8720     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8721
8722   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8723                          &DAG.getTarget().Options))
8724     return GetNegatedExpression(N0, DAG, LegalOperations);
8725
8726   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8727   // constant pool values.
8728   if (!TLI.isFNegFree(VT) &&
8729       N0.getOpcode() == ISD::BITCAST &&
8730       N0.getNode()->hasOneUse()) {
8731     SDValue Int = N0.getOperand(0);
8732     EVT IntVT = Int.getValueType();
8733     if (IntVT.isInteger() && !IntVT.isVector()) {
8734       APInt SignMask;
8735       if (N0.getValueType().isVector()) {
8736         // For a vector, get a mask such as 0x80... per scalar element
8737         // and splat it.
8738         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8739         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8740       } else {
8741         // For a scalar, just generate 0x80...
8742         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8743       }
8744       SDLoc DL0(N0);
8745       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8746                         DAG.getConstant(SignMask, DL0, IntVT));
8747       AddToWorklist(Int.getNode());
8748       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8749     }
8750   }
8751
8752   // (fneg (fmul c, x)) -> (fmul -c, x)
8753   if (N0.getOpcode() == ISD::FMUL) {
8754     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8755     if (CFP1) {
8756       APFloat CVal = CFP1->getValueAPF();
8757       CVal.changeSign();
8758       if (Level >= AfterLegalizeDAG &&
8759           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8760            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8761         return DAG.getNode(
8762             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8763             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8764     }
8765   }
8766
8767   return SDValue();
8768 }
8769
8770 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8771   SDValue N0 = N->getOperand(0);
8772   SDValue N1 = N->getOperand(1);
8773   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8774   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8775
8776   if (N0CFP && N1CFP) {
8777     const APFloat &C0 = N0CFP->getValueAPF();
8778     const APFloat &C1 = N1CFP->getValueAPF();
8779     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8780   }
8781
8782   if (N0CFP) {
8783     EVT VT = N->getValueType(0);
8784     // Canonicalize to constant on RHS.
8785     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8786   }
8787
8788   return SDValue();
8789 }
8790
8791 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8792   SDValue N0 = N->getOperand(0);
8793   SDValue N1 = N->getOperand(1);
8794   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8795   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8796
8797   if (N0CFP && N1CFP) {
8798     const APFloat &C0 = N0CFP->getValueAPF();
8799     const APFloat &C1 = N1CFP->getValueAPF();
8800     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8801   }
8802
8803   if (N0CFP) {
8804     EVT VT = N->getValueType(0);
8805     // Canonicalize to constant on RHS.
8806     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8807   }
8808
8809   return SDValue();
8810 }
8811
8812 SDValue DAGCombiner::visitFABS(SDNode *N) {
8813   SDValue N0 = N->getOperand(0);
8814   EVT VT = N->getValueType(0);
8815
8816   // fold (fabs c1) -> fabs(c1)
8817   if (isConstantFPBuildVectorOrConstantFP(N0))
8818     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8819
8820   // fold (fabs (fabs x)) -> (fabs x)
8821   if (N0.getOpcode() == ISD::FABS)
8822     return N->getOperand(0);
8823
8824   // fold (fabs (fneg x)) -> (fabs x)
8825   // fold (fabs (fcopysign x, y)) -> (fabs x)
8826   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8827     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8828
8829   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8830   // constant pool values.
8831   if (!TLI.isFAbsFree(VT) &&
8832       N0.getOpcode() == ISD::BITCAST &&
8833       N0.getNode()->hasOneUse()) {
8834     SDValue Int = N0.getOperand(0);
8835     EVT IntVT = Int.getValueType();
8836     if (IntVT.isInteger() && !IntVT.isVector()) {
8837       APInt SignMask;
8838       if (N0.getValueType().isVector()) {
8839         // For a vector, get a mask such as 0x7f... per scalar element
8840         // and splat it.
8841         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8842         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8843       } else {
8844         // For a scalar, just generate 0x7f...
8845         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8846       }
8847       SDLoc DL(N0);
8848       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8849                         DAG.getConstant(SignMask, DL, IntVT));
8850       AddToWorklist(Int.getNode());
8851       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8852     }
8853   }
8854
8855   return SDValue();
8856 }
8857
8858 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8859   SDValue Chain = N->getOperand(0);
8860   SDValue N1 = N->getOperand(1);
8861   SDValue N2 = N->getOperand(2);
8862
8863   // If N is a constant we could fold this into a fallthrough or unconditional
8864   // branch. However that doesn't happen very often in normal code, because
8865   // Instcombine/SimplifyCFG should have handled the available opportunities.
8866   // If we did this folding here, it would be necessary to update the
8867   // MachineBasicBlock CFG, which is awkward.
8868
8869   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8870   // on the target.
8871   if (N1.getOpcode() == ISD::SETCC &&
8872       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8873                                    N1.getOperand(0).getValueType())) {
8874     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8875                        Chain, N1.getOperand(2),
8876                        N1.getOperand(0), N1.getOperand(1), N2);
8877   }
8878
8879   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8880       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8881        (N1.getOperand(0).hasOneUse() &&
8882         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8883     SDNode *Trunc = nullptr;
8884     if (N1.getOpcode() == ISD::TRUNCATE) {
8885       // Look pass the truncate.
8886       Trunc = N1.getNode();
8887       N1 = N1.getOperand(0);
8888     }
8889
8890     // Match this pattern so that we can generate simpler code:
8891     //
8892     //   %a = ...
8893     //   %b = and i32 %a, 2
8894     //   %c = srl i32 %b, 1
8895     //   brcond i32 %c ...
8896     //
8897     // into
8898     //
8899     //   %a = ...
8900     //   %b = and i32 %a, 2
8901     //   %c = setcc eq %b, 0
8902     //   brcond %c ...
8903     //
8904     // This applies only when the AND constant value has one bit set and the
8905     // SRL constant is equal to the log2 of the AND constant. The back-end is
8906     // smart enough to convert the result into a TEST/JMP sequence.
8907     SDValue Op0 = N1.getOperand(0);
8908     SDValue Op1 = N1.getOperand(1);
8909
8910     if (Op0.getOpcode() == ISD::AND &&
8911         Op1.getOpcode() == ISD::Constant) {
8912       SDValue AndOp1 = Op0.getOperand(1);
8913
8914       if (AndOp1.getOpcode() == ISD::Constant) {
8915         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8916
8917         if (AndConst.isPowerOf2() &&
8918             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8919           SDLoc DL(N);
8920           SDValue SetCC =
8921             DAG.getSetCC(DL,
8922                          getSetCCResultType(Op0.getValueType()),
8923                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8924                          ISD::SETNE);
8925
8926           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8927                                           MVT::Other, Chain, SetCC, N2);
8928           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8929           // will convert it back to (X & C1) >> C2.
8930           CombineTo(N, NewBRCond, false);
8931           // Truncate is dead.
8932           if (Trunc)
8933             deleteAndRecombine(Trunc);
8934           // Replace the uses of SRL with SETCC
8935           WorklistRemover DeadNodes(*this);
8936           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8937           deleteAndRecombine(N1.getNode());
8938           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8939         }
8940       }
8941     }
8942
8943     if (Trunc)
8944       // Restore N1 if the above transformation doesn't match.
8945       N1 = N->getOperand(1);
8946   }
8947
8948   // Transform br(xor(x, y)) -> br(x != y)
8949   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8950   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8951     SDNode *TheXor = N1.getNode();
8952     SDValue Op0 = TheXor->getOperand(0);
8953     SDValue Op1 = TheXor->getOperand(1);
8954     if (Op0.getOpcode() == Op1.getOpcode()) {
8955       // Avoid missing important xor optimizations.
8956       SDValue Tmp = visitXOR(TheXor);
8957       if (Tmp.getNode()) {
8958         if (Tmp.getNode() != TheXor) {
8959           DEBUG(dbgs() << "\nReplacing.8 ";
8960                 TheXor->dump(&DAG);
8961                 dbgs() << "\nWith: ";
8962                 Tmp.getNode()->dump(&DAG);
8963                 dbgs() << '\n');
8964           WorklistRemover DeadNodes(*this);
8965           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8966           deleteAndRecombine(TheXor);
8967           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8968                              MVT::Other, Chain, Tmp, N2);
8969         }
8970
8971         // visitXOR has changed XOR's operands or replaced the XOR completely,
8972         // bail out.
8973         return SDValue(N, 0);
8974       }
8975     }
8976
8977     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8978       bool Equal = false;
8979       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8980         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8981             Op0.getOpcode() == ISD::XOR) {
8982           TheXor = Op0.getNode();
8983           Equal = true;
8984         }
8985
8986       EVT SetCCVT = N1.getValueType();
8987       if (LegalTypes)
8988         SetCCVT = getSetCCResultType(SetCCVT);
8989       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8990                                    SetCCVT,
8991                                    Op0, Op1,
8992                                    Equal ? ISD::SETEQ : ISD::SETNE);
8993       // Replace the uses of XOR with SETCC
8994       WorklistRemover DeadNodes(*this);
8995       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8996       deleteAndRecombine(N1.getNode());
8997       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8998                          MVT::Other, Chain, SetCC, N2);
8999     }
9000   }
9001
9002   return SDValue();
9003 }
9004
9005 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
9006 //
9007 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
9008   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
9009   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
9010
9011   // If N is a constant we could fold this into a fallthrough or unconditional
9012   // branch. However that doesn't happen very often in normal code, because
9013   // Instcombine/SimplifyCFG should have handled the available opportunities.
9014   // If we did this folding here, it would be necessary to update the
9015   // MachineBasicBlock CFG, which is awkward.
9016
9017   // Use SimplifySetCC to simplify SETCC's.
9018   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
9019                                CondLHS, CondRHS, CC->get(), SDLoc(N),
9020                                false);
9021   if (Simp.getNode()) AddToWorklist(Simp.getNode());
9022
9023   // fold to a simpler setcc
9024   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
9025     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
9026                        N->getOperand(0), Simp.getOperand(2),
9027                        Simp.getOperand(0), Simp.getOperand(1),
9028                        N->getOperand(4));
9029
9030   return SDValue();
9031 }
9032
9033 /// Return true if 'Use' is a load or a store that uses N as its base pointer
9034 /// and that N may be folded in the load / store addressing mode.
9035 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
9036                                     SelectionDAG &DAG,
9037                                     const TargetLowering &TLI) {
9038   EVT VT;
9039   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
9040     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
9041       return false;
9042     VT = LD->getMemoryVT();
9043   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
9044     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
9045       return false;
9046     VT = ST->getMemoryVT();
9047   } else
9048     return false;
9049
9050   TargetLowering::AddrMode AM;
9051   if (N->getOpcode() == ISD::ADD) {
9052     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9053     if (Offset)
9054       // [reg +/- imm]
9055       AM.BaseOffs = Offset->getSExtValue();
9056     else
9057       // [reg +/- reg]
9058       AM.Scale = 1;
9059   } else if (N->getOpcode() == ISD::SUB) {
9060     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
9061     if (Offset)
9062       // [reg +/- imm]
9063       AM.BaseOffs = -Offset->getSExtValue();
9064     else
9065       // [reg +/- reg]
9066       AM.Scale = 1;
9067   } else
9068     return false;
9069
9070   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
9071 }
9072
9073 /// Try turning a load/store into a pre-indexed load/store when the base
9074 /// pointer is an add or subtract and it has other uses besides the load/store.
9075 /// After the transformation, the new indexed load/store has effectively folded
9076 /// the add/subtract in and all of its other uses are redirected to the
9077 /// new load/store.
9078 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
9079   if (Level < AfterLegalizeDAG)
9080     return false;
9081
9082   bool isLoad = true;
9083   SDValue Ptr;
9084   EVT VT;
9085   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9086     if (LD->isIndexed())
9087       return false;
9088     VT = LD->getMemoryVT();
9089     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
9090         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
9091       return false;
9092     Ptr = LD->getBasePtr();
9093   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9094     if (ST->isIndexed())
9095       return false;
9096     VT = ST->getMemoryVT();
9097     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
9098         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
9099       return false;
9100     Ptr = ST->getBasePtr();
9101     isLoad = false;
9102   } else {
9103     return false;
9104   }
9105
9106   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
9107   // out.  There is no reason to make this a preinc/predec.
9108   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9109       Ptr.getNode()->hasOneUse())
9110     return false;
9111
9112   // Ask the target to do addressing mode selection.
9113   SDValue BasePtr;
9114   SDValue Offset;
9115   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9116   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9117     return false;
9118
9119   // Backends without true r+i pre-indexed forms may need to pass a
9120   // constant base with a variable offset so that constant coercion
9121   // will work with the patterns in canonical form.
9122   bool Swapped = false;
9123   if (isa<ConstantSDNode>(BasePtr)) {
9124     std::swap(BasePtr, Offset);
9125     Swapped = true;
9126   }
9127
9128   // Don't create a indexed load / store with zero offset.
9129   if (isa<ConstantSDNode>(Offset) &&
9130       cast<ConstantSDNode>(Offset)->isNullValue())
9131     return false;
9132
9133   // Try turning it into a pre-indexed load / store except when:
9134   // 1) The new base ptr is a frame index.
9135   // 2) If N is a store and the new base ptr is either the same as or is a
9136   //    predecessor of the value being stored.
9137   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9138   //    that would create a cycle.
9139   // 4) All uses are load / store ops that use it as old base ptr.
9140
9141   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9142   // (plus the implicit offset) to a register to preinc anyway.
9143   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9144     return false;
9145
9146   // Check #2.
9147   if (!isLoad) {
9148     SDValue Val = cast<StoreSDNode>(N)->getValue();
9149     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9150       return false;
9151   }
9152
9153   // If the offset is a constant, there may be other adds of constants that
9154   // can be folded with this one. We should do this to avoid having to keep
9155   // a copy of the original base pointer.
9156   SmallVector<SDNode *, 16> OtherUses;
9157   if (isa<ConstantSDNode>(Offset))
9158     for (SDNode *Use : BasePtr.getNode()->uses()) {
9159       if (Use == Ptr.getNode())
9160         continue;
9161
9162       if (Use->isPredecessorOf(N))
9163         continue;
9164
9165       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9166         OtherUses.clear();
9167         break;
9168       }
9169
9170       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9171       if (Op1.getNode() == BasePtr.getNode())
9172         std::swap(Op0, Op1);
9173       assert(Op0.getNode() == BasePtr.getNode() &&
9174              "Use of ADD/SUB but not an operand");
9175
9176       if (!isa<ConstantSDNode>(Op1)) {
9177         OtherUses.clear();
9178         break;
9179       }
9180
9181       // FIXME: In some cases, we can be smarter about this.
9182       if (Op1.getValueType() != Offset.getValueType()) {
9183         OtherUses.clear();
9184         break;
9185       }
9186
9187       OtherUses.push_back(Use);
9188     }
9189
9190   if (Swapped)
9191     std::swap(BasePtr, Offset);
9192
9193   // Now check for #3 and #4.
9194   bool RealUse = false;
9195
9196   // Caches for hasPredecessorHelper
9197   SmallPtrSet<const SDNode *, 32> Visited;
9198   SmallVector<const SDNode *, 16> Worklist;
9199
9200   for (SDNode *Use : Ptr.getNode()->uses()) {
9201     if (Use == N)
9202       continue;
9203     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9204       return false;
9205
9206     // If Ptr may be folded in addressing mode of other use, then it's
9207     // not profitable to do this transformation.
9208     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9209       RealUse = true;
9210   }
9211
9212   if (!RealUse)
9213     return false;
9214
9215   SDValue Result;
9216   if (isLoad)
9217     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9218                                 BasePtr, Offset, AM);
9219   else
9220     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9221                                  BasePtr, Offset, AM);
9222   ++PreIndexedNodes;
9223   ++NodesCombined;
9224   DEBUG(dbgs() << "\nReplacing.4 ";
9225         N->dump(&DAG);
9226         dbgs() << "\nWith: ";
9227         Result.getNode()->dump(&DAG);
9228         dbgs() << '\n');
9229   WorklistRemover DeadNodes(*this);
9230   if (isLoad) {
9231     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9232     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9233   } else {
9234     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9235   }
9236
9237   // Finally, since the node is now dead, remove it from the graph.
9238   deleteAndRecombine(N);
9239
9240   if (Swapped)
9241     std::swap(BasePtr, Offset);
9242
9243   // Replace other uses of BasePtr that can be updated to use Ptr
9244   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9245     unsigned OffsetIdx = 1;
9246     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9247       OffsetIdx = 0;
9248     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9249            BasePtr.getNode() && "Expected BasePtr operand");
9250
9251     // We need to replace ptr0 in the following expression:
9252     //   x0 * offset0 + y0 * ptr0 = t0
9253     // knowing that
9254     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9255     //
9256     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9257     // indexed load/store and the expresion that needs to be re-written.
9258     //
9259     // Therefore, we have:
9260     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9261
9262     ConstantSDNode *CN =
9263       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9264     int X0, X1, Y0, Y1;
9265     APInt Offset0 = CN->getAPIntValue();
9266     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9267
9268     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9269     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9270     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9271     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9272
9273     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9274
9275     APInt CNV = Offset0;
9276     if (X0 < 0) CNV = -CNV;
9277     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9278     else CNV = CNV - Offset1;
9279
9280     SDLoc DL(OtherUses[i]);
9281
9282     // We can now generate the new expression.
9283     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9284     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9285
9286     SDValue NewUse = DAG.getNode(Opcode,
9287                                  DL,
9288                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9289     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9290     deleteAndRecombine(OtherUses[i]);
9291   }
9292
9293   // Replace the uses of Ptr with uses of the updated base value.
9294   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9295   deleteAndRecombine(Ptr.getNode());
9296
9297   return true;
9298 }
9299
9300 /// Try to combine a load/store with a add/sub of the base pointer node into a
9301 /// post-indexed load/store. The transformation folded the add/subtract into the
9302 /// new indexed load/store effectively and all of its uses are redirected to the
9303 /// new load/store.
9304 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9305   if (Level < AfterLegalizeDAG)
9306     return false;
9307
9308   bool isLoad = true;
9309   SDValue Ptr;
9310   EVT VT;
9311   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9312     if (LD->isIndexed())
9313       return false;
9314     VT = LD->getMemoryVT();
9315     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9316         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9317       return false;
9318     Ptr = LD->getBasePtr();
9319   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9320     if (ST->isIndexed())
9321       return false;
9322     VT = ST->getMemoryVT();
9323     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9324         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9325       return false;
9326     Ptr = ST->getBasePtr();
9327     isLoad = false;
9328   } else {
9329     return false;
9330   }
9331
9332   if (Ptr.getNode()->hasOneUse())
9333     return false;
9334
9335   for (SDNode *Op : Ptr.getNode()->uses()) {
9336     if (Op == N ||
9337         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9338       continue;
9339
9340     SDValue BasePtr;
9341     SDValue Offset;
9342     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9343     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9344       // Don't create a indexed load / store with zero offset.
9345       if (isa<ConstantSDNode>(Offset) &&
9346           cast<ConstantSDNode>(Offset)->isNullValue())
9347         continue;
9348
9349       // Try turning it into a post-indexed load / store except when
9350       // 1) All uses are load / store ops that use it as base ptr (and
9351       //    it may be folded as addressing mmode).
9352       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9353       //    nor a successor of N. Otherwise, if Op is folded that would
9354       //    create a cycle.
9355
9356       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9357         continue;
9358
9359       // Check for #1.
9360       bool TryNext = false;
9361       for (SDNode *Use : BasePtr.getNode()->uses()) {
9362         if (Use == Ptr.getNode())
9363           continue;
9364
9365         // If all the uses are load / store addresses, then don't do the
9366         // transformation.
9367         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9368           bool RealUse = false;
9369           for (SDNode *UseUse : Use->uses()) {
9370             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9371               RealUse = true;
9372           }
9373
9374           if (!RealUse) {
9375             TryNext = true;
9376             break;
9377           }
9378         }
9379       }
9380
9381       if (TryNext)
9382         continue;
9383
9384       // Check for #2
9385       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9386         SDValue Result = isLoad
9387           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9388                                BasePtr, Offset, AM)
9389           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9390                                 BasePtr, Offset, AM);
9391         ++PostIndexedNodes;
9392         ++NodesCombined;
9393         DEBUG(dbgs() << "\nReplacing.5 ";
9394               N->dump(&DAG);
9395               dbgs() << "\nWith: ";
9396               Result.getNode()->dump(&DAG);
9397               dbgs() << '\n');
9398         WorklistRemover DeadNodes(*this);
9399         if (isLoad) {
9400           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9401           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9402         } else {
9403           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9404         }
9405
9406         // Finally, since the node is now dead, remove it from the graph.
9407         deleteAndRecombine(N);
9408
9409         // Replace the uses of Use with uses of the updated base value.
9410         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9411                                       Result.getValue(isLoad ? 1 : 0));
9412         deleteAndRecombine(Op);
9413         return true;
9414       }
9415     }
9416   }
9417
9418   return false;
9419 }
9420
9421 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9422 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9423   ISD::MemIndexedMode AM = LD->getAddressingMode();
9424   assert(AM != ISD::UNINDEXED);
9425   SDValue BP = LD->getOperand(1);
9426   SDValue Inc = LD->getOperand(2);
9427
9428   // Some backends use TargetConstants for load offsets, but don't expect
9429   // TargetConstants in general ADD nodes. We can convert these constants into
9430   // regular Constants (if the constant is not opaque).
9431   assert((Inc.getOpcode() != ISD::TargetConstant ||
9432           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9433          "Cannot split out indexing using opaque target constants");
9434   if (Inc.getOpcode() == ISD::TargetConstant) {
9435     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9436     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9437                           ConstInc->getValueType(0));
9438   }
9439
9440   unsigned Opc =
9441       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9442   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9443 }
9444
9445 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9446   LoadSDNode *LD  = cast<LoadSDNode>(N);
9447   SDValue Chain = LD->getChain();
9448   SDValue Ptr   = LD->getBasePtr();
9449
9450   // If load is not volatile and there are no uses of the loaded value (and
9451   // the updated indexed value in case of indexed loads), change uses of the
9452   // chain value into uses of the chain input (i.e. delete the dead load).
9453   if (!LD->isVolatile()) {
9454     if (N->getValueType(1) == MVT::Other) {
9455       // Unindexed loads.
9456       if (!N->hasAnyUseOfValue(0)) {
9457         // It's not safe to use the two value CombineTo variant here. e.g.
9458         // v1, chain2 = load chain1, loc
9459         // v2, chain3 = load chain2, loc
9460         // v3         = add v2, c
9461         // Now we replace use of chain2 with chain1.  This makes the second load
9462         // isomorphic to the one we are deleting, and thus makes this load live.
9463         DEBUG(dbgs() << "\nReplacing.6 ";
9464               N->dump(&DAG);
9465               dbgs() << "\nWith chain: ";
9466               Chain.getNode()->dump(&DAG);
9467               dbgs() << "\n");
9468         WorklistRemover DeadNodes(*this);
9469         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9470
9471         if (N->use_empty())
9472           deleteAndRecombine(N);
9473
9474         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9475       }
9476     } else {
9477       // Indexed loads.
9478       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9479
9480       // If this load has an opaque TargetConstant offset, then we cannot split
9481       // the indexing into an add/sub directly (that TargetConstant may not be
9482       // valid for a different type of node, and we cannot convert an opaque
9483       // target constant into a regular constant).
9484       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9485                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9486
9487       if (!N->hasAnyUseOfValue(0) &&
9488           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9489         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9490         SDValue Index;
9491         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9492           Index = SplitIndexingFromLoad(LD);
9493           // Try to fold the base pointer arithmetic into subsequent loads and
9494           // stores.
9495           AddUsersToWorklist(N);
9496         } else
9497           Index = DAG.getUNDEF(N->getValueType(1));
9498         DEBUG(dbgs() << "\nReplacing.7 ";
9499               N->dump(&DAG);
9500               dbgs() << "\nWith: ";
9501               Undef.getNode()->dump(&DAG);
9502               dbgs() << " and 2 other values\n");
9503         WorklistRemover DeadNodes(*this);
9504         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9505         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9506         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9507         deleteAndRecombine(N);
9508         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9509       }
9510     }
9511   }
9512
9513   // If this load is directly stored, replace the load value with the stored
9514   // value.
9515   // TODO: Handle store large -> read small portion.
9516   // TODO: Handle TRUNCSTORE/LOADEXT
9517   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9518     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9519       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9520       if (PrevST->getBasePtr() == Ptr &&
9521           PrevST->getValue().getValueType() == N->getValueType(0))
9522       return CombineTo(N, Chain.getOperand(1), Chain);
9523     }
9524   }
9525
9526   // Try to infer better alignment information than the load already has.
9527   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9528     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9529       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9530         SDValue NewLoad =
9531                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9532                               LD->getValueType(0),
9533                               Chain, Ptr, LD->getPointerInfo(),
9534                               LD->getMemoryVT(),
9535                               LD->isVolatile(), LD->isNonTemporal(),
9536                               LD->isInvariant(), Align, LD->getAAInfo());
9537         if (NewLoad.getNode() != N)
9538           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9539       }
9540     }
9541   }
9542
9543   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9544                                                   : DAG.getSubtarget().useAA();
9545 #ifndef NDEBUG
9546   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9547       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9548     UseAA = false;
9549 #endif
9550   if (UseAA && LD->isUnindexed()) {
9551     // Walk up chain skipping non-aliasing memory nodes.
9552     SDValue BetterChain = FindBetterChain(N, Chain);
9553
9554     // If there is a better chain.
9555     if (Chain != BetterChain) {
9556       SDValue ReplLoad;
9557
9558       // Replace the chain to void dependency.
9559       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9560         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9561                                BetterChain, Ptr, LD->getMemOperand());
9562       } else {
9563         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9564                                   LD->getValueType(0),
9565                                   BetterChain, Ptr, LD->getMemoryVT(),
9566                                   LD->getMemOperand());
9567       }
9568
9569       // Create token factor to keep old chain connected.
9570       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9571                                   MVT::Other, Chain, ReplLoad.getValue(1));
9572
9573       // Make sure the new and old chains are cleaned up.
9574       AddToWorklist(Token.getNode());
9575
9576       // Replace uses with load result and token factor. Don't add users
9577       // to work list.
9578       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9579     }
9580   }
9581
9582   // Try transforming N to an indexed load.
9583   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9584     return SDValue(N, 0);
9585
9586   // Try to slice up N to more direct loads if the slices are mapped to
9587   // different register banks or pairing can take place.
9588   if (SliceUpLoad(N))
9589     return SDValue(N, 0);
9590
9591   return SDValue();
9592 }
9593
9594 namespace {
9595 /// \brief Helper structure used to slice a load in smaller loads.
9596 /// Basically a slice is obtained from the following sequence:
9597 /// Origin = load Ty1, Base
9598 /// Shift = srl Ty1 Origin, CstTy Amount
9599 /// Inst = trunc Shift to Ty2
9600 ///
9601 /// Then, it will be rewriten into:
9602 /// Slice = load SliceTy, Base + SliceOffset
9603 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9604 ///
9605 /// SliceTy is deduced from the number of bits that are actually used to
9606 /// build Inst.
9607 struct LoadedSlice {
9608   /// \brief Helper structure used to compute the cost of a slice.
9609   struct Cost {
9610     /// Are we optimizing for code size.
9611     bool ForCodeSize;
9612     /// Various cost.
9613     unsigned Loads;
9614     unsigned Truncates;
9615     unsigned CrossRegisterBanksCopies;
9616     unsigned ZExts;
9617     unsigned Shift;
9618
9619     Cost(bool ForCodeSize = false)
9620         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9621           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9622
9623     /// \brief Get the cost of one isolated slice.
9624     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9625         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9626           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9627       EVT TruncType = LS.Inst->getValueType(0);
9628       EVT LoadedType = LS.getLoadedType();
9629       if (TruncType != LoadedType &&
9630           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9631         ZExts = 1;
9632     }
9633
9634     /// \brief Account for slicing gain in the current cost.
9635     /// Slicing provide a few gains like removing a shift or a
9636     /// truncate. This method allows to grow the cost of the original
9637     /// load with the gain from this slice.
9638     void addSliceGain(const LoadedSlice &LS) {
9639       // Each slice saves a truncate.
9640       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9641       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9642                               LS.Inst->getOperand(0).getValueType()))
9643         ++Truncates;
9644       // If there is a shift amount, this slice gets rid of it.
9645       if (LS.Shift)
9646         ++Shift;
9647       // If this slice can merge a cross register bank copy, account for it.
9648       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9649         ++CrossRegisterBanksCopies;
9650     }
9651
9652     Cost &operator+=(const Cost &RHS) {
9653       Loads += RHS.Loads;
9654       Truncates += RHS.Truncates;
9655       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9656       ZExts += RHS.ZExts;
9657       Shift += RHS.Shift;
9658       return *this;
9659     }
9660
9661     bool operator==(const Cost &RHS) const {
9662       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9663              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9664              ZExts == RHS.ZExts && Shift == RHS.Shift;
9665     }
9666
9667     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9668
9669     bool operator<(const Cost &RHS) const {
9670       // Assume cross register banks copies are as expensive as loads.
9671       // FIXME: Do we want some more target hooks?
9672       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9673       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9674       // Unless we are optimizing for code size, consider the
9675       // expensive operation first.
9676       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9677         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9678       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9679              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9680     }
9681
9682     bool operator>(const Cost &RHS) const { return RHS < *this; }
9683
9684     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9685
9686     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9687   };
9688   // The last instruction that represent the slice. This should be a
9689   // truncate instruction.
9690   SDNode *Inst;
9691   // The original load instruction.
9692   LoadSDNode *Origin;
9693   // The right shift amount in bits from the original load.
9694   unsigned Shift;
9695   // The DAG from which Origin came from.
9696   // This is used to get some contextual information about legal types, etc.
9697   SelectionDAG *DAG;
9698
9699   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9700               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9701       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9702
9703   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9704   /// \return Result is \p BitWidth and has used bits set to 1 and
9705   ///         not used bits set to 0.
9706   APInt getUsedBits() const {
9707     // Reproduce the trunc(lshr) sequence:
9708     // - Start from the truncated value.
9709     // - Zero extend to the desired bit width.
9710     // - Shift left.
9711     assert(Origin && "No original load to compare against.");
9712     unsigned BitWidth = Origin->getValueSizeInBits(0);
9713     assert(Inst && "This slice is not bound to an instruction");
9714     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9715            "Extracted slice is bigger than the whole type!");
9716     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9717     UsedBits.setAllBits();
9718     UsedBits = UsedBits.zext(BitWidth);
9719     UsedBits <<= Shift;
9720     return UsedBits;
9721   }
9722
9723   /// \brief Get the size of the slice to be loaded in bytes.
9724   unsigned getLoadedSize() const {
9725     unsigned SliceSize = getUsedBits().countPopulation();
9726     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9727     return SliceSize / 8;
9728   }
9729
9730   /// \brief Get the type that will be loaded for this slice.
9731   /// Note: This may not be the final type for the slice.
9732   EVT getLoadedType() const {
9733     assert(DAG && "Missing context");
9734     LLVMContext &Ctxt = *DAG->getContext();
9735     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9736   }
9737
9738   /// \brief Get the alignment of the load used for this slice.
9739   unsigned getAlignment() const {
9740     unsigned Alignment = Origin->getAlignment();
9741     unsigned Offset = getOffsetFromBase();
9742     if (Offset != 0)
9743       Alignment = MinAlign(Alignment, Alignment + Offset);
9744     return Alignment;
9745   }
9746
9747   /// \brief Check if this slice can be rewritten with legal operations.
9748   bool isLegal() const {
9749     // An invalid slice is not legal.
9750     if (!Origin || !Inst || !DAG)
9751       return false;
9752
9753     // Offsets are for indexed load only, we do not handle that.
9754     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9755       return false;
9756
9757     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9758
9759     // Check that the type is legal.
9760     EVT SliceType = getLoadedType();
9761     if (!TLI.isTypeLegal(SliceType))
9762       return false;
9763
9764     // Check that the load is legal for this type.
9765     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9766       return false;
9767
9768     // Check that the offset can be computed.
9769     // 1. Check its type.
9770     EVT PtrType = Origin->getBasePtr().getValueType();
9771     if (PtrType == MVT::Untyped || PtrType.isExtended())
9772       return false;
9773
9774     // 2. Check that it fits in the immediate.
9775     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9776       return false;
9777
9778     // 3. Check that the computation is legal.
9779     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9780       return false;
9781
9782     // Check that the zext is legal if it needs one.
9783     EVT TruncateType = Inst->getValueType(0);
9784     if (TruncateType != SliceType &&
9785         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9786       return false;
9787
9788     return true;
9789   }
9790
9791   /// \brief Get the offset in bytes of this slice in the original chunk of
9792   /// bits.
9793   /// \pre DAG != nullptr.
9794   uint64_t getOffsetFromBase() const {
9795     assert(DAG && "Missing context.");
9796     bool IsBigEndian =
9797         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9798     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9799     uint64_t Offset = Shift / 8;
9800     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9801     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9802            "The size of the original loaded type is not a multiple of a"
9803            " byte.");
9804     // If Offset is bigger than TySizeInBytes, it means we are loading all
9805     // zeros. This should have been optimized before in the process.
9806     assert(TySizeInBytes > Offset &&
9807            "Invalid shift amount for given loaded size");
9808     if (IsBigEndian)
9809       Offset = TySizeInBytes - Offset - getLoadedSize();
9810     return Offset;
9811   }
9812
9813   /// \brief Generate the sequence of instructions to load the slice
9814   /// represented by this object and redirect the uses of this slice to
9815   /// this new sequence of instructions.
9816   /// \pre this->Inst && this->Origin are valid Instructions and this
9817   /// object passed the legal check: LoadedSlice::isLegal returned true.
9818   /// \return The last instruction of the sequence used to load the slice.
9819   SDValue loadSlice() const {
9820     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9821     const SDValue &OldBaseAddr = Origin->getBasePtr();
9822     SDValue BaseAddr = OldBaseAddr;
9823     // Get the offset in that chunk of bytes w.r.t. the endianess.
9824     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9825     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9826     if (Offset) {
9827       // BaseAddr = BaseAddr + Offset.
9828       EVT ArithType = BaseAddr.getValueType();
9829       SDLoc DL(Origin);
9830       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9831                               DAG->getConstant(Offset, DL, ArithType));
9832     }
9833
9834     // Create the type of the loaded slice according to its size.
9835     EVT SliceType = getLoadedType();
9836
9837     // Create the load for the slice.
9838     SDValue LastInst = DAG->getLoad(
9839         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9840         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9841         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9842     // If the final type is not the same as the loaded type, this means that
9843     // we have to pad with zero. Create a zero extend for that.
9844     EVT FinalType = Inst->getValueType(0);
9845     if (SliceType != FinalType)
9846       LastInst =
9847           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9848     return LastInst;
9849   }
9850
9851   /// \brief Check if this slice can be merged with an expensive cross register
9852   /// bank copy. E.g.,
9853   /// i = load i32
9854   /// f = bitcast i32 i to float
9855   bool canMergeExpensiveCrossRegisterBankCopy() const {
9856     if (!Inst || !Inst->hasOneUse())
9857       return false;
9858     SDNode *Use = *Inst->use_begin();
9859     if (Use->getOpcode() != ISD::BITCAST)
9860       return false;
9861     assert(DAG && "Missing context");
9862     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9863     EVT ResVT = Use->getValueType(0);
9864     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9865     const TargetRegisterClass *ArgRC =
9866         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9867     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9868       return false;
9869
9870     // At this point, we know that we perform a cross-register-bank copy.
9871     // Check if it is expensive.
9872     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9873     // Assume bitcasts are cheap, unless both register classes do not
9874     // explicitly share a common sub class.
9875     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9876       return false;
9877
9878     // Check if it will be merged with the load.
9879     // 1. Check the alignment constraint.
9880     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9881         ResVT.getTypeForEVT(*DAG->getContext()));
9882
9883     if (RequiredAlignment > getAlignment())
9884       return false;
9885
9886     // 2. Check that the load is a legal operation for that type.
9887     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9888       return false;
9889
9890     // 3. Check that we do not have a zext in the way.
9891     if (Inst->getValueType(0) != getLoadedType())
9892       return false;
9893
9894     return true;
9895   }
9896 };
9897 }
9898
9899 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9900 /// \p UsedBits looks like 0..0 1..1 0..0.
9901 static bool areUsedBitsDense(const APInt &UsedBits) {
9902   // If all the bits are one, this is dense!
9903   if (UsedBits.isAllOnesValue())
9904     return true;
9905
9906   // Get rid of the unused bits on the right.
9907   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9908   // Get rid of the unused bits on the left.
9909   if (NarrowedUsedBits.countLeadingZeros())
9910     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9911   // Check that the chunk of bits is completely used.
9912   return NarrowedUsedBits.isAllOnesValue();
9913 }
9914
9915 /// \brief Check whether or not \p First and \p Second are next to each other
9916 /// in memory. This means that there is no hole between the bits loaded
9917 /// by \p First and the bits loaded by \p Second.
9918 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9919                                      const LoadedSlice &Second) {
9920   assert(First.Origin == Second.Origin && First.Origin &&
9921          "Unable to match different memory origins.");
9922   APInt UsedBits = First.getUsedBits();
9923   assert((UsedBits & Second.getUsedBits()) == 0 &&
9924          "Slices are not supposed to overlap.");
9925   UsedBits |= Second.getUsedBits();
9926   return areUsedBitsDense(UsedBits);
9927 }
9928
9929 /// \brief Adjust the \p GlobalLSCost according to the target
9930 /// paring capabilities and the layout of the slices.
9931 /// \pre \p GlobalLSCost should account for at least as many loads as
9932 /// there is in the slices in \p LoadedSlices.
9933 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9934                                  LoadedSlice::Cost &GlobalLSCost) {
9935   unsigned NumberOfSlices = LoadedSlices.size();
9936   // If there is less than 2 elements, no pairing is possible.
9937   if (NumberOfSlices < 2)
9938     return;
9939
9940   // Sort the slices so that elements that are likely to be next to each
9941   // other in memory are next to each other in the list.
9942   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9943             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9944     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9945     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9946   });
9947   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9948   // First (resp. Second) is the first (resp. Second) potentially candidate
9949   // to be placed in a paired load.
9950   const LoadedSlice *First = nullptr;
9951   const LoadedSlice *Second = nullptr;
9952   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9953                 // Set the beginning of the pair.
9954                                                            First = Second) {
9955
9956     Second = &LoadedSlices[CurrSlice];
9957
9958     // If First is NULL, it means we start a new pair.
9959     // Get to the next slice.
9960     if (!First)
9961       continue;
9962
9963     EVT LoadedType = First->getLoadedType();
9964
9965     // If the types of the slices are different, we cannot pair them.
9966     if (LoadedType != Second->getLoadedType())
9967       continue;
9968
9969     // Check if the target supplies paired loads for this type.
9970     unsigned RequiredAlignment = 0;
9971     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9972       // move to the next pair, this type is hopeless.
9973       Second = nullptr;
9974       continue;
9975     }
9976     // Check if we meet the alignment requirement.
9977     if (RequiredAlignment > First->getAlignment())
9978       continue;
9979
9980     // Check that both loads are next to each other in memory.
9981     if (!areSlicesNextToEachOther(*First, *Second))
9982       continue;
9983
9984     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9985     --GlobalLSCost.Loads;
9986     // Move to the next pair.
9987     Second = nullptr;
9988   }
9989 }
9990
9991 /// \brief Check the profitability of all involved LoadedSlice.
9992 /// Currently, it is considered profitable if there is exactly two
9993 /// involved slices (1) which are (2) next to each other in memory, and
9994 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9995 ///
9996 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9997 /// the elements themselves.
9998 ///
9999 /// FIXME: When the cost model will be mature enough, we can relax
10000 /// constraints (1) and (2).
10001 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
10002                                 const APInt &UsedBits, bool ForCodeSize) {
10003   unsigned NumberOfSlices = LoadedSlices.size();
10004   if (StressLoadSlicing)
10005     return NumberOfSlices > 1;
10006
10007   // Check (1).
10008   if (NumberOfSlices != 2)
10009     return false;
10010
10011   // Check (2).
10012   if (!areUsedBitsDense(UsedBits))
10013     return false;
10014
10015   // Check (3).
10016   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
10017   // The original code has one big load.
10018   OrigCost.Loads = 1;
10019   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
10020     const LoadedSlice &LS = LoadedSlices[CurrSlice];
10021     // Accumulate the cost of all the slices.
10022     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
10023     GlobalSlicingCost += SliceCost;
10024
10025     // Account as cost in the original configuration the gain obtained
10026     // with the current slices.
10027     OrigCost.addSliceGain(LS);
10028   }
10029
10030   // If the target supports paired load, adjust the cost accordingly.
10031   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
10032   return OrigCost > GlobalSlicingCost;
10033 }
10034
10035 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
10036 /// operations, split it in the various pieces being extracted.
10037 ///
10038 /// This sort of thing is introduced by SROA.
10039 /// This slicing takes care not to insert overlapping loads.
10040 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
10041 bool DAGCombiner::SliceUpLoad(SDNode *N) {
10042   if (Level < AfterLegalizeDAG)
10043     return false;
10044
10045   LoadSDNode *LD = cast<LoadSDNode>(N);
10046   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
10047       !LD->getValueType(0).isInteger())
10048     return false;
10049
10050   // Keep track of already used bits to detect overlapping values.
10051   // In that case, we will just abort the transformation.
10052   APInt UsedBits(LD->getValueSizeInBits(0), 0);
10053
10054   SmallVector<LoadedSlice, 4> LoadedSlices;
10055
10056   // Check if this load is used as several smaller chunks of bits.
10057   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
10058   // of computation for each trunc.
10059   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
10060        UI != UIEnd; ++UI) {
10061     // Skip the uses of the chain.
10062     if (UI.getUse().getResNo() != 0)
10063       continue;
10064
10065     SDNode *User = *UI;
10066     unsigned Shift = 0;
10067
10068     // Check if this is a trunc(lshr).
10069     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
10070         isa<ConstantSDNode>(User->getOperand(1))) {
10071       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
10072       User = *User->use_begin();
10073     }
10074
10075     // At this point, User is a Truncate, iff we encountered, trunc or
10076     // trunc(lshr).
10077     if (User->getOpcode() != ISD::TRUNCATE)
10078       return false;
10079
10080     // The width of the type must be a power of 2 and greater than 8-bits.
10081     // Otherwise the load cannot be represented in LLVM IR.
10082     // Moreover, if we shifted with a non-8-bits multiple, the slice
10083     // will be across several bytes. We do not support that.
10084     unsigned Width = User->getValueSizeInBits(0);
10085     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
10086       return 0;
10087
10088     // Build the slice for this chain of computations.
10089     LoadedSlice LS(User, LD, Shift, &DAG);
10090     APInt CurrentUsedBits = LS.getUsedBits();
10091
10092     // Check if this slice overlaps with another.
10093     if ((CurrentUsedBits & UsedBits) != 0)
10094       return false;
10095     // Update the bits used globally.
10096     UsedBits |= CurrentUsedBits;
10097
10098     // Check if the new slice would be legal.
10099     if (!LS.isLegal())
10100       return false;
10101
10102     // Record the slice.
10103     LoadedSlices.push_back(LS);
10104   }
10105
10106   // Abort slicing if it does not seem to be profitable.
10107   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
10108     return false;
10109
10110   ++SlicedLoads;
10111
10112   // Rewrite each chain to use an independent load.
10113   // By construction, each chain can be represented by a unique load.
10114
10115   // Prepare the argument for the new token factor for all the slices.
10116   SmallVector<SDValue, 8> ArgChains;
10117   for (SmallVectorImpl<LoadedSlice>::const_iterator
10118            LSIt = LoadedSlices.begin(),
10119            LSItEnd = LoadedSlices.end();
10120        LSIt != LSItEnd; ++LSIt) {
10121     SDValue SliceInst = LSIt->loadSlice();
10122     CombineTo(LSIt->Inst, SliceInst, true);
10123     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10124       SliceInst = SliceInst.getOperand(0);
10125     assert(SliceInst->getOpcode() == ISD::LOAD &&
10126            "It takes more than a zext to get to the loaded slice!!");
10127     ArgChains.push_back(SliceInst.getValue(1));
10128   }
10129
10130   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10131                               ArgChains);
10132   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10133   return true;
10134 }
10135
10136 /// Check to see if V is (and load (ptr), imm), where the load is having
10137 /// specific bytes cleared out.  If so, return the byte size being masked out
10138 /// and the shift amount.
10139 static std::pair<unsigned, unsigned>
10140 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10141   std::pair<unsigned, unsigned> Result(0, 0);
10142
10143   // Check for the structure we're looking for.
10144   if (V->getOpcode() != ISD::AND ||
10145       !isa<ConstantSDNode>(V->getOperand(1)) ||
10146       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10147     return Result;
10148
10149   // Check the chain and pointer.
10150   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10151   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10152
10153   // The store should be chained directly to the load or be an operand of a
10154   // tokenfactor.
10155   if (LD == Chain.getNode())
10156     ; // ok.
10157   else if (Chain->getOpcode() != ISD::TokenFactor)
10158     return Result; // Fail.
10159   else {
10160     bool isOk = false;
10161     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10162       if (Chain->getOperand(i).getNode() == LD) {
10163         isOk = true;
10164         break;
10165       }
10166     if (!isOk) return Result;
10167   }
10168
10169   // This only handles simple types.
10170   if (V.getValueType() != MVT::i16 &&
10171       V.getValueType() != MVT::i32 &&
10172       V.getValueType() != MVT::i64)
10173     return Result;
10174
10175   // Check the constant mask.  Invert it so that the bits being masked out are
10176   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10177   // follow the sign bit for uniformity.
10178   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10179   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10180   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10181   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10182   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10183   if (NotMaskLZ == 64) return Result;  // All zero mask.
10184
10185   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10186   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10187     return Result;
10188
10189   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10190   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10191     NotMaskLZ -= 64-V.getValueSizeInBits();
10192
10193   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10194   switch (MaskedBytes) {
10195   case 1:
10196   case 2:
10197   case 4: break;
10198   default: return Result; // All one mask, or 5-byte mask.
10199   }
10200
10201   // Verify that the first bit starts at a multiple of mask so that the access
10202   // is aligned the same as the access width.
10203   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10204
10205   Result.first = MaskedBytes;
10206   Result.second = NotMaskTZ/8;
10207   return Result;
10208 }
10209
10210
10211 /// Check to see if IVal is something that provides a value as specified by
10212 /// MaskInfo. If so, replace the specified store with a narrower store of
10213 /// truncated IVal.
10214 static SDNode *
10215 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10216                                 SDValue IVal, StoreSDNode *St,
10217                                 DAGCombiner *DC) {
10218   unsigned NumBytes = MaskInfo.first;
10219   unsigned ByteShift = MaskInfo.second;
10220   SelectionDAG &DAG = DC->getDAG();
10221
10222   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10223   // that uses this.  If not, this is not a replacement.
10224   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10225                                   ByteShift*8, (ByteShift+NumBytes)*8);
10226   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10227
10228   // Check that it is legal on the target to do this.  It is legal if the new
10229   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10230   // legalization.
10231   MVT VT = MVT::getIntegerVT(NumBytes*8);
10232   if (!DC->isTypeLegal(VT))
10233     return nullptr;
10234
10235   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10236   // shifted by ByteShift and truncated down to NumBytes.
10237   if (ByteShift) {
10238     SDLoc DL(IVal);
10239     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10240                        DAG.getConstant(ByteShift*8, DL,
10241                                     DC->getShiftAmountTy(IVal.getValueType())));
10242   }
10243
10244   // Figure out the offset for the store and the alignment of the access.
10245   unsigned StOffset;
10246   unsigned NewAlign = St->getAlignment();
10247
10248   if (DAG.getTargetLoweringInfo().isLittleEndian())
10249     StOffset = ByteShift;
10250   else
10251     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10252
10253   SDValue Ptr = St->getBasePtr();
10254   if (StOffset) {
10255     SDLoc DL(IVal);
10256     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10257                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10258     NewAlign = MinAlign(NewAlign, StOffset);
10259   }
10260
10261   // Truncate down to the new size.
10262   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10263
10264   ++OpsNarrowed;
10265   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10266                       St->getPointerInfo().getWithOffset(StOffset),
10267                       false, false, NewAlign).getNode();
10268 }
10269
10270
10271 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10272 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10273 /// narrowing the load and store if it would end up being a win for performance
10274 /// or code size.
10275 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10276   StoreSDNode *ST  = cast<StoreSDNode>(N);
10277   if (ST->isVolatile())
10278     return SDValue();
10279
10280   SDValue Chain = ST->getChain();
10281   SDValue Value = ST->getValue();
10282   SDValue Ptr   = ST->getBasePtr();
10283   EVT VT = Value.getValueType();
10284
10285   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10286     return SDValue();
10287
10288   unsigned Opc = Value.getOpcode();
10289
10290   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10291   // is a byte mask indicating a consecutive number of bytes, check to see if
10292   // Y is known to provide just those bytes.  If so, we try to replace the
10293   // load + replace + store sequence with a single (narrower) store, which makes
10294   // the load dead.
10295   if (Opc == ISD::OR) {
10296     std::pair<unsigned, unsigned> MaskedLoad;
10297     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10298     if (MaskedLoad.first)
10299       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10300                                                   Value.getOperand(1), ST,this))
10301         return SDValue(NewST, 0);
10302
10303     // Or is commutative, so try swapping X and Y.
10304     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10305     if (MaskedLoad.first)
10306       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10307                                                   Value.getOperand(0), ST,this))
10308         return SDValue(NewST, 0);
10309   }
10310
10311   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10312       Value.getOperand(1).getOpcode() != ISD::Constant)
10313     return SDValue();
10314
10315   SDValue N0 = Value.getOperand(0);
10316   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10317       Chain == SDValue(N0.getNode(), 1)) {
10318     LoadSDNode *LD = cast<LoadSDNode>(N0);
10319     if (LD->getBasePtr() != Ptr ||
10320         LD->getPointerInfo().getAddrSpace() !=
10321         ST->getPointerInfo().getAddrSpace())
10322       return SDValue();
10323
10324     // Find the type to narrow it the load / op / store to.
10325     SDValue N1 = Value.getOperand(1);
10326     unsigned BitWidth = N1.getValueSizeInBits();
10327     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10328     if (Opc == ISD::AND)
10329       Imm ^= APInt::getAllOnesValue(BitWidth);
10330     if (Imm == 0 || Imm.isAllOnesValue())
10331       return SDValue();
10332     unsigned ShAmt = Imm.countTrailingZeros();
10333     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10334     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10335     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10336     // The narrowing should be profitable, the load/store operation should be
10337     // legal (or custom) and the store size should be equal to the NewVT width.
10338     while (NewBW < BitWidth &&
10339            (NewVT.getStoreSizeInBits() != NewBW ||
10340             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10341             !TLI.isNarrowingProfitable(VT, NewVT))) {
10342       NewBW = NextPowerOf2(NewBW);
10343       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10344     }
10345     if (NewBW >= BitWidth)
10346       return SDValue();
10347
10348     // If the lsb changed does not start at the type bitwidth boundary,
10349     // start at the previous one.
10350     if (ShAmt % NewBW)
10351       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10352     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10353                                    std::min(BitWidth, ShAmt + NewBW));
10354     if ((Imm & Mask) == Imm) {
10355       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10356       if (Opc == ISD::AND)
10357         NewImm ^= APInt::getAllOnesValue(NewBW);
10358       uint64_t PtrOff = ShAmt / 8;
10359       // For big endian targets, we need to adjust the offset to the pointer to
10360       // load the correct bytes.
10361       if (TLI.isBigEndian())
10362         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10363
10364       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10365       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10366       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10367         return SDValue();
10368
10369       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10370                                    Ptr.getValueType(), Ptr,
10371                                    DAG.getConstant(PtrOff, SDLoc(LD),
10372                                                    Ptr.getValueType()));
10373       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10374                                   LD->getChain(), NewPtr,
10375                                   LD->getPointerInfo().getWithOffset(PtrOff),
10376                                   LD->isVolatile(), LD->isNonTemporal(),
10377                                   LD->isInvariant(), NewAlign,
10378                                   LD->getAAInfo());
10379       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10380                                    DAG.getConstant(NewImm, SDLoc(Value),
10381                                                    NewVT));
10382       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10383                                    NewVal, NewPtr,
10384                                    ST->getPointerInfo().getWithOffset(PtrOff),
10385                                    false, false, NewAlign);
10386
10387       AddToWorklist(NewPtr.getNode());
10388       AddToWorklist(NewLD.getNode());
10389       AddToWorklist(NewVal.getNode());
10390       WorklistRemover DeadNodes(*this);
10391       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10392       ++OpsNarrowed;
10393       return NewST;
10394     }
10395   }
10396
10397   return SDValue();
10398 }
10399
10400 /// For a given floating point load / store pair, if the load value isn't used
10401 /// by any other operations, then consider transforming the pair to integer
10402 /// load / store operations if the target deems the transformation profitable.
10403 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10404   StoreSDNode *ST  = cast<StoreSDNode>(N);
10405   SDValue Chain = ST->getChain();
10406   SDValue Value = ST->getValue();
10407   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10408       Value.hasOneUse() &&
10409       Chain == SDValue(Value.getNode(), 1)) {
10410     LoadSDNode *LD = cast<LoadSDNode>(Value);
10411     EVT VT = LD->getMemoryVT();
10412     if (!VT.isFloatingPoint() ||
10413         VT != ST->getMemoryVT() ||
10414         LD->isNonTemporal() ||
10415         ST->isNonTemporal() ||
10416         LD->getPointerInfo().getAddrSpace() != 0 ||
10417         ST->getPointerInfo().getAddrSpace() != 0)
10418       return SDValue();
10419
10420     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10421     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10422         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10423         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10424         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10425       return SDValue();
10426
10427     unsigned LDAlign = LD->getAlignment();
10428     unsigned STAlign = ST->getAlignment();
10429     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10430     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10431     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10432       return SDValue();
10433
10434     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10435                                 LD->getChain(), LD->getBasePtr(),
10436                                 LD->getPointerInfo(),
10437                                 false, false, false, LDAlign);
10438
10439     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10440                                  NewLD, ST->getBasePtr(),
10441                                  ST->getPointerInfo(),
10442                                  false, false, STAlign);
10443
10444     AddToWorklist(NewLD.getNode());
10445     AddToWorklist(NewST.getNode());
10446     WorklistRemover DeadNodes(*this);
10447     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10448     ++LdStFP2Int;
10449     return NewST;
10450   }
10451
10452   return SDValue();
10453 }
10454
10455 namespace {
10456 /// Helper struct to parse and store a memory address as base + index + offset.
10457 /// We ignore sign extensions when it is safe to do so.
10458 /// The following two expressions are not equivalent. To differentiate we need
10459 /// to store whether there was a sign extension involved in the index
10460 /// computation.
10461 ///  (load (i64 add (i64 copyfromreg %c)
10462 ///                 (i64 signextend (add (i8 load %index)
10463 ///                                      (i8 1))))
10464 /// vs
10465 ///
10466 /// (load (i64 add (i64 copyfromreg %c)
10467 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10468 ///                                         (i32 1)))))
10469 struct BaseIndexOffset {
10470   SDValue Base;
10471   SDValue Index;
10472   int64_t Offset;
10473   bool IsIndexSignExt;
10474
10475   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10476
10477   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10478                   bool IsIndexSignExt) :
10479     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10480
10481   bool equalBaseIndex(const BaseIndexOffset &Other) {
10482     return Other.Base == Base && Other.Index == Index &&
10483       Other.IsIndexSignExt == IsIndexSignExt;
10484   }
10485
10486   /// Parses tree in Ptr for base, index, offset addresses.
10487   static BaseIndexOffset match(SDValue Ptr) {
10488     bool IsIndexSignExt = false;
10489
10490     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10491     // instruction, then it could be just the BASE or everything else we don't
10492     // know how to handle. Just use Ptr as BASE and give up.
10493     if (Ptr->getOpcode() != ISD::ADD)
10494       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10495
10496     // We know that we have at least an ADD instruction. Try to pattern match
10497     // the simple case of BASE + OFFSET.
10498     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10499       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10500       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10501                               IsIndexSignExt);
10502     }
10503
10504     // Inside a loop the current BASE pointer is calculated using an ADD and a
10505     // MUL instruction. In this case Ptr is the actual BASE pointer.
10506     // (i64 add (i64 %array_ptr)
10507     //          (i64 mul (i64 %induction_var)
10508     //                   (i64 %element_size)))
10509     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10510       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10511
10512     // Look at Base + Index + Offset cases.
10513     SDValue Base = Ptr->getOperand(0);
10514     SDValue IndexOffset = Ptr->getOperand(1);
10515
10516     // Skip signextends.
10517     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10518       IndexOffset = IndexOffset->getOperand(0);
10519       IsIndexSignExt = true;
10520     }
10521
10522     // Either the case of Base + Index (no offset) or something else.
10523     if (IndexOffset->getOpcode() != ISD::ADD)
10524       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10525
10526     // Now we have the case of Base + Index + offset.
10527     SDValue Index = IndexOffset->getOperand(0);
10528     SDValue Offset = IndexOffset->getOperand(1);
10529
10530     if (!isa<ConstantSDNode>(Offset))
10531       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10532
10533     // Ignore signextends.
10534     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10535       Index = Index->getOperand(0);
10536       IsIndexSignExt = true;
10537     } else IsIndexSignExt = false;
10538
10539     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10540     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10541   }
10542 };
10543 } // namespace
10544
10545 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10546                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10547                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10548   // Make sure we have something to merge.
10549   if (NumElem < 2)
10550     return false;
10551
10552   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10553   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10554   unsigned LatestNodeUsed = 0;
10555
10556   for (unsigned i=0; i < NumElem; ++i) {
10557     // Find a chain for the new wide-store operand. Notice that some
10558     // of the store nodes that we found may not be selected for inclusion
10559     // in the wide store. The chain we use needs to be the chain of the
10560     // latest store node which is *used* and replaced by the wide store.
10561     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10562       LatestNodeUsed = i;
10563   }
10564
10565   // The latest Node in the DAG.
10566   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10567   SDLoc DL(StoreNodes[0].MemNode);
10568
10569   SDValue StoredVal;
10570   if (UseVector) {
10571     // Find a legal type for the vector store.
10572     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10573     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10574     if (IsConstantSrc) {
10575       // A vector store with a constant source implies that the constant is
10576       // zero; we only handle merging stores of constant zeros because the zero
10577       // can be materialized without a load.
10578       // It may be beneficial to loosen this restriction to allow non-zero
10579       // store merging.
10580       StoredVal = DAG.getConstant(0, DL, Ty);
10581     } else {
10582       SmallVector<SDValue, 8> Ops;
10583       for (unsigned i = 0; i < NumElem ; ++i) {
10584         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10585         SDValue Val = St->getValue();
10586         // All of the operands of a BUILD_VECTOR must have the same type.
10587         if (Val.getValueType() != MemVT)
10588           return false;
10589         Ops.push_back(Val);
10590       }
10591
10592       // Build the extracted vector elements back into a vector.
10593       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10594     }
10595   } else {
10596     // We should always use a vector store when merging extracted vector
10597     // elements, so this path implies a store of constants.
10598     assert(IsConstantSrc && "Merged vector elements should use vector store");
10599
10600     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10601     APInt StoreInt(StoreBW, 0);
10602
10603     // Construct a single integer constant which is made of the smaller
10604     // constant inputs.
10605     bool IsLE = TLI.isLittleEndian();
10606     for (unsigned i = 0; i < NumElem ; ++i) {
10607       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10608       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10609       SDValue Val = St->getValue();
10610       StoreInt <<= ElementSizeBytes*8;
10611       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10612         StoreInt |= C->getAPIntValue().zext(StoreBW);
10613       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10614         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10615       } else {
10616         llvm_unreachable("Invalid constant element type");
10617       }
10618     }
10619
10620     // Create the new Load and Store operations.
10621     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10622     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10623   }
10624
10625   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10626                                   FirstInChain->getBasePtr(),
10627                                   FirstInChain->getPointerInfo(),
10628                                   false, false,
10629                                   FirstInChain->getAlignment());
10630
10631   // Replace the last store with the new store
10632   CombineTo(LatestOp, NewStore);
10633   // Erase all other stores.
10634   for (unsigned i = 0; i < NumElem ; ++i) {
10635     if (StoreNodes[i].MemNode == LatestOp)
10636       continue;
10637     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10638     // ReplaceAllUsesWith will replace all uses that existed when it was
10639     // called, but graph optimizations may cause new ones to appear. For
10640     // example, the case in pr14333 looks like
10641     //
10642     //  St's chain -> St -> another store -> X
10643     //
10644     // And the only difference from St to the other store is the chain.
10645     // When we change it's chain to be St's chain they become identical,
10646     // get CSEed and the net result is that X is now a use of St.
10647     // Since we know that St is redundant, just iterate.
10648     while (!St->use_empty())
10649       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10650     deleteAndRecombine(St);
10651   }
10652
10653   return true;
10654 }
10655
10656 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10657   if (OptLevel == CodeGenOpt::None)
10658     return false;
10659
10660   EVT MemVT = St->getMemoryVT();
10661   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10662   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10663       Attribute::NoImplicitFloat);
10664
10665   // Don't merge vectors into wider inputs.
10666   if (MemVT.isVector() || !MemVT.isSimple())
10667     return false;
10668
10669   // Perform an early exit check. Do not bother looking at stored values that
10670   // are not constants, loads, or extracted vector elements.
10671   SDValue StoredVal = St->getValue();
10672   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10673   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10674                        isa<ConstantFPSDNode>(StoredVal);
10675   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10676
10677   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10678     return false;
10679
10680   // Only look at ends of store sequences.
10681   SDValue Chain = SDValue(St, 0);
10682   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10683     return false;
10684
10685   // This holds the base pointer, index, and the offset in bytes from the base
10686   // pointer.
10687   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10688
10689   // We must have a base and an offset.
10690   if (!BasePtr.Base.getNode())
10691     return false;
10692
10693   // Do not handle stores to undef base pointers.
10694   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10695     return false;
10696
10697   // Save the LoadSDNodes that we find in the chain.
10698   // We need to make sure that these nodes do not interfere with
10699   // any of the store nodes.
10700   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10701
10702   // Save the StoreSDNodes that we find in the chain.
10703   SmallVector<MemOpLink, 8> StoreNodes;
10704
10705   // Walk up the chain and look for nodes with offsets from the same
10706   // base pointer. Stop when reaching an instruction with a different kind
10707   // or instruction which has a different base pointer.
10708   unsigned Seq = 0;
10709   StoreSDNode *Index = St;
10710   while (Index) {
10711     // If the chain has more than one use, then we can't reorder the mem ops.
10712     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10713       break;
10714
10715     // Find the base pointer and offset for this memory node.
10716     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10717
10718     // Check that the base pointer is the same as the original one.
10719     if (!Ptr.equalBaseIndex(BasePtr))
10720       break;
10721
10722     // Check that the alignment is the same.
10723     if (Index->getAlignment() != St->getAlignment())
10724       break;
10725
10726     // The memory operands must not be volatile.
10727     if (Index->isVolatile() || Index->isIndexed())
10728       break;
10729
10730     // No truncation.
10731     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10732       if (St->isTruncatingStore())
10733         break;
10734
10735     // The stored memory type must be the same.
10736     if (Index->getMemoryVT() != MemVT)
10737       break;
10738
10739     // We do not allow unaligned stores because we want to prevent overriding
10740     // stores.
10741     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10742       break;
10743
10744     // We found a potential memory operand to merge.
10745     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10746
10747     // Find the next memory operand in the chain. If the next operand in the
10748     // chain is a store then move up and continue the scan with the next
10749     // memory operand. If the next operand is a load save it and use alias
10750     // information to check if it interferes with anything.
10751     SDNode *NextInChain = Index->getChain().getNode();
10752     while (1) {
10753       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10754         // We found a store node. Use it for the next iteration.
10755         Index = STn;
10756         break;
10757       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10758         if (Ldn->isVolatile()) {
10759           Index = nullptr;
10760           break;
10761         }
10762
10763         // Save the load node for later. Continue the scan.
10764         AliasLoadNodes.push_back(Ldn);
10765         NextInChain = Ldn->getChain().getNode();
10766         continue;
10767       } else {
10768         Index = nullptr;
10769         break;
10770       }
10771     }
10772   }
10773
10774   // Check if there is anything to merge.
10775   if (StoreNodes.size() < 2)
10776     return false;
10777
10778   // Sort the memory operands according to their distance from the base pointer.
10779   std::sort(StoreNodes.begin(), StoreNodes.end(),
10780             [](MemOpLink LHS, MemOpLink RHS) {
10781     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10782            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10783             LHS.SequenceNum > RHS.SequenceNum);
10784   });
10785
10786   // Scan the memory operations on the chain and find the first non-consecutive
10787   // store memory address.
10788   unsigned LastConsecutiveStore = 0;
10789   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10790   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10791
10792     // Check that the addresses are consecutive starting from the second
10793     // element in the list of stores.
10794     if (i > 0) {
10795       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10796       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10797         break;
10798     }
10799
10800     bool Alias = false;
10801     // Check if this store interferes with any of the loads that we found.
10802     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10803       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10804         Alias = true;
10805         break;
10806       }
10807     // We found a load that alias with this store. Stop the sequence.
10808     if (Alias)
10809       break;
10810
10811     // Mark this node as useful.
10812     LastConsecutiveStore = i;
10813   }
10814
10815   // The node with the lowest store address.
10816   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10817
10818   // Store the constants into memory as one consecutive store.
10819   if (IsConstantSrc) {
10820     unsigned LastLegalType = 0;
10821     unsigned LastLegalVectorType = 0;
10822     bool NonZero = false;
10823     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10824       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10825       SDValue StoredVal = St->getValue();
10826
10827       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10828         NonZero |= !C->isNullValue();
10829       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10830         NonZero |= !C->getConstantFPValue()->isNullValue();
10831       } else {
10832         // Non-constant.
10833         break;
10834       }
10835
10836       // Find a legal type for the constant store.
10837       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10838       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10839       if (TLI.isTypeLegal(StoreTy))
10840         LastLegalType = i+1;
10841       // Or check whether a truncstore is legal.
10842       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10843                TargetLowering::TypePromoteInteger) {
10844         EVT LegalizedStoredValueTy =
10845           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10846         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10847           LastLegalType = i+1;
10848       }
10849
10850       // Find a legal type for the vector store.
10851       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10852       if (TLI.isTypeLegal(Ty))
10853         LastLegalVectorType = i + 1;
10854     }
10855
10856     // We only use vectors if the constant is known to be zero and the
10857     // function is not marked with the noimplicitfloat attribute.
10858     if (NonZero || NoVectors)
10859       LastLegalVectorType = 0;
10860
10861     // Check if we found a legal integer type to store.
10862     if (LastLegalType == 0 && LastLegalVectorType == 0)
10863       return false;
10864
10865     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10866     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10867
10868     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10869                                            true, UseVector);
10870   }
10871
10872   // When extracting multiple vector elements, try to store them
10873   // in one vector store rather than a sequence of scalar stores.
10874   if (IsExtractVecEltSrc) {
10875     unsigned NumElem = 0;
10876     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10877       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10878       SDValue StoredVal = St->getValue();
10879       // This restriction could be loosened.
10880       // Bail out if any stored values are not elements extracted from a vector.
10881       // It should be possible to handle mixed sources, but load sources need
10882       // more careful handling (see the block of code below that handles
10883       // consecutive loads).
10884       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10885         return false;
10886
10887       // Find a legal type for the vector store.
10888       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10889       if (TLI.isTypeLegal(Ty))
10890         NumElem = i + 1;
10891     }
10892
10893     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10894                                            false, true);
10895   }
10896
10897   // Below we handle the case of multiple consecutive stores that
10898   // come from multiple consecutive loads. We merge them into a single
10899   // wide load and a single wide store.
10900
10901   // Look for load nodes which are used by the stored values.
10902   SmallVector<MemOpLink, 8> LoadNodes;
10903
10904   // Find acceptable loads. Loads need to have the same chain (token factor),
10905   // must not be zext, volatile, indexed, and they must be consecutive.
10906   BaseIndexOffset LdBasePtr;
10907   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10908     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10909     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10910     if (!Ld) break;
10911
10912     // Loads must only have one use.
10913     if (!Ld->hasNUsesOfValue(1, 0))
10914       break;
10915
10916     // Check that the alignment is the same as the stores.
10917     if (Ld->getAlignment() != St->getAlignment())
10918       break;
10919
10920     // The memory operands must not be volatile.
10921     if (Ld->isVolatile() || Ld->isIndexed())
10922       break;
10923
10924     // We do not accept ext loads.
10925     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10926       break;
10927
10928     // The stored memory type must be the same.
10929     if (Ld->getMemoryVT() != MemVT)
10930       break;
10931
10932     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10933     // If this is not the first ptr that we check.
10934     if (LdBasePtr.Base.getNode()) {
10935       // The base ptr must be the same.
10936       if (!LdPtr.equalBaseIndex(LdBasePtr))
10937         break;
10938     } else {
10939       // Check that all other base pointers are the same as this one.
10940       LdBasePtr = LdPtr;
10941     }
10942
10943     // We found a potential memory operand to merge.
10944     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10945   }
10946
10947   if (LoadNodes.size() < 2)
10948     return false;
10949
10950   // If we have load/store pair instructions and we only have two values,
10951   // don't bother.
10952   unsigned RequiredAlignment;
10953   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10954       St->getAlignment() >= RequiredAlignment)
10955     return false;
10956
10957   // Scan the memory operations on the chain and find the first non-consecutive
10958   // load memory address. These variables hold the index in the store node
10959   // array.
10960   unsigned LastConsecutiveLoad = 0;
10961   // This variable refers to the size and not index in the array.
10962   unsigned LastLegalVectorType = 0;
10963   unsigned LastLegalIntegerType = 0;
10964   StartAddress = LoadNodes[0].OffsetFromBase;
10965   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10966   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10967     // All loads much share the same chain.
10968     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10969       break;
10970
10971     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10972     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10973       break;
10974     LastConsecutiveLoad = i;
10975
10976     // Find a legal type for the vector store.
10977     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10978     if (TLI.isTypeLegal(StoreTy))
10979       LastLegalVectorType = i + 1;
10980
10981     // Find a legal type for the integer store.
10982     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10983     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10984     if (TLI.isTypeLegal(StoreTy))
10985       LastLegalIntegerType = i + 1;
10986     // Or check whether a truncstore and extload is legal.
10987     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10988              TargetLowering::TypePromoteInteger) {
10989       EVT LegalizedStoredValueTy =
10990         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10991       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10992           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10993           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10994           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10995         LastLegalIntegerType = i+1;
10996     }
10997   }
10998
10999   // Only use vector types if the vector type is larger than the integer type.
11000   // If they are the same, use integers.
11001   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
11002   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
11003
11004   // We add +1 here because the LastXXX variables refer to location while
11005   // the NumElem refers to array/index size.
11006   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
11007   NumElem = std::min(LastLegalType, NumElem);
11008
11009   if (NumElem < 2)
11010     return false;
11011
11012   // The latest Node in the DAG.
11013   unsigned LatestNodeUsed = 0;
11014   for (unsigned i=1; i<NumElem; ++i) {
11015     // Find a chain for the new wide-store operand. Notice that some
11016     // of the store nodes that we found may not be selected for inclusion
11017     // in the wide store. The chain we use needs to be the chain of the
11018     // latest store node which is *used* and replaced by the wide store.
11019     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
11020       LatestNodeUsed = i;
11021   }
11022
11023   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
11024
11025   // Find if it is better to use vectors or integers to load and store
11026   // to memory.
11027   EVT JointMemOpVT;
11028   if (UseVectorTy) {
11029     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
11030   } else {
11031     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
11032     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
11033   }
11034
11035   SDLoc LoadDL(LoadNodes[0].MemNode);
11036   SDLoc StoreDL(StoreNodes[0].MemNode);
11037
11038   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
11039   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
11040                                 FirstLoad->getChain(),
11041                                 FirstLoad->getBasePtr(),
11042                                 FirstLoad->getPointerInfo(),
11043                                 false, false, false,
11044                                 FirstLoad->getAlignment());
11045
11046   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
11047                                   FirstInChain->getBasePtr(),
11048                                   FirstInChain->getPointerInfo(), false, false,
11049                                   FirstInChain->getAlignment());
11050
11051   // Replace one of the loads with the new load.
11052   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
11053   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
11054                                 SDValue(NewLoad.getNode(), 1));
11055
11056   // Remove the rest of the load chains.
11057   for (unsigned i = 1; i < NumElem ; ++i) {
11058     // Replace all chain users of the old load nodes with the chain of the new
11059     // load node.
11060     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
11061     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
11062   }
11063
11064   // Replace the last store with the new store.
11065   CombineTo(LatestOp, NewStore);
11066   // Erase all other stores.
11067   for (unsigned i = 0; i < NumElem ; ++i) {
11068     // Remove all Store nodes.
11069     if (StoreNodes[i].MemNode == LatestOp)
11070       continue;
11071     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
11072     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
11073     deleteAndRecombine(St);
11074   }
11075
11076   return true;
11077 }
11078
11079 SDValue DAGCombiner::visitSTORE(SDNode *N) {
11080   StoreSDNode *ST  = cast<StoreSDNode>(N);
11081   SDValue Chain = ST->getChain();
11082   SDValue Value = ST->getValue();
11083   SDValue Ptr   = ST->getBasePtr();
11084
11085   // If this is a store of a bit convert, store the input value if the
11086   // resultant store does not need a higher alignment than the original.
11087   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
11088       ST->isUnindexed()) {
11089     unsigned OrigAlign = ST->getAlignment();
11090     EVT SVT = Value.getOperand(0).getValueType();
11091     unsigned Align = TLI.getDataLayout()->
11092       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
11093     if (Align <= OrigAlign &&
11094         ((!LegalOperations && !ST->isVolatile()) ||
11095          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
11096       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
11097                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
11098                           ST->isNonTemporal(), OrigAlign,
11099                           ST->getAAInfo());
11100   }
11101
11102   // Turn 'store undef, Ptr' -> nothing.
11103   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
11104     return Chain;
11105
11106   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
11107   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
11108     // NOTE: If the original store is volatile, this transform must not increase
11109     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11110     // processor operation but an i64 (which is not legal) requires two.  So the
11111     // transform should not be done in this case.
11112     if (Value.getOpcode() != ISD::TargetConstantFP) {
11113       SDValue Tmp;
11114       switch (CFP->getSimpleValueType(0).SimpleTy) {
11115       default: llvm_unreachable("Unknown FP type");
11116       case MVT::f16:    // We don't do this for these yet.
11117       case MVT::f80:
11118       case MVT::f128:
11119       case MVT::ppcf128:
11120         break;
11121       case MVT::f32:
11122         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11123             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11124           ;
11125           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11126                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11127                               MVT::i32);
11128           return DAG.getStore(Chain, SDLoc(N), Tmp,
11129                               Ptr, ST->getMemOperand());
11130         }
11131         break;
11132       case MVT::f64:
11133         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11134              !ST->isVolatile()) ||
11135             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11136           ;
11137           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11138                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11139           return DAG.getStore(Chain, SDLoc(N), Tmp,
11140                               Ptr, ST->getMemOperand());
11141         }
11142
11143         if (!ST->isVolatile() &&
11144             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11145           // Many FP stores are not made apparent until after legalize, e.g. for
11146           // argument passing.  Since this is so common, custom legalize the
11147           // 64-bit integer store into two 32-bit stores.
11148           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11149           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11150           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11151           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11152
11153           unsigned Alignment = ST->getAlignment();
11154           bool isVolatile = ST->isVolatile();
11155           bool isNonTemporal = ST->isNonTemporal();
11156           AAMDNodes AAInfo = ST->getAAInfo();
11157
11158           SDLoc DL(N);
11159
11160           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11161                                      Ptr, ST->getPointerInfo(),
11162                                      isVolatile, isNonTemporal,
11163                                      ST->getAlignment(), AAInfo);
11164           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11165                             DAG.getConstant(4, DL, Ptr.getValueType()));
11166           Alignment = MinAlign(Alignment, 4U);
11167           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11168                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11169                                      isVolatile, isNonTemporal,
11170                                      Alignment, AAInfo);
11171           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11172                              St0, St1);
11173         }
11174
11175         break;
11176       }
11177     }
11178   }
11179
11180   // Try to infer better alignment information than the store already has.
11181   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11182     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11183       if (Align > ST->getAlignment()) {
11184         SDValue NewStore =
11185                DAG.getTruncStore(Chain, SDLoc(N), Value,
11186                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11187                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11188                                  ST->getAAInfo());
11189         if (NewStore.getNode() != N)
11190           return CombineTo(ST, NewStore, true);
11191       }
11192     }
11193   }
11194
11195   // Try transforming a pair floating point load / store ops to integer
11196   // load / store ops.
11197   SDValue NewST = TransformFPLoadStorePair(N);
11198   if (NewST.getNode())
11199     return NewST;
11200
11201   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11202                                                   : DAG.getSubtarget().useAA();
11203 #ifndef NDEBUG
11204   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11205       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11206     UseAA = false;
11207 #endif
11208   if (UseAA && ST->isUnindexed()) {
11209     // Walk up chain skipping non-aliasing memory nodes.
11210     SDValue BetterChain = FindBetterChain(N, Chain);
11211
11212     // If there is a better chain.
11213     if (Chain != BetterChain) {
11214       SDValue ReplStore;
11215
11216       // Replace the chain to avoid dependency.
11217       if (ST->isTruncatingStore()) {
11218         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11219                                       ST->getMemoryVT(), ST->getMemOperand());
11220       } else {
11221         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11222                                  ST->getMemOperand());
11223       }
11224
11225       // Create token to keep both nodes around.
11226       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11227                                   MVT::Other, Chain, ReplStore);
11228
11229       // Make sure the new and old chains are cleaned up.
11230       AddToWorklist(Token.getNode());
11231
11232       // Don't add users to work list.
11233       return CombineTo(N, Token, false);
11234     }
11235   }
11236
11237   // Try transforming N to an indexed store.
11238   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11239     return SDValue(N, 0);
11240
11241   // FIXME: is there such a thing as a truncating indexed store?
11242   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11243       Value.getValueType().isInteger()) {
11244     // See if we can simplify the input to this truncstore with knowledge that
11245     // only the low bits are being used.  For example:
11246     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11247     SDValue Shorter =
11248       GetDemandedBits(Value,
11249                       APInt::getLowBitsSet(
11250                         Value.getValueType().getScalarType().getSizeInBits(),
11251                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11252     AddToWorklist(Value.getNode());
11253     if (Shorter.getNode())
11254       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11255                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11256
11257     // Otherwise, see if we can simplify the operation with
11258     // SimplifyDemandedBits, which only works if the value has a single use.
11259     if (SimplifyDemandedBits(Value,
11260                         APInt::getLowBitsSet(
11261                           Value.getValueType().getScalarType().getSizeInBits(),
11262                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11263       return SDValue(N, 0);
11264   }
11265
11266   // If this is a load followed by a store to the same location, then the store
11267   // is dead/noop.
11268   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11269     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11270         ST->isUnindexed() && !ST->isVolatile() &&
11271         // There can't be any side effects between the load and store, such as
11272         // a call or store.
11273         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11274       // The store is dead, remove it.
11275       return Chain;
11276     }
11277   }
11278
11279   // If this is a store followed by a store with the same value to the same
11280   // location, then the store is dead/noop.
11281   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11282     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11283         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11284         ST1->isUnindexed() && !ST1->isVolatile()) {
11285       // The store is dead, remove it.
11286       return Chain;
11287     }
11288   }
11289
11290   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11291   // truncating store.  We can do this even if this is already a truncstore.
11292   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11293       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11294       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11295                             ST->getMemoryVT())) {
11296     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11297                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11298   }
11299
11300   // Only perform this optimization before the types are legal, because we
11301   // don't want to perform this optimization on every DAGCombine invocation.
11302   if (!LegalTypes) {
11303     bool EverChanged = false;
11304
11305     do {
11306       // There can be multiple store sequences on the same chain.
11307       // Keep trying to merge store sequences until we are unable to do so
11308       // or until we merge the last store on the chain.
11309       bool Changed = MergeConsecutiveStores(ST);
11310       EverChanged |= Changed;
11311       if (!Changed) break;
11312     } while (ST->getOpcode() != ISD::DELETED_NODE);
11313
11314     if (EverChanged)
11315       return SDValue(N, 0);
11316   }
11317
11318   return ReduceLoadOpStoreWidth(N);
11319 }
11320
11321 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11322   SDValue InVec = N->getOperand(0);
11323   SDValue InVal = N->getOperand(1);
11324   SDValue EltNo = N->getOperand(2);
11325   SDLoc dl(N);
11326
11327   // If the inserted element is an UNDEF, just use the input vector.
11328   if (InVal.getOpcode() == ISD::UNDEF)
11329     return InVec;
11330
11331   EVT VT = InVec.getValueType();
11332
11333   // If we can't generate a legal BUILD_VECTOR, exit
11334   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11335     return SDValue();
11336
11337   // Check that we know which element is being inserted
11338   if (!isa<ConstantSDNode>(EltNo))
11339     return SDValue();
11340   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11341
11342   // Canonicalize insert_vector_elt dag nodes.
11343   // Example:
11344   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11345   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11346   //
11347   // Do this only if the child insert_vector node has one use; also
11348   // do this only if indices are both constants and Idx1 < Idx0.
11349   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11350       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11351     unsigned OtherElt =
11352       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11353     if (Elt < OtherElt) {
11354       // Swap nodes.
11355       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11356                                   InVec.getOperand(0), InVal, EltNo);
11357       AddToWorklist(NewOp.getNode());
11358       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11359                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11360     }
11361   }
11362
11363   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11364   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11365   // vector elements.
11366   SmallVector<SDValue, 8> Ops;
11367   // Do not combine these two vectors if the output vector will not replace
11368   // the input vector.
11369   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11370     Ops.append(InVec.getNode()->op_begin(),
11371                InVec.getNode()->op_end());
11372   } else if (InVec.getOpcode() == ISD::UNDEF) {
11373     unsigned NElts = VT.getVectorNumElements();
11374     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11375   } else {
11376     return SDValue();
11377   }
11378
11379   // Insert the element
11380   if (Elt < Ops.size()) {
11381     // All the operands of BUILD_VECTOR must have the same type;
11382     // we enforce that here.
11383     EVT OpVT = Ops[0].getValueType();
11384     if (InVal.getValueType() != OpVT)
11385       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11386                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11387                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11388     Ops[Elt] = InVal;
11389   }
11390
11391   // Return the new vector
11392   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11393 }
11394
11395 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11396     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11397   EVT ResultVT = EVE->getValueType(0);
11398   EVT VecEltVT = InVecVT.getVectorElementType();
11399   unsigned Align = OriginalLoad->getAlignment();
11400   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11401       VecEltVT.getTypeForEVT(*DAG.getContext()));
11402
11403   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11404     return SDValue();
11405
11406   Align = NewAlign;
11407
11408   SDValue NewPtr = OriginalLoad->getBasePtr();
11409   SDValue Offset;
11410   EVT PtrType = NewPtr.getValueType();
11411   MachinePointerInfo MPI;
11412   SDLoc DL(EVE);
11413   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11414     int Elt = ConstEltNo->getZExtValue();
11415     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11416     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11417     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11418   } else {
11419     Offset = DAG.getZExtOrTrunc(EltNo, DL, PtrType);
11420     Offset = DAG.getNode(
11421         ISD::MUL, DL, PtrType, Offset,
11422         DAG.getConstant(VecEltVT.getStoreSize(), DL, PtrType));
11423     MPI = OriginalLoad->getPointerInfo();
11424   }
11425   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11426
11427   // The replacement we need to do here is a little tricky: we need to
11428   // replace an extractelement of a load with a load.
11429   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11430   // Note that this replacement assumes that the extractvalue is the only
11431   // use of the load; that's okay because we don't want to perform this
11432   // transformation in other cases anyway.
11433   SDValue Load;
11434   SDValue Chain;
11435   if (ResultVT.bitsGT(VecEltVT)) {
11436     // If the result type of vextract is wider than the load, then issue an
11437     // extending load instead.
11438     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11439                                                   VecEltVT)
11440                                    ? ISD::ZEXTLOAD
11441                                    : ISD::EXTLOAD;
11442     Load = DAG.getExtLoad(
11443         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11444         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11445         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11446     Chain = Load.getValue(1);
11447   } else {
11448     Load = DAG.getLoad(
11449         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11450         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11451         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11452     Chain = Load.getValue(1);
11453     if (ResultVT.bitsLT(VecEltVT))
11454       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11455     else
11456       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11457   }
11458   WorklistRemover DeadNodes(*this);
11459   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11460   SDValue To[] = { Load, Chain };
11461   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11462   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11463   // worklist explicitly as well.
11464   AddToWorklist(Load.getNode());
11465   AddUsersToWorklist(Load.getNode()); // Add users too
11466   // Make sure to revisit this node to clean it up; it will usually be dead.
11467   AddToWorklist(EVE);
11468   ++OpsNarrowed;
11469   return SDValue(EVE, 0);
11470 }
11471
11472 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11473   // (vextract (scalar_to_vector val, 0) -> val
11474   SDValue InVec = N->getOperand(0);
11475   EVT VT = InVec.getValueType();
11476   EVT NVT = N->getValueType(0);
11477
11478   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11479     // Check if the result type doesn't match the inserted element type. A
11480     // SCALAR_TO_VECTOR may truncate the inserted element and the
11481     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11482     SDValue InOp = InVec.getOperand(0);
11483     if (InOp.getValueType() != NVT) {
11484       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11485       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11486     }
11487     return InOp;
11488   }
11489
11490   SDValue EltNo = N->getOperand(1);
11491   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11492
11493   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11494   // We only perform this optimization before the op legalization phase because
11495   // we may introduce new vector instructions which are not backed by TD
11496   // patterns. For example on AVX, extracting elements from a wide vector
11497   // without using extract_subvector. However, if we can find an underlying
11498   // scalar value, then we can always use that.
11499   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11500       && ConstEltNo) {
11501     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11502     int NumElem = VT.getVectorNumElements();
11503     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11504     // Find the new index to extract from.
11505     int OrigElt = SVOp->getMaskElt(Elt);
11506
11507     // Extracting an undef index is undef.
11508     if (OrigElt == -1)
11509       return DAG.getUNDEF(NVT);
11510
11511     // Select the right vector half to extract from.
11512     SDValue SVInVec;
11513     if (OrigElt < NumElem) {
11514       SVInVec = InVec->getOperand(0);
11515     } else {
11516       SVInVec = InVec->getOperand(1);
11517       OrigElt -= NumElem;
11518     }
11519
11520     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11521       SDValue InOp = SVInVec.getOperand(OrigElt);
11522       if (InOp.getValueType() != NVT) {
11523         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11524         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11525       }
11526
11527       return InOp;
11528     }
11529
11530     // FIXME: We should handle recursing on other vector shuffles and
11531     // scalar_to_vector here as well.
11532
11533     if (!LegalOperations) {
11534       EVT IndexTy = TLI.getVectorIdxTy();
11535       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11536                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11537     }
11538   }
11539
11540   bool BCNumEltsChanged = false;
11541   EVT ExtVT = VT.getVectorElementType();
11542   EVT LVT = ExtVT;
11543
11544   // If the result of load has to be truncated, then it's not necessarily
11545   // profitable.
11546   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11547     return SDValue();
11548
11549   if (InVec.getOpcode() == ISD::BITCAST) {
11550     // Don't duplicate a load with other uses.
11551     if (!InVec.hasOneUse())
11552       return SDValue();
11553
11554     EVT BCVT = InVec.getOperand(0).getValueType();
11555     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11556       return SDValue();
11557     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11558       BCNumEltsChanged = true;
11559     InVec = InVec.getOperand(0);
11560     ExtVT = BCVT.getVectorElementType();
11561   }
11562
11563   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11564   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11565       ISD::isNormalLoad(InVec.getNode()) &&
11566       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11567     SDValue Index = N->getOperand(1);
11568     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11569       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11570                                                            OrigLoad);
11571   }
11572
11573   // Perform only after legalization to ensure build_vector / vector_shuffle
11574   // optimizations have already been done.
11575   if (!LegalOperations) return SDValue();
11576
11577   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11578   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11579   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11580
11581   if (ConstEltNo) {
11582     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11583
11584     LoadSDNode *LN0 = nullptr;
11585     const ShuffleVectorSDNode *SVN = nullptr;
11586     if (ISD::isNormalLoad(InVec.getNode())) {
11587       LN0 = cast<LoadSDNode>(InVec);
11588     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11589                InVec.getOperand(0).getValueType() == ExtVT &&
11590                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11591       // Don't duplicate a load with other uses.
11592       if (!InVec.hasOneUse())
11593         return SDValue();
11594
11595       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11596     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11597       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11598       // =>
11599       // (load $addr+1*size)
11600
11601       // Don't duplicate a load with other uses.
11602       if (!InVec.hasOneUse())
11603         return SDValue();
11604
11605       // If the bit convert changed the number of elements, it is unsafe
11606       // to examine the mask.
11607       if (BCNumEltsChanged)
11608         return SDValue();
11609
11610       // Select the input vector, guarding against out of range extract vector.
11611       unsigned NumElems = VT.getVectorNumElements();
11612       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11613       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11614
11615       if (InVec.getOpcode() == ISD::BITCAST) {
11616         // Don't duplicate a load with other uses.
11617         if (!InVec.hasOneUse())
11618           return SDValue();
11619
11620         InVec = InVec.getOperand(0);
11621       }
11622       if (ISD::isNormalLoad(InVec.getNode())) {
11623         LN0 = cast<LoadSDNode>(InVec);
11624         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11625         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11626       }
11627     }
11628
11629     // Make sure we found a non-volatile load and the extractelement is
11630     // the only use.
11631     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11632       return SDValue();
11633
11634     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11635     if (Elt == -1)
11636       return DAG.getUNDEF(LVT);
11637
11638     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11639   }
11640
11641   return SDValue();
11642 }
11643
11644 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11645 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11646   // We perform this optimization post type-legalization because
11647   // the type-legalizer often scalarizes integer-promoted vectors.
11648   // Performing this optimization before may create bit-casts which
11649   // will be type-legalized to complex code sequences.
11650   // We perform this optimization only before the operation legalizer because we
11651   // may introduce illegal operations.
11652   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11653     return SDValue();
11654
11655   unsigned NumInScalars = N->getNumOperands();
11656   SDLoc dl(N);
11657   EVT VT = N->getValueType(0);
11658
11659   // Check to see if this is a BUILD_VECTOR of a bunch of values
11660   // which come from any_extend or zero_extend nodes. If so, we can create
11661   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11662   // optimizations. We do not handle sign-extend because we can't fill the sign
11663   // using shuffles.
11664   EVT SourceType = MVT::Other;
11665   bool AllAnyExt = true;
11666
11667   for (unsigned i = 0; i != NumInScalars; ++i) {
11668     SDValue In = N->getOperand(i);
11669     // Ignore undef inputs.
11670     if (In.getOpcode() == ISD::UNDEF) continue;
11671
11672     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11673     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11674
11675     // Abort if the element is not an extension.
11676     if (!ZeroExt && !AnyExt) {
11677       SourceType = MVT::Other;
11678       break;
11679     }
11680
11681     // The input is a ZeroExt or AnyExt. Check the original type.
11682     EVT InTy = In.getOperand(0).getValueType();
11683
11684     // Check that all of the widened source types are the same.
11685     if (SourceType == MVT::Other)
11686       // First time.
11687       SourceType = InTy;
11688     else if (InTy != SourceType) {
11689       // Multiple income types. Abort.
11690       SourceType = MVT::Other;
11691       break;
11692     }
11693
11694     // Check if all of the extends are ANY_EXTENDs.
11695     AllAnyExt &= AnyExt;
11696   }
11697
11698   // In order to have valid types, all of the inputs must be extended from the
11699   // same source type and all of the inputs must be any or zero extend.
11700   // Scalar sizes must be a power of two.
11701   EVT OutScalarTy = VT.getScalarType();
11702   bool ValidTypes = SourceType != MVT::Other &&
11703                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11704                  isPowerOf2_32(SourceType.getSizeInBits());
11705
11706   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11707   // turn into a single shuffle instruction.
11708   if (!ValidTypes)
11709     return SDValue();
11710
11711   bool isLE = TLI.isLittleEndian();
11712   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11713   assert(ElemRatio > 1 && "Invalid element size ratio");
11714   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11715                                DAG.getConstant(0, SDLoc(N), SourceType);
11716
11717   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11718   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11719
11720   // Populate the new build_vector
11721   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11722     SDValue Cast = N->getOperand(i);
11723     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11724             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11725             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11726     SDValue In;
11727     if (Cast.getOpcode() == ISD::UNDEF)
11728       In = DAG.getUNDEF(SourceType);
11729     else
11730       In = Cast->getOperand(0);
11731     unsigned Index = isLE ? (i * ElemRatio) :
11732                             (i * ElemRatio + (ElemRatio - 1));
11733
11734     assert(Index < Ops.size() && "Invalid index");
11735     Ops[Index] = In;
11736   }
11737
11738   // The type of the new BUILD_VECTOR node.
11739   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11740   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11741          "Invalid vector size");
11742   // Check if the new vector type is legal.
11743   if (!isTypeLegal(VecVT)) return SDValue();
11744
11745   // Make the new BUILD_VECTOR.
11746   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11747
11748   // The new BUILD_VECTOR node has the potential to be further optimized.
11749   AddToWorklist(BV.getNode());
11750   // Bitcast to the desired type.
11751   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11752 }
11753
11754 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11755   EVT VT = N->getValueType(0);
11756
11757   unsigned NumInScalars = N->getNumOperands();
11758   SDLoc dl(N);
11759
11760   EVT SrcVT = MVT::Other;
11761   unsigned Opcode = ISD::DELETED_NODE;
11762   unsigned NumDefs = 0;
11763
11764   for (unsigned i = 0; i != NumInScalars; ++i) {
11765     SDValue In = N->getOperand(i);
11766     unsigned Opc = In.getOpcode();
11767
11768     if (Opc == ISD::UNDEF)
11769       continue;
11770
11771     // If all scalar values are floats and converted from integers.
11772     if (Opcode == ISD::DELETED_NODE &&
11773         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11774       Opcode = Opc;
11775     }
11776
11777     if (Opc != Opcode)
11778       return SDValue();
11779
11780     EVT InVT = In.getOperand(0).getValueType();
11781
11782     // If all scalar values are typed differently, bail out. It's chosen to
11783     // simplify BUILD_VECTOR of integer types.
11784     if (SrcVT == MVT::Other)
11785       SrcVT = InVT;
11786     if (SrcVT != InVT)
11787       return SDValue();
11788     NumDefs++;
11789   }
11790
11791   // If the vector has just one element defined, it's not worth to fold it into
11792   // a vectorized one.
11793   if (NumDefs < 2)
11794     return SDValue();
11795
11796   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11797          && "Should only handle conversion from integer to float.");
11798   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11799
11800   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11801
11802   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11803     return SDValue();
11804
11805   // Just because the floating-point vector type is legal does not necessarily
11806   // mean that the corresponding integer vector type is.
11807   if (!isTypeLegal(NVT))
11808     return SDValue();
11809
11810   SmallVector<SDValue, 8> Opnds;
11811   for (unsigned i = 0; i != NumInScalars; ++i) {
11812     SDValue In = N->getOperand(i);
11813
11814     if (In.getOpcode() == ISD::UNDEF)
11815       Opnds.push_back(DAG.getUNDEF(SrcVT));
11816     else
11817       Opnds.push_back(In.getOperand(0));
11818   }
11819   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11820   AddToWorklist(BV.getNode());
11821
11822   return DAG.getNode(Opcode, dl, VT, BV);
11823 }
11824
11825 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11826   unsigned NumInScalars = N->getNumOperands();
11827   SDLoc dl(N);
11828   EVT VT = N->getValueType(0);
11829
11830   // A vector built entirely of undefs is undef.
11831   if (ISD::allOperandsUndef(N))
11832     return DAG.getUNDEF(VT);
11833
11834   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11835     return V;
11836
11837   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11838     return V;
11839
11840   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11841   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11842   // at most two distinct vectors, turn this into a shuffle node.
11843
11844   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11845   if (!isTypeLegal(VT))
11846     return SDValue();
11847
11848   // May only combine to shuffle after legalize if shuffle is legal.
11849   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11850     return SDValue();
11851
11852   SDValue VecIn1, VecIn2;
11853   bool UsesZeroVector = false;
11854   for (unsigned i = 0; i != NumInScalars; ++i) {
11855     SDValue Op = N->getOperand(i);
11856     // Ignore undef inputs.
11857     if (Op.getOpcode() == ISD::UNDEF) continue;
11858
11859     // See if we can combine this build_vector into a blend with a zero vector.
11860     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11861         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11862         (Op.getOpcode() == ISD::ConstantFP &&
11863         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11864       UsesZeroVector = true;
11865       continue;
11866     }
11867
11868     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11869     // constant index, bail out.
11870     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11871         !isa<ConstantSDNode>(Op.getOperand(1))) {
11872       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11873       break;
11874     }
11875
11876     // We allow up to two distinct input vectors.
11877     SDValue ExtractedFromVec = Op.getOperand(0);
11878     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11879       continue;
11880
11881     if (!VecIn1.getNode()) {
11882       VecIn1 = ExtractedFromVec;
11883     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11884       VecIn2 = ExtractedFromVec;
11885     } else {
11886       // Too many inputs.
11887       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11888       break;
11889     }
11890   }
11891
11892   // If everything is good, we can make a shuffle operation.
11893   if (VecIn1.getNode()) {
11894     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11895     SmallVector<int, 8> Mask;
11896     for (unsigned i = 0; i != NumInScalars; ++i) {
11897       unsigned Opcode = N->getOperand(i).getOpcode();
11898       if (Opcode == ISD::UNDEF) {
11899         Mask.push_back(-1);
11900         continue;
11901       }
11902
11903       // Operands can also be zero.
11904       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11905         assert(UsesZeroVector &&
11906                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11907                "Unexpected node found!");
11908         Mask.push_back(NumInScalars+i);
11909         continue;
11910       }
11911
11912       // If extracting from the first vector, just use the index directly.
11913       SDValue Extract = N->getOperand(i);
11914       SDValue ExtVal = Extract.getOperand(1);
11915       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11916       if (Extract.getOperand(0) == VecIn1) {
11917         Mask.push_back(ExtIndex);
11918         continue;
11919       }
11920
11921       // Otherwise, use InIdx + InputVecSize
11922       Mask.push_back(InNumElements + ExtIndex);
11923     }
11924
11925     // Avoid introducing illegal shuffles with zero.
11926     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11927       return SDValue();
11928
11929     // We can't generate a shuffle node with mismatched input and output types.
11930     // Attempt to transform a single input vector to the correct type.
11931     if ((VT != VecIn1.getValueType())) {
11932       // If the input vector type has a different base type to the output
11933       // vector type, bail out.
11934       EVT VTElemType = VT.getVectorElementType();
11935       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11936           (VecIn2.getNode() &&
11937            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11938         return SDValue();
11939
11940       // If the input vector is too small, widen it.
11941       // We only support widening of vectors which are half the size of the
11942       // output registers. For example XMM->YMM widening on X86 with AVX.
11943       EVT VecInT = VecIn1.getValueType();
11944       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11945         // If we only have one small input, widen it by adding undef values.
11946         if (!VecIn2.getNode())
11947           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11948                                DAG.getUNDEF(VecIn1.getValueType()));
11949         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11950           // If we have two small inputs of the same type, try to concat them.
11951           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11952           VecIn2 = SDValue(nullptr, 0);
11953         } else
11954           return SDValue();
11955       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11956         // If the input vector is too large, try to split it.
11957         // We don't support having two input vectors that are too large.
11958         // If the zero vector was used, we can not split the vector,
11959         // since we'd need 3 inputs.
11960         if (UsesZeroVector || VecIn2.getNode())
11961           return SDValue();
11962
11963         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11964           return SDValue();
11965
11966         // Try to replace VecIn1 with two extract_subvectors
11967         // No need to update the masks, they should still be correct.
11968         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11969           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11970         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11971           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11972       } else
11973         return SDValue();
11974     }
11975
11976     if (UsesZeroVector)
11977       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11978                                 DAG.getConstantFP(0.0, dl, VT);
11979     else
11980       // If VecIn2 is unused then change it to undef.
11981       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11982
11983     // Check that we were able to transform all incoming values to the same
11984     // type.
11985     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11986         VecIn1.getValueType() != VT)
11987           return SDValue();
11988
11989     // Return the new VECTOR_SHUFFLE node.
11990     SDValue Ops[2];
11991     Ops[0] = VecIn1;
11992     Ops[1] = VecIn2;
11993     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11994   }
11995
11996   return SDValue();
11997 }
11998
11999 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
12000   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12001   EVT OpVT = N->getOperand(0).getValueType();
12002
12003   // If the operands are legal vectors, leave them alone.
12004   if (TLI.isTypeLegal(OpVT))
12005     return SDValue();
12006
12007   SDLoc DL(N);
12008   EVT VT = N->getValueType(0);
12009   SmallVector<SDValue, 8> Ops;
12010
12011   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
12012   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12013
12014   // Keep track of what we encounter.
12015   bool AnyInteger = false;
12016   bool AnyFP = false;
12017   for (const SDValue &Op : N->ops()) {
12018     if (ISD::BITCAST == Op.getOpcode() &&
12019         !Op.getOperand(0).getValueType().isVector())
12020       Ops.push_back(Op.getOperand(0));
12021     else if (ISD::UNDEF == Op.getOpcode())
12022       Ops.push_back(ScalarUndef);
12023     else
12024       return SDValue();
12025
12026     // Note whether we encounter an integer or floating point scalar.
12027     // If it's neither, bail out, it could be something weird like x86mmx.
12028     EVT LastOpVT = Ops.back().getValueType();
12029     if (LastOpVT.isFloatingPoint())
12030       AnyFP = true;
12031     else if (LastOpVT.isInteger())
12032       AnyInteger = true;
12033     else
12034       return SDValue();
12035   }
12036
12037   // If any of the operands is a floating point scalar bitcast to a vector,
12038   // use floating point types throughout, and bitcast everything.  
12039   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
12040   if (AnyFP) {
12041     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
12042     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
12043     if (AnyInteger) {
12044       for (SDValue &Op : Ops) {
12045         if (Op.getValueType() == SVT)
12046           continue;
12047         if (Op.getOpcode() == ISD::UNDEF)
12048           Op = ScalarUndef;
12049         else
12050           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
12051       }
12052     }
12053   }
12054
12055   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
12056                                VT.getSizeInBits() / SVT.getSizeInBits());
12057   return DAG.getNode(ISD::BITCAST, DL, VT,
12058                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
12059 }
12060
12061 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
12062   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
12063   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
12064   // inputs come from at most two distinct vectors, turn this into a shuffle
12065   // node.
12066
12067   // If we only have one input vector, we don't need to do any concatenation.
12068   if (N->getNumOperands() == 1)
12069     return N->getOperand(0);
12070
12071   // Check if all of the operands are undefs.
12072   EVT VT = N->getValueType(0);
12073   if (ISD::allOperandsUndef(N))
12074     return DAG.getUNDEF(VT);
12075
12076   // Optimize concat_vectors where all but the first of the vectors are undef.
12077   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
12078         return Op.getOpcode() == ISD::UNDEF;
12079       })) {
12080     SDValue In = N->getOperand(0);
12081     assert(In.getValueType().isVector() && "Must concat vectors");
12082
12083     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
12084     if (In->getOpcode() == ISD::BITCAST &&
12085         !In->getOperand(0)->getValueType(0).isVector()) {
12086       SDValue Scalar = In->getOperand(0);
12087
12088       // If the bitcast type isn't legal, it might be a trunc of a legal type;
12089       // look through the trunc so we can still do the transform:
12090       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
12091       if (Scalar->getOpcode() == ISD::TRUNCATE &&
12092           !TLI.isTypeLegal(Scalar.getValueType()) &&
12093           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
12094         Scalar = Scalar->getOperand(0);
12095
12096       EVT SclTy = Scalar->getValueType(0);
12097
12098       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
12099         return SDValue();
12100
12101       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
12102                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12103       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12104         return SDValue();
12105
12106       SDLoc dl = SDLoc(N);
12107       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12108       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12109     }
12110   }
12111
12112   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12113   // We have already tested above for an UNDEF only concatenation.
12114   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12115   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12116   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12117     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12118   };
12119   bool AllBuildVectorsOrUndefs =
12120       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12121   if (AllBuildVectorsOrUndefs) {
12122     SmallVector<SDValue, 8> Opnds;
12123     EVT SVT = VT.getScalarType();
12124
12125     EVT MinVT = SVT;
12126     if (!SVT.isFloatingPoint()) {
12127       // If BUILD_VECTOR are from built from integer, they may have different
12128       // operand types. Get the smallest type and truncate all operands to it.
12129       bool FoundMinVT = false;
12130       for (const SDValue &Op : N->ops())
12131         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12132           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12133           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12134           FoundMinVT = true;
12135         }
12136       assert(FoundMinVT && "Concat vector type mismatch");
12137     }
12138
12139     for (const SDValue &Op : N->ops()) {
12140       EVT OpVT = Op.getValueType();
12141       unsigned NumElts = OpVT.getVectorNumElements();
12142
12143       if (ISD::UNDEF == Op.getOpcode())
12144         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12145
12146       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12147         if (SVT.isFloatingPoint()) {
12148           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12149           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12150         } else {
12151           for (unsigned i = 0; i != NumElts; ++i)
12152             Opnds.push_back(
12153                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12154         }
12155       }
12156     }
12157
12158     assert(VT.getVectorNumElements() == Opnds.size() &&
12159            "Concat vector type mismatch");
12160     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12161   }
12162
12163   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12164   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12165     return V;
12166
12167   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12168   // nodes often generate nop CONCAT_VECTOR nodes.
12169   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12170   // place the incoming vectors at the exact same location.
12171   SDValue SingleSource = SDValue();
12172   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12173
12174   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12175     SDValue Op = N->getOperand(i);
12176
12177     if (Op.getOpcode() == ISD::UNDEF)
12178       continue;
12179
12180     // Check if this is the identity extract:
12181     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12182       return SDValue();
12183
12184     // Find the single incoming vector for the extract_subvector.
12185     if (SingleSource.getNode()) {
12186       if (Op.getOperand(0) != SingleSource)
12187         return SDValue();
12188     } else {
12189       SingleSource = Op.getOperand(0);
12190
12191       // Check the source type is the same as the type of the result.
12192       // If not, this concat may extend the vector, so we can not
12193       // optimize it away.
12194       if (SingleSource.getValueType() != N->getValueType(0))
12195         return SDValue();
12196     }
12197
12198     unsigned IdentityIndex = i * PartNumElem;
12199     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12200     // The extract index must be constant.
12201     if (!CS)
12202       return SDValue();
12203
12204     // Check that we are reading from the identity index.
12205     if (CS->getZExtValue() != IdentityIndex)
12206       return SDValue();
12207   }
12208
12209   if (SingleSource.getNode())
12210     return SingleSource;
12211
12212   return SDValue();
12213 }
12214
12215 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12216   EVT NVT = N->getValueType(0);
12217   SDValue V = N->getOperand(0);
12218
12219   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12220     // Combine:
12221     //    (extract_subvec (concat V1, V2, ...), i)
12222     // Into:
12223     //    Vi if possible
12224     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12225     // type.
12226     if (V->getOperand(0).getValueType() != NVT)
12227       return SDValue();
12228     unsigned Idx = N->getConstantOperandVal(1);
12229     unsigned NumElems = NVT.getVectorNumElements();
12230     assert((Idx % NumElems) == 0 &&
12231            "IDX in concat is not a multiple of the result vector length.");
12232     return V->getOperand(Idx / NumElems);
12233   }
12234
12235   // Skip bitcasting
12236   if (V->getOpcode() == ISD::BITCAST)
12237     V = V.getOperand(0);
12238
12239   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12240     SDLoc dl(N);
12241     // Handle only simple case where vector being inserted and vector
12242     // being extracted are of same type, and are half size of larger vectors.
12243     EVT BigVT = V->getOperand(0).getValueType();
12244     EVT SmallVT = V->getOperand(1).getValueType();
12245     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12246       return SDValue();
12247
12248     // Only handle cases where both indexes are constants with the same type.
12249     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12250     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12251
12252     if (InsIdx && ExtIdx &&
12253         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12254         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12255       // Combine:
12256       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12257       // Into:
12258       //    indices are equal or bit offsets are equal => V1
12259       //    otherwise => (extract_subvec V1, ExtIdx)
12260       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12261           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12262         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12263       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12264                          DAG.getNode(ISD::BITCAST, dl,
12265                                      N->getOperand(0).getValueType(),
12266                                      V->getOperand(0)), N->getOperand(1));
12267     }
12268   }
12269
12270   return SDValue();
12271 }
12272
12273 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12274                                                  SDValue V, SelectionDAG &DAG) {
12275   SDLoc DL(V);
12276   EVT VT = V.getValueType();
12277
12278   switch (V.getOpcode()) {
12279   default:
12280     return V;
12281
12282   case ISD::CONCAT_VECTORS: {
12283     EVT OpVT = V->getOperand(0).getValueType();
12284     int OpSize = OpVT.getVectorNumElements();
12285     SmallBitVector OpUsedElements(OpSize, false);
12286     bool FoundSimplification = false;
12287     SmallVector<SDValue, 4> NewOps;
12288     NewOps.reserve(V->getNumOperands());
12289     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12290       SDValue Op = V->getOperand(i);
12291       bool OpUsed = false;
12292       for (int j = 0; j < OpSize; ++j)
12293         if (UsedElements[i * OpSize + j]) {
12294           OpUsedElements[j] = true;
12295           OpUsed = true;
12296         }
12297       NewOps.push_back(
12298           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12299                  : DAG.getUNDEF(OpVT));
12300       FoundSimplification |= Op == NewOps.back();
12301       OpUsedElements.reset();
12302     }
12303     if (FoundSimplification)
12304       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12305     return V;
12306   }
12307
12308   case ISD::INSERT_SUBVECTOR: {
12309     SDValue BaseV = V->getOperand(0);
12310     SDValue SubV = V->getOperand(1);
12311     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12312     if (!IdxN)
12313       return V;
12314
12315     int SubSize = SubV.getValueType().getVectorNumElements();
12316     int Idx = IdxN->getZExtValue();
12317     bool SubVectorUsed = false;
12318     SmallBitVector SubUsedElements(SubSize, false);
12319     for (int i = 0; i < SubSize; ++i)
12320       if (UsedElements[i + Idx]) {
12321         SubVectorUsed = true;
12322         SubUsedElements[i] = true;
12323         UsedElements[i + Idx] = false;
12324       }
12325
12326     // Now recurse on both the base and sub vectors.
12327     SDValue SimplifiedSubV =
12328         SubVectorUsed
12329             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12330             : DAG.getUNDEF(SubV.getValueType());
12331     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12332     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12333       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12334                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12335     return V;
12336   }
12337   }
12338 }
12339
12340 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12341                                        SDValue N1, SelectionDAG &DAG) {
12342   EVT VT = SVN->getValueType(0);
12343   int NumElts = VT.getVectorNumElements();
12344   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12345   for (int M : SVN->getMask())
12346     if (M >= 0 && M < NumElts)
12347       N0UsedElements[M] = true;
12348     else if (M >= NumElts)
12349       N1UsedElements[M - NumElts] = true;
12350
12351   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12352   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12353   if (S0 == N0 && S1 == N1)
12354     return SDValue();
12355
12356   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12357 }
12358
12359 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12360 // or turn a shuffle of a single concat into simpler shuffle then concat.
12361 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12362   EVT VT = N->getValueType(0);
12363   unsigned NumElts = VT.getVectorNumElements();
12364
12365   SDValue N0 = N->getOperand(0);
12366   SDValue N1 = N->getOperand(1);
12367   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12368
12369   SmallVector<SDValue, 4> Ops;
12370   EVT ConcatVT = N0.getOperand(0).getValueType();
12371   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12372   unsigned NumConcats = NumElts / NumElemsPerConcat;
12373
12374   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12375   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12376   // half vector elements.
12377   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12378       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12379                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12380     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12381                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12382     N1 = DAG.getUNDEF(ConcatVT);
12383     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12384   }
12385
12386   // Look at every vector that's inserted. We're looking for exact
12387   // subvector-sized copies from a concatenated vector
12388   for (unsigned I = 0; I != NumConcats; ++I) {
12389     // Make sure we're dealing with a copy.
12390     unsigned Begin = I * NumElemsPerConcat;
12391     bool AllUndef = true, NoUndef = true;
12392     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12393       if (SVN->getMaskElt(J) >= 0)
12394         AllUndef = false;
12395       else
12396         NoUndef = false;
12397     }
12398
12399     if (NoUndef) {
12400       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12401         return SDValue();
12402
12403       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12404         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12405           return SDValue();
12406
12407       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12408       if (FirstElt < N0.getNumOperands())
12409         Ops.push_back(N0.getOperand(FirstElt));
12410       else
12411         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12412
12413     } else if (AllUndef) {
12414       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12415     } else { // Mixed with general masks and undefs, can't do optimization.
12416       return SDValue();
12417     }
12418   }
12419
12420   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12421 }
12422
12423 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12424   EVT VT = N->getValueType(0);
12425   unsigned NumElts = VT.getVectorNumElements();
12426
12427   SDValue N0 = N->getOperand(0);
12428   SDValue N1 = N->getOperand(1);
12429
12430   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12431
12432   // Canonicalize shuffle undef, undef -> undef
12433   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12434     return DAG.getUNDEF(VT);
12435
12436   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12437
12438   // Canonicalize shuffle v, v -> v, undef
12439   if (N0 == N1) {
12440     SmallVector<int, 8> NewMask;
12441     for (unsigned i = 0; i != NumElts; ++i) {
12442       int Idx = SVN->getMaskElt(i);
12443       if (Idx >= (int)NumElts) Idx -= NumElts;
12444       NewMask.push_back(Idx);
12445     }
12446     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12447                                 &NewMask[0]);
12448   }
12449
12450   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12451   if (N0.getOpcode() == ISD::UNDEF) {
12452     SmallVector<int, 8> NewMask;
12453     for (unsigned i = 0; i != NumElts; ++i) {
12454       int Idx = SVN->getMaskElt(i);
12455       if (Idx >= 0) {
12456         if (Idx >= (int)NumElts)
12457           Idx -= NumElts;
12458         else
12459           Idx = -1; // remove reference to lhs
12460       }
12461       NewMask.push_back(Idx);
12462     }
12463     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12464                                 &NewMask[0]);
12465   }
12466
12467   // Remove references to rhs if it is undef
12468   if (N1.getOpcode() == ISD::UNDEF) {
12469     bool Changed = false;
12470     SmallVector<int, 8> NewMask;
12471     for (unsigned i = 0; i != NumElts; ++i) {
12472       int Idx = SVN->getMaskElt(i);
12473       if (Idx >= (int)NumElts) {
12474         Idx = -1;
12475         Changed = true;
12476       }
12477       NewMask.push_back(Idx);
12478     }
12479     if (Changed)
12480       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12481   }
12482
12483   // If it is a splat, check if the argument vector is another splat or a
12484   // build_vector.
12485   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12486     SDNode *V = N0.getNode();
12487
12488     // If this is a bit convert that changes the element type of the vector but
12489     // not the number of vector elements, look through it.  Be careful not to
12490     // look though conversions that change things like v4f32 to v2f64.
12491     if (V->getOpcode() == ISD::BITCAST) {
12492       SDValue ConvInput = V->getOperand(0);
12493       if (ConvInput.getValueType().isVector() &&
12494           ConvInput.getValueType().getVectorNumElements() == NumElts)
12495         V = ConvInput.getNode();
12496     }
12497
12498     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12499       assert(V->getNumOperands() == NumElts &&
12500              "BUILD_VECTOR has wrong number of operands");
12501       SDValue Base;
12502       bool AllSame = true;
12503       for (unsigned i = 0; i != NumElts; ++i) {
12504         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12505           Base = V->getOperand(i);
12506           break;
12507         }
12508       }
12509       // Splat of <u, u, u, u>, return <u, u, u, u>
12510       if (!Base.getNode())
12511         return N0;
12512       for (unsigned i = 0; i != NumElts; ++i) {
12513         if (V->getOperand(i) != Base) {
12514           AllSame = false;
12515           break;
12516         }
12517       }
12518       // Splat of <x, x, x, x>, return <x, x, x, x>
12519       if (AllSame)
12520         return N0;
12521
12522       // Canonicalize any other splat as a build_vector.
12523       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12524       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12525       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12526                                   V->getValueType(0), Ops);
12527
12528       // We may have jumped through bitcasts, so the type of the
12529       // BUILD_VECTOR may not match the type of the shuffle.
12530       if (V->getValueType(0) != VT)
12531         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12532       return NewBV;
12533     }
12534   }
12535
12536   // There are various patterns used to build up a vector from smaller vectors,
12537   // subvectors, or elements. Scan chains of these and replace unused insertions
12538   // or components with undef.
12539   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12540     return S;
12541
12542   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12543       Level < AfterLegalizeVectorOps &&
12544       (N1.getOpcode() == ISD::UNDEF ||
12545       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12546        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12547     SDValue V = partitionShuffleOfConcats(N, DAG);
12548
12549     if (V.getNode())
12550       return V;
12551   }
12552
12553   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12554   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12555   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12556     SmallVector<SDValue, 8> Ops;
12557     for (int M : SVN->getMask()) {
12558       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12559       if (M >= 0) {
12560         int Idx = M % NumElts;
12561         SDValue &S = (M < (int)NumElts ? N0 : N1);
12562         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12563           Op = S.getOperand(Idx);
12564         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12565           if (Idx == 0)
12566             Op = S.getOperand(0);
12567         } else {
12568           // Operand can't be combined - bail out.
12569           break;
12570         }
12571       }
12572       Ops.push_back(Op);
12573     }
12574     if (Ops.size() == VT.getVectorNumElements()) {
12575       // BUILD_VECTOR requires all inputs to be of the same type, find the
12576       // maximum type and extend them all.
12577       EVT SVT = VT.getScalarType();
12578       if (SVT.isInteger())
12579         for (SDValue &Op : Ops)
12580           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12581       if (SVT != VT.getScalarType())
12582         for (SDValue &Op : Ops)
12583           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12584                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12585                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12586       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12587     }
12588   }
12589
12590   // If this shuffle only has a single input that is a bitcasted shuffle,
12591   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12592   // back to their original types.
12593   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12594       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12595       TLI.isTypeLegal(VT)) {
12596
12597     // Peek through the bitcast only if there is one user.
12598     SDValue BC0 = N0;
12599     while (BC0.getOpcode() == ISD::BITCAST) {
12600       if (!BC0.hasOneUse())
12601         break;
12602       BC0 = BC0.getOperand(0);
12603     }
12604
12605     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12606       if (Scale == 1)
12607         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12608
12609       SmallVector<int, 8> NewMask;
12610       for (int M : Mask)
12611         for (int s = 0; s != Scale; ++s)
12612           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12613       return NewMask;
12614     };
12615
12616     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12617       EVT SVT = VT.getScalarType();
12618       EVT InnerVT = BC0->getValueType(0);
12619       EVT InnerSVT = InnerVT.getScalarType();
12620
12621       // Determine which shuffle works with the smaller scalar type.
12622       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12623       EVT ScaleSVT = ScaleVT.getScalarType();
12624
12625       if (TLI.isTypeLegal(ScaleVT) &&
12626           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12627           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12628
12629         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12630         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12631
12632         // Scale the shuffle masks to the smaller scalar type.
12633         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12634         SmallVector<int, 8> InnerMask =
12635             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12636         SmallVector<int, 8> OuterMask =
12637             ScaleShuffleMask(SVN->getMask(), OuterScale);
12638
12639         // Merge the shuffle masks.
12640         SmallVector<int, 8> NewMask;
12641         for (int M : OuterMask)
12642           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12643
12644         // Test for shuffle mask legality over both commutations.
12645         SDValue SV0 = BC0->getOperand(0);
12646         SDValue SV1 = BC0->getOperand(1);
12647         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12648         if (!LegalMask) {
12649           std::swap(SV0, SV1);
12650           ShuffleVectorSDNode::commuteMask(NewMask);
12651           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12652         }
12653
12654         if (LegalMask) {
12655           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12656           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12657           return DAG.getNode(
12658               ISD::BITCAST, SDLoc(N), VT,
12659               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12660         }
12661       }
12662     }
12663   }
12664
12665   // Canonicalize shuffles according to rules:
12666   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12667   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12668   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12669   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12670       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12671       TLI.isTypeLegal(VT)) {
12672     // The incoming shuffle must be of the same type as the result of the
12673     // current shuffle.
12674     assert(N1->getOperand(0).getValueType() == VT &&
12675            "Shuffle types don't match");
12676
12677     SDValue SV0 = N1->getOperand(0);
12678     SDValue SV1 = N1->getOperand(1);
12679     bool HasSameOp0 = N0 == SV0;
12680     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12681     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12682       // Commute the operands of this shuffle so that next rule
12683       // will trigger.
12684       return DAG.getCommutedVectorShuffle(*SVN);
12685   }
12686
12687   // Try to fold according to rules:
12688   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12689   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12690   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12691   // Don't try to fold shuffles with illegal type.
12692   // Only fold if this shuffle is the only user of the other shuffle.
12693   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12694       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12695     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12696
12697     // The incoming shuffle must be of the same type as the result of the
12698     // current shuffle.
12699     assert(OtherSV->getOperand(0).getValueType() == VT &&
12700            "Shuffle types don't match");
12701
12702     SDValue SV0, SV1;
12703     SmallVector<int, 4> Mask;
12704     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12705     // operand, and SV1 as the second operand.
12706     for (unsigned i = 0; i != NumElts; ++i) {
12707       int Idx = SVN->getMaskElt(i);
12708       if (Idx < 0) {
12709         // Propagate Undef.
12710         Mask.push_back(Idx);
12711         continue;
12712       }
12713
12714       SDValue CurrentVec;
12715       if (Idx < (int)NumElts) {
12716         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12717         // shuffle mask to identify which vector is actually referenced.
12718         Idx = OtherSV->getMaskElt(Idx);
12719         if (Idx < 0) {
12720           // Propagate Undef.
12721           Mask.push_back(Idx);
12722           continue;
12723         }
12724
12725         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12726                                            : OtherSV->getOperand(1);
12727       } else {
12728         // This shuffle index references an element within N1.
12729         CurrentVec = N1;
12730       }
12731
12732       // Simple case where 'CurrentVec' is UNDEF.
12733       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12734         Mask.push_back(-1);
12735         continue;
12736       }
12737
12738       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12739       // will be the first or second operand of the combined shuffle.
12740       Idx = Idx % NumElts;
12741       if (!SV0.getNode() || SV0 == CurrentVec) {
12742         // Ok. CurrentVec is the left hand side.
12743         // Update the mask accordingly.
12744         SV0 = CurrentVec;
12745         Mask.push_back(Idx);
12746         continue;
12747       }
12748
12749       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12750       if (SV1.getNode() && SV1 != CurrentVec)
12751         return SDValue();
12752
12753       // Ok. CurrentVec is the right hand side.
12754       // Update the mask accordingly.
12755       SV1 = CurrentVec;
12756       Mask.push_back(Idx + NumElts);
12757     }
12758
12759     // Check if all indices in Mask are Undef. In case, propagate Undef.
12760     bool isUndefMask = true;
12761     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12762       isUndefMask &= Mask[i] < 0;
12763
12764     if (isUndefMask)
12765       return DAG.getUNDEF(VT);
12766
12767     if (!SV0.getNode())
12768       SV0 = DAG.getUNDEF(VT);
12769     if (!SV1.getNode())
12770       SV1 = DAG.getUNDEF(VT);
12771
12772     // Avoid introducing shuffles with illegal mask.
12773     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12774       ShuffleVectorSDNode::commuteMask(Mask);
12775
12776       if (!TLI.isShuffleMaskLegal(Mask, VT))
12777         return SDValue();
12778
12779       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12780       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12781       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12782       std::swap(SV0, SV1);
12783     }
12784
12785     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12786     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12787     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12788     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12789   }
12790
12791   return SDValue();
12792 }
12793
12794 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12795   SDValue InVal = N->getOperand(0);
12796   EVT VT = N->getValueType(0);
12797
12798   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12799   // with a VECTOR_SHUFFLE.
12800   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12801     SDValue InVec = InVal->getOperand(0);
12802     SDValue EltNo = InVal->getOperand(1);
12803
12804     // FIXME: We could support implicit truncation if the shuffle can be
12805     // scaled to a smaller vector scalar type.
12806     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12807     if (C0 && VT == InVec.getValueType() &&
12808         VT.getScalarType() == InVal.getValueType()) {
12809       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12810       int Elt = C0->getZExtValue();
12811       NewMask[0] = Elt;
12812
12813       if (TLI.isShuffleMaskLegal(NewMask, VT))
12814         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12815                                     NewMask);
12816     }
12817   }
12818
12819   return SDValue();
12820 }
12821
12822 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12823   SDValue N0 = N->getOperand(0);
12824   SDValue N2 = N->getOperand(2);
12825
12826   // If the input vector is a concatenation, and the insert replaces
12827   // one of the halves, we can optimize into a single concat_vectors.
12828   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12829       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12830     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12831     EVT VT = N->getValueType(0);
12832
12833     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12834     // (concat_vectors Z, Y)
12835     if (InsIdx == 0)
12836       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12837                          N->getOperand(1), N0.getOperand(1));
12838
12839     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12840     // (concat_vectors X, Z)
12841     if (InsIdx == VT.getVectorNumElements()/2)
12842       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12843                          N0.getOperand(0), N->getOperand(1));
12844   }
12845
12846   return SDValue();
12847 }
12848
12849 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12850   SDValue N0 = N->getOperand(0);
12851
12852   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12853   if (N0->getOpcode() == ISD::FP16_TO_FP)
12854     return N0->getOperand(0);
12855
12856   return SDValue();
12857 }
12858
12859 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12860 /// with the destination vector and a zero vector.
12861 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12862 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12863 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12864   EVT VT = N->getValueType(0);
12865   SDValue LHS = N->getOperand(0);
12866   SDValue RHS = N->getOperand(1);
12867   SDLoc dl(N);
12868
12869   // Make sure we're not running after operation legalization where it 
12870   // may have custom lowered the vector shuffles.
12871   if (LegalOperations)
12872     return SDValue();
12873
12874   if (N->getOpcode() != ISD::AND)
12875     return SDValue();
12876
12877   if (RHS.getOpcode() == ISD::BITCAST)
12878     RHS = RHS.getOperand(0);
12879
12880   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12881     SmallVector<int, 8> Indices;
12882     unsigned NumElts = RHS.getNumOperands();
12883
12884     for (unsigned i = 0; i != NumElts; ++i) {
12885       SDValue Elt = RHS.getOperand(i);
12886       if (!isa<ConstantSDNode>(Elt))
12887         return SDValue();
12888
12889       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12890         Indices.push_back(i);
12891       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12892         Indices.push_back(NumElts+i);
12893       else
12894         return SDValue();
12895     }
12896
12897     // Let's see if the target supports this vector_shuffle.
12898     EVT RVT = RHS.getValueType();
12899     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12900       return SDValue();
12901
12902     // Return the new VECTOR_SHUFFLE node.
12903     EVT EltVT = RVT.getVectorElementType();
12904     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12905                                    DAG.getConstant(0, dl, EltVT));
12906     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12907     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12908     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12909     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12910   }
12911
12912   return SDValue();
12913 }
12914
12915 /// Visit a binary vector operation, like ADD.
12916 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12917   assert(N->getValueType(0).isVector() &&
12918          "SimplifyVBinOp only works on vectors!");
12919
12920   SDValue LHS = N->getOperand(0);
12921   SDValue RHS = N->getOperand(1);
12922
12923   if (SDValue Shuffle = XformToShuffleWithZero(N))
12924     return Shuffle;
12925
12926   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12927   // this operation.
12928   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12929       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12930     // Check if both vectors are constants. If not bail out.
12931     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12932           cast<BuildVectorSDNode>(RHS)->isConstant()))
12933       return SDValue();
12934
12935     SmallVector<SDValue, 8> Ops;
12936     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12937       SDValue LHSOp = LHS.getOperand(i);
12938       SDValue RHSOp = RHS.getOperand(i);
12939
12940       // Can't fold divide by zero.
12941       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12942           N->getOpcode() == ISD::FDIV) {
12943         if ((RHSOp.getOpcode() == ISD::Constant &&
12944              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12945             (RHSOp.getOpcode() == ISD::ConstantFP &&
12946              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12947           break;
12948       }
12949
12950       EVT VT = LHSOp.getValueType();
12951       EVT RVT = RHSOp.getValueType();
12952       if (RVT != VT) {
12953         // Integer BUILD_VECTOR operands may have types larger than the element
12954         // size (e.g., when the element type is not legal).  Prior to type
12955         // legalization, the types may not match between the two BUILD_VECTORS.
12956         // Truncate one of the operands to make them match.
12957         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12958           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12959         } else {
12960           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12961           VT = RVT;
12962         }
12963       }
12964       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12965                                    LHSOp, RHSOp);
12966       if (FoldOp.getOpcode() != ISD::UNDEF &&
12967           FoldOp.getOpcode() != ISD::Constant &&
12968           FoldOp.getOpcode() != ISD::ConstantFP)
12969         break;
12970       Ops.push_back(FoldOp);
12971       AddToWorklist(FoldOp.getNode());
12972     }
12973
12974     if (Ops.size() == LHS.getNumOperands())
12975       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12976   }
12977
12978   // Type legalization might introduce new shuffles in the DAG.
12979   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12980   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12981   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12982       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12983       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12984       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12985     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12986     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12987
12988     if (SVN0->getMask().equals(SVN1->getMask())) {
12989       EVT VT = N->getValueType(0);
12990       SDValue UndefVector = LHS.getOperand(1);
12991       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12992                                      LHS.getOperand(0), RHS.getOperand(0));
12993       AddUsersToWorklist(N);
12994       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12995                                   &SVN0->getMask()[0]);
12996     }
12997   }
12998
12999   return SDValue();
13000 }
13001
13002 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
13003                                     SDValue N1, SDValue N2){
13004   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
13005
13006   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
13007                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
13008
13009   // If we got a simplified select_cc node back from SimplifySelectCC, then
13010   // break it down into a new SETCC node, and a new SELECT node, and then return
13011   // the SELECT node, since we were called with a SELECT node.
13012   if (SCC.getNode()) {
13013     // Check to see if we got a select_cc back (to turn into setcc/select).
13014     // Otherwise, just return whatever node we got back, like fabs.
13015     if (SCC.getOpcode() == ISD::SELECT_CC) {
13016       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
13017                                   N0.getValueType(),
13018                                   SCC.getOperand(0), SCC.getOperand(1),
13019                                   SCC.getOperand(4));
13020       AddToWorklist(SETCC.getNode());
13021       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
13022                            SCC.getOperand(2), SCC.getOperand(3));
13023     }
13024
13025     return SCC;
13026   }
13027   return SDValue();
13028 }
13029
13030 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
13031 /// being selected between, see if we can simplify the select.  Callers of this
13032 /// should assume that TheSelect is deleted if this returns true.  As such, they
13033 /// should return the appropriate thing (e.g. the node) back to the top-level of
13034 /// the DAG combiner loop to avoid it being looked at.
13035 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
13036                                     SDValue RHS) {
13037
13038   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13039   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
13040   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
13041     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
13042       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
13043       SDValue Sqrt = RHS;
13044       ISD::CondCode CC;
13045       SDValue CmpLHS;
13046       const ConstantFPSDNode *NegZero = nullptr;
13047
13048       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
13049         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
13050         CmpLHS = TheSelect->getOperand(0);
13051         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
13052       } else {
13053         // SELECT or VSELECT
13054         SDValue Cmp = TheSelect->getOperand(0);
13055         if (Cmp.getOpcode() == ISD::SETCC) {
13056           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
13057           CmpLHS = Cmp.getOperand(0);
13058           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
13059         }
13060       }
13061       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
13062           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
13063           CC == ISD::SETULT || CC == ISD::SETLT)) {
13064         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
13065         CombineTo(TheSelect, Sqrt);
13066         return true;
13067       }
13068     }
13069   }
13070   // Cannot simplify select with vector condition
13071   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
13072
13073   // If this is a select from two identical things, try to pull the operation
13074   // through the select.
13075   if (LHS.getOpcode() != RHS.getOpcode() ||
13076       !LHS.hasOneUse() || !RHS.hasOneUse())
13077     return false;
13078
13079   // If this is a load and the token chain is identical, replace the select
13080   // of two loads with a load through a select of the address to load from.
13081   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
13082   // constants have been dropped into the constant pool.
13083   if (LHS.getOpcode() == ISD::LOAD) {
13084     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
13085     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
13086
13087     // Token chains must be identical.
13088     if (LHS.getOperand(0) != RHS.getOperand(0) ||
13089         // Do not let this transformation reduce the number of volatile loads.
13090         LLD->isVolatile() || RLD->isVolatile() ||
13091         // FIXME: If either is a pre/post inc/dec load,
13092         // we'd need to split out the address adjustment.
13093         LLD->isIndexed() || RLD->isIndexed() ||
13094         // If this is an EXTLOAD, the VT's must match.
13095         LLD->getMemoryVT() != RLD->getMemoryVT() ||
13096         // If this is an EXTLOAD, the kind of extension must match.
13097         (LLD->getExtensionType() != RLD->getExtensionType() &&
13098          // The only exception is if one of the extensions is anyext.
13099          LLD->getExtensionType() != ISD::EXTLOAD &&
13100          RLD->getExtensionType() != ISD::EXTLOAD) ||
13101         // FIXME: this discards src value information.  This is
13102         // over-conservative. It would be beneficial to be able to remember
13103         // both potential memory locations.  Since we are discarding
13104         // src value info, don't do the transformation if the memory
13105         // locations are not in the default address space.
13106         LLD->getPointerInfo().getAddrSpace() != 0 ||
13107         RLD->getPointerInfo().getAddrSpace() != 0 ||
13108         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13109                                       LLD->getBasePtr().getValueType()))
13110       return false;
13111
13112     // Check that the select condition doesn't reach either load.  If so,
13113     // folding this will induce a cycle into the DAG.  If not, this is safe to
13114     // xform, so create a select of the addresses.
13115     SDValue Addr;
13116     if (TheSelect->getOpcode() == ISD::SELECT) {
13117       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13118       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13119           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13120         return false;
13121       // The loads must not depend on one another.
13122       if (LLD->isPredecessorOf(RLD) ||
13123           RLD->isPredecessorOf(LLD))
13124         return false;
13125       Addr = DAG.getSelect(SDLoc(TheSelect),
13126                            LLD->getBasePtr().getValueType(),
13127                            TheSelect->getOperand(0), LLD->getBasePtr(),
13128                            RLD->getBasePtr());
13129     } else {  // Otherwise SELECT_CC
13130       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13131       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13132
13133       if ((LLD->hasAnyUseOfValue(1) &&
13134            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13135           (RLD->hasAnyUseOfValue(1) &&
13136            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13137         return false;
13138
13139       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13140                          LLD->getBasePtr().getValueType(),
13141                          TheSelect->getOperand(0),
13142                          TheSelect->getOperand(1),
13143                          LLD->getBasePtr(), RLD->getBasePtr(),
13144                          TheSelect->getOperand(4));
13145     }
13146
13147     SDValue Load;
13148     // It is safe to replace the two loads if they have different alignments,
13149     // but the new load must be the minimum (most restrictive) alignment of the
13150     // inputs.
13151     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13152     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13153     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13154       Load = DAG.getLoad(TheSelect->getValueType(0),
13155                          SDLoc(TheSelect),
13156                          // FIXME: Discards pointer and AA info.
13157                          LLD->getChain(), Addr, MachinePointerInfo(),
13158                          LLD->isVolatile(), LLD->isNonTemporal(),
13159                          isInvariant, Alignment);
13160     } else {
13161       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13162                             RLD->getExtensionType() : LLD->getExtensionType(),
13163                             SDLoc(TheSelect),
13164                             TheSelect->getValueType(0),
13165                             // FIXME: Discards pointer and AA info.
13166                             LLD->getChain(), Addr, MachinePointerInfo(),
13167                             LLD->getMemoryVT(), LLD->isVolatile(),
13168                             LLD->isNonTemporal(), isInvariant, Alignment);
13169     }
13170
13171     // Users of the select now use the result of the load.
13172     CombineTo(TheSelect, Load);
13173
13174     // Users of the old loads now use the new load's chain.  We know the
13175     // old-load value is dead now.
13176     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13177     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13178     return true;
13179   }
13180
13181   return false;
13182 }
13183
13184 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13185 /// where 'cond' is the comparison specified by CC.
13186 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13187                                       SDValue N2, SDValue N3,
13188                                       ISD::CondCode CC, bool NotExtCompare) {
13189   // (x ? y : y) -> y.
13190   if (N2 == N3) return N2;
13191
13192   EVT VT = N2.getValueType();
13193   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13194   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13195   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13196
13197   // Determine if the condition we're dealing with is constant
13198   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13199                               N0, N1, CC, DL, false);
13200   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13201   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13202
13203   // fold select_cc true, x, y -> x
13204   if (SCCC && !SCCC->isNullValue())
13205     return N2;
13206   // fold select_cc false, x, y -> y
13207   if (SCCC && SCCC->isNullValue())
13208     return N3;
13209
13210   // Check to see if we can simplify the select into an fabs node
13211   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13212     // Allow either -0.0 or 0.0
13213     if (CFP->getValueAPF().isZero()) {
13214       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13215       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13216           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13217           N2 == N3.getOperand(0))
13218         return DAG.getNode(ISD::FABS, DL, VT, N0);
13219
13220       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13221       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13222           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13223           N2.getOperand(0) == N3)
13224         return DAG.getNode(ISD::FABS, DL, VT, N3);
13225     }
13226   }
13227
13228   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13229   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13230   // in it.  This is a win when the constant is not otherwise available because
13231   // it replaces two constant pool loads with one.  We only do this if the FP
13232   // type is known to be legal, because if it isn't, then we are before legalize
13233   // types an we want the other legalization to happen first (e.g. to avoid
13234   // messing with soft float) and if the ConstantFP is not legal, because if
13235   // it is legal, we may not need to store the FP constant in a constant pool.
13236   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13237     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13238       if (TLI.isTypeLegal(N2.getValueType()) &&
13239           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13240                TargetLowering::Legal &&
13241            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13242            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13243           // If both constants have multiple uses, then we won't need to do an
13244           // extra load, they are likely around in registers for other users.
13245           (TV->hasOneUse() || FV->hasOneUse())) {
13246         Constant *Elts[] = {
13247           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13248           const_cast<ConstantFP*>(TV->getConstantFPValue())
13249         };
13250         Type *FPTy = Elts[0]->getType();
13251         const DataLayout &TD = *TLI.getDataLayout();
13252
13253         // Create a ConstantArray of the two constants.
13254         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13255         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13256                                             TD.getPrefTypeAlignment(FPTy));
13257         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13258
13259         // Get the offsets to the 0 and 1 element of the array so that we can
13260         // select between them.
13261         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13262         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13263         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13264
13265         SDValue Cond = DAG.getSetCC(DL,
13266                                     getSetCCResultType(N0.getValueType()),
13267                                     N0, N1, CC);
13268         AddToWorklist(Cond.getNode());
13269         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13270                                           Cond, One, Zero);
13271         AddToWorklist(CstOffset.getNode());
13272         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13273                             CstOffset);
13274         AddToWorklist(CPIdx.getNode());
13275         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13276                            MachinePointerInfo::getConstantPool(), false,
13277                            false, false, Alignment);
13278       }
13279     }
13280
13281   // Check to see if we can perform the "gzip trick", transforming
13282   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13283   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13284       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13285        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13286     EVT XType = N0.getValueType();
13287     EVT AType = N2.getValueType();
13288     if (XType.bitsGE(AType)) {
13289       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13290       // single-bit constant.
13291       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13292         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13293         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13294         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13295                                        getShiftAmountTy(N0.getValueType()));
13296         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13297                                     XType, N0, ShCt);
13298         AddToWorklist(Shift.getNode());
13299
13300         if (XType.bitsGT(AType)) {
13301           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13302           AddToWorklist(Shift.getNode());
13303         }
13304
13305         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13306       }
13307
13308       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13309                                   XType, N0,
13310                                   DAG.getConstant(XType.getSizeInBits() - 1,
13311                                                   SDLoc(N0),
13312                                          getShiftAmountTy(N0.getValueType())));
13313       AddToWorklist(Shift.getNode());
13314
13315       if (XType.bitsGT(AType)) {
13316         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13317         AddToWorklist(Shift.getNode());
13318       }
13319
13320       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13321     }
13322   }
13323
13324   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13325   // where y is has a single bit set.
13326   // A plaintext description would be, we can turn the SELECT_CC into an AND
13327   // when the condition can be materialized as an all-ones register.  Any
13328   // single bit-test can be materialized as an all-ones register with
13329   // shift-left and shift-right-arith.
13330   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13331       N0->getValueType(0) == VT &&
13332       N1C && N1C->isNullValue() &&
13333       N2C && N2C->isNullValue()) {
13334     SDValue AndLHS = N0->getOperand(0);
13335     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13336     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13337       // Shift the tested bit over the sign bit.
13338       APInt AndMask = ConstAndRHS->getAPIntValue();
13339       SDValue ShlAmt =
13340         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13341                         getShiftAmountTy(AndLHS.getValueType()));
13342       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13343
13344       // Now arithmetic right shift it all the way over, so the result is either
13345       // all-ones, or zero.
13346       SDValue ShrAmt =
13347         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13348                         getShiftAmountTy(Shl.getValueType()));
13349       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13350
13351       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13352     }
13353   }
13354
13355   // fold select C, 16, 0 -> shl C, 4
13356   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13357       TLI.getBooleanContents(N0.getValueType()) ==
13358           TargetLowering::ZeroOrOneBooleanContent) {
13359
13360     // If the caller doesn't want us to simplify this into a zext of a compare,
13361     // don't do it.
13362     if (NotExtCompare && N2C->getAPIntValue() == 1)
13363       return SDValue();
13364
13365     // Get a SetCC of the condition
13366     // NOTE: Don't create a SETCC if it's not legal on this target.
13367     if (!LegalOperations ||
13368         TLI.isOperationLegal(ISD::SETCC,
13369           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13370       SDValue Temp, SCC;
13371       // cast from setcc result type to select result type
13372       if (LegalTypes) {
13373         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13374                             N0, N1, CC);
13375         if (N2.getValueType().bitsLT(SCC.getValueType()))
13376           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13377                                         N2.getValueType());
13378         else
13379           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13380                              N2.getValueType(), SCC);
13381       } else {
13382         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13383         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13384                            N2.getValueType(), SCC);
13385       }
13386
13387       AddToWorklist(SCC.getNode());
13388       AddToWorklist(Temp.getNode());
13389
13390       if (N2C->getAPIntValue() == 1)
13391         return Temp;
13392
13393       // shl setcc result by log2 n2c
13394       return DAG.getNode(
13395           ISD::SHL, DL, N2.getValueType(), Temp,
13396           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13397                           getShiftAmountTy(Temp.getValueType())));
13398     }
13399   }
13400
13401   // Check to see if this is the equivalent of setcc
13402   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13403   // otherwise, go ahead with the folds.
13404   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13405     EVT XType = N0.getValueType();
13406     if (!LegalOperations ||
13407         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13408       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13409       if (Res.getValueType() != VT)
13410         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13411       return Res;
13412     }
13413
13414     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13415     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13416         (!LegalOperations ||
13417          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13418       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13419       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13420                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13421                                          SDLoc(Ctlz),
13422                                        getShiftAmountTy(Ctlz.getValueType())));
13423     }
13424     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13425     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13426       SDLoc DL(N0);
13427       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13428                                   XType, DAG.getConstant(0, DL, XType), N0);
13429       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13430       return DAG.getNode(ISD::SRL, DL, XType,
13431                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13432                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13433                                          getShiftAmountTy(XType)));
13434     }
13435     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13436     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13437       SDLoc DL(N0);
13438       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13439                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13440                                          getShiftAmountTy(N0.getValueType())));
13441       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13442                                                                     XType));
13443     }
13444   }
13445
13446   // Check to see if this is an integer abs.
13447   // select_cc setg[te] X,  0,  X, -X ->
13448   // select_cc setgt    X, -1,  X, -X ->
13449   // select_cc setl[te] X,  0, -X,  X ->
13450   // select_cc setlt    X,  1, -X,  X ->
13451   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13452   if (N1C) {
13453     ConstantSDNode *SubC = nullptr;
13454     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13455          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13456         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13457       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13458     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13459               (N1C->isOne() && CC == ISD::SETLT)) &&
13460              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13461       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13462
13463     EVT XType = N0.getValueType();
13464     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13465       SDLoc DL(N0);
13466       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13467                                   N0,
13468                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13469                                          getShiftAmountTy(N0.getValueType())));
13470       SDValue Add = DAG.getNode(ISD::ADD, DL,
13471                                 XType, N0, Shift);
13472       AddToWorklist(Shift.getNode());
13473       AddToWorklist(Add.getNode());
13474       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13475     }
13476   }
13477
13478   return SDValue();
13479 }
13480
13481 /// This is a stub for TargetLowering::SimplifySetCC.
13482 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13483                                    SDValue N1, ISD::CondCode Cond,
13484                                    SDLoc DL, bool foldBooleans) {
13485   TargetLowering::DAGCombinerInfo
13486     DagCombineInfo(DAG, Level, false, this);
13487   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13488 }
13489
13490 /// Given an ISD::SDIV node expressing a divide by constant, return
13491 /// a DAG expression to select that will generate the same value by multiplying
13492 /// by a magic number.
13493 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13494 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13495   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13496   if (!C)
13497     return SDValue();
13498
13499   // Avoid division by zero.
13500   if (!C->getAPIntValue())
13501     return SDValue();
13502
13503   std::vector<SDNode*> Built;
13504   SDValue S =
13505       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13506
13507   for (SDNode *N : Built)
13508     AddToWorklist(N);
13509   return S;
13510 }
13511
13512 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13513 /// DAG expression that will generate the same value by right shifting.
13514 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13515   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13516   if (!C)
13517     return SDValue();
13518
13519   // Avoid division by zero.
13520   if (!C->getAPIntValue())
13521     return SDValue();
13522
13523   std::vector<SDNode *> Built;
13524   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13525
13526   for (SDNode *N : Built)
13527     AddToWorklist(N);
13528   return S;
13529 }
13530
13531 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13532 /// expression that will generate the same value by multiplying by a magic
13533 /// number.
13534 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13535 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13536   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13537   if (!C)
13538     return SDValue();
13539
13540   // Avoid division by zero.
13541   if (!C->getAPIntValue())
13542     return SDValue();
13543
13544   std::vector<SDNode*> Built;
13545   SDValue S =
13546       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13547
13548   for (SDNode *N : Built)
13549     AddToWorklist(N);
13550   return S;
13551 }
13552
13553 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13554   if (Level >= AfterLegalizeDAG)
13555     return SDValue();
13556
13557   // Expose the DAG combiner to the target combiner implementations.
13558   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13559
13560   unsigned Iterations = 0;
13561   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13562     if (Iterations) {
13563       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13564       // For the reciprocal, we need to find the zero of the function:
13565       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13566       //     =>
13567       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13568       //     does not require additional intermediate precision]
13569       EVT VT = Op.getValueType();
13570       SDLoc DL(Op);
13571       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13572
13573       AddToWorklist(Est.getNode());
13574
13575       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13576       for (unsigned i = 0; i < Iterations; ++i) {
13577         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13578         AddToWorklist(NewEst.getNode());
13579
13580         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13581         AddToWorklist(NewEst.getNode());
13582
13583         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13584         AddToWorklist(NewEst.getNode());
13585
13586         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13587         AddToWorklist(Est.getNode());
13588       }
13589     }
13590     return Est;
13591   }
13592
13593   return SDValue();
13594 }
13595
13596 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13597 /// For the reciprocal sqrt, we need to find the zero of the function:
13598 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13599 ///     =>
13600 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13601 /// As a result, we precompute A/2 prior to the iteration loop.
13602 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13603                                           unsigned Iterations) {
13604   EVT VT = Arg.getValueType();
13605   SDLoc DL(Arg);
13606   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13607
13608   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13609   // this entire sequence requires only one FP constant.
13610   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13611   AddToWorklist(HalfArg.getNode());
13612
13613   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13614   AddToWorklist(HalfArg.getNode());
13615
13616   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13617   for (unsigned i = 0; i < Iterations; ++i) {
13618     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13619     AddToWorklist(NewEst.getNode());
13620
13621     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13622     AddToWorklist(NewEst.getNode());
13623
13624     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13625     AddToWorklist(NewEst.getNode());
13626
13627     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13628     AddToWorklist(Est.getNode());
13629   }
13630   return Est;
13631 }
13632
13633 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13634 /// For the reciprocal sqrt, we need to find the zero of the function:
13635 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13636 ///     =>
13637 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13638 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13639                                           unsigned Iterations) {
13640   EVT VT = Arg.getValueType();
13641   SDLoc DL(Arg);
13642   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13643   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13644
13645   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13646   for (unsigned i = 0; i < Iterations; ++i) {
13647     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13648     AddToWorklist(HalfEst.getNode());
13649
13650     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13651     AddToWorklist(Est.getNode());
13652
13653     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13654     AddToWorklist(Est.getNode());
13655
13656     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13657     AddToWorklist(Est.getNode());
13658
13659     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13660     AddToWorklist(Est.getNode());
13661   }
13662   return Est;
13663 }
13664
13665 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13666   if (Level >= AfterLegalizeDAG)
13667     return SDValue();
13668
13669   // Expose the DAG combiner to the target combiner implementations.
13670   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13671   unsigned Iterations = 0;
13672   bool UseOneConstNR = false;
13673   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13674     AddToWorklist(Est.getNode());
13675     if (Iterations) {
13676       Est = UseOneConstNR ?
13677         BuildRsqrtNROneConst(Op, Est, Iterations) :
13678         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13679     }
13680     return Est;
13681   }
13682
13683   return SDValue();
13684 }
13685
13686 /// Return true if base is a frame index, which is known not to alias with
13687 /// anything but itself.  Provides base object and offset as results.
13688 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13689                            const GlobalValue *&GV, const void *&CV) {
13690   // Assume it is a primitive operation.
13691   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13692
13693   // If it's an adding a simple constant then integrate the offset.
13694   if (Base.getOpcode() == ISD::ADD) {
13695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13696       Base = Base.getOperand(0);
13697       Offset += C->getZExtValue();
13698     }
13699   }
13700
13701   // Return the underlying GlobalValue, and update the Offset.  Return false
13702   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13703   // by multiple nodes with different offsets.
13704   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13705     GV = G->getGlobal();
13706     Offset += G->getOffset();
13707     return false;
13708   }
13709
13710   // Return the underlying Constant value, and update the Offset.  Return false
13711   // for ConstantSDNodes since the same constant pool entry may be represented
13712   // by multiple nodes with different offsets.
13713   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13714     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13715                                          : (const void *)C->getConstVal();
13716     Offset += C->getOffset();
13717     return false;
13718   }
13719   // If it's any of the following then it can't alias with anything but itself.
13720   return isa<FrameIndexSDNode>(Base);
13721 }
13722
13723 /// Return true if there is any possibility that the two addresses overlap.
13724 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13725   // If they are the same then they must be aliases.
13726   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13727
13728   // If they are both volatile then they cannot be reordered.
13729   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13730
13731   // Gather base node and offset information.
13732   SDValue Base1, Base2;
13733   int64_t Offset1, Offset2;
13734   const GlobalValue *GV1, *GV2;
13735   const void *CV1, *CV2;
13736   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13737                                       Base1, Offset1, GV1, CV1);
13738   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13739                                       Base2, Offset2, GV2, CV2);
13740
13741   // If they have a same base address then check to see if they overlap.
13742   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13743     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13744              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13745
13746   // It is possible for different frame indices to alias each other, mostly
13747   // when tail call optimization reuses return address slots for arguments.
13748   // To catch this case, look up the actual index of frame indices to compute
13749   // the real alias relationship.
13750   if (isFrameIndex1 && isFrameIndex2) {
13751     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13752     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13753     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13754     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13755              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13756   }
13757
13758   // Otherwise, if we know what the bases are, and they aren't identical, then
13759   // we know they cannot alias.
13760   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13761     return false;
13762
13763   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13764   // compared to the size and offset of the access, we may be able to prove they
13765   // do not alias.  This check is conservative for now to catch cases created by
13766   // splitting vector types.
13767   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13768       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13769       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13770        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13771       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13772     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13773     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13774
13775     // There is no overlap between these relatively aligned accesses of similar
13776     // size, return no alias.
13777     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13778         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13779       return false;
13780   }
13781
13782   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13783                    ? CombinerGlobalAA
13784                    : DAG.getSubtarget().useAA();
13785 #ifndef NDEBUG
13786   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13787       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13788     UseAA = false;
13789 #endif
13790   if (UseAA &&
13791       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13792     // Use alias analysis information.
13793     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13794                                  Op1->getSrcValueOffset());
13795     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13796         Op0->getSrcValueOffset() - MinOffset;
13797     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13798         Op1->getSrcValueOffset() - MinOffset;
13799     AliasAnalysis::AliasResult AAResult =
13800         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13801                                          Overlap1,
13802                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13803                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13804                                          Overlap2,
13805                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13806     if (AAResult == AliasAnalysis::NoAlias)
13807       return false;
13808   }
13809
13810   // Otherwise we have to assume they alias.
13811   return true;
13812 }
13813
13814 /// Walk up chain skipping non-aliasing memory nodes,
13815 /// looking for aliasing nodes and adding them to the Aliases vector.
13816 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13817                                    SmallVectorImpl<SDValue> &Aliases) {
13818   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13819   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13820
13821   // Get alias information for node.
13822   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13823
13824   // Starting off.
13825   Chains.push_back(OriginalChain);
13826   unsigned Depth = 0;
13827
13828   // Look at each chain and determine if it is an alias.  If so, add it to the
13829   // aliases list.  If not, then continue up the chain looking for the next
13830   // candidate.
13831   while (!Chains.empty()) {
13832     SDValue Chain = Chains.back();
13833     Chains.pop_back();
13834
13835     // For TokenFactor nodes, look at each operand and only continue up the
13836     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13837     // find more and revert to original chain since the xform is unlikely to be
13838     // profitable.
13839     //
13840     // FIXME: The depth check could be made to return the last non-aliasing
13841     // chain we found before we hit a tokenfactor rather than the original
13842     // chain.
13843     if (Depth > 6 || Aliases.size() == 2) {
13844       Aliases.clear();
13845       Aliases.push_back(OriginalChain);
13846       return;
13847     }
13848
13849     // Don't bother if we've been before.
13850     if (!Visited.insert(Chain.getNode()).second)
13851       continue;
13852
13853     switch (Chain.getOpcode()) {
13854     case ISD::EntryToken:
13855       // Entry token is ideal chain operand, but handled in FindBetterChain.
13856       break;
13857
13858     case ISD::LOAD:
13859     case ISD::STORE: {
13860       // Get alias information for Chain.
13861       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13862           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13863
13864       // If chain is alias then stop here.
13865       if (!(IsLoad && IsOpLoad) &&
13866           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13867         Aliases.push_back(Chain);
13868       } else {
13869         // Look further up the chain.
13870         Chains.push_back(Chain.getOperand(0));
13871         ++Depth;
13872       }
13873       break;
13874     }
13875
13876     case ISD::TokenFactor:
13877       // We have to check each of the operands of the token factor for "small"
13878       // token factors, so we queue them up.  Adding the operands to the queue
13879       // (stack) in reverse order maintains the original order and increases the
13880       // likelihood that getNode will find a matching token factor (CSE.)
13881       if (Chain.getNumOperands() > 16) {
13882         Aliases.push_back(Chain);
13883         break;
13884       }
13885       for (unsigned n = Chain.getNumOperands(); n;)
13886         Chains.push_back(Chain.getOperand(--n));
13887       ++Depth;
13888       break;
13889
13890     default:
13891       // For all other instructions we will just have to take what we can get.
13892       Aliases.push_back(Chain);
13893       break;
13894     }
13895   }
13896
13897   // We need to be careful here to also search for aliases through the
13898   // value operand of a store, etc. Consider the following situation:
13899   //   Token1 = ...
13900   //   L1 = load Token1, %52
13901   //   S1 = store Token1, L1, %51
13902   //   L2 = load Token1, %52+8
13903   //   S2 = store Token1, L2, %51+8
13904   //   Token2 = Token(S1, S2)
13905   //   L3 = load Token2, %53
13906   //   S3 = store Token2, L3, %52
13907   //   L4 = load Token2, %53+8
13908   //   S4 = store Token2, L4, %52+8
13909   // If we search for aliases of S3 (which loads address %52), and we look
13910   // only through the chain, then we'll miss the trivial dependence on L1
13911   // (which also loads from %52). We then might change all loads and
13912   // stores to use Token1 as their chain operand, which could result in
13913   // copying %53 into %52 before copying %52 into %51 (which should
13914   // happen first).
13915   //
13916   // The problem is, however, that searching for such data dependencies
13917   // can become expensive, and the cost is not directly related to the
13918   // chain depth. Instead, we'll rule out such configurations here by
13919   // insisting that we've visited all chain users (except for users
13920   // of the original chain, which is not necessary). When doing this,
13921   // we need to look through nodes we don't care about (otherwise, things
13922   // like register copies will interfere with trivial cases).
13923
13924   SmallVector<const SDNode *, 16> Worklist;
13925   for (const SDNode *N : Visited)
13926     if (N != OriginalChain.getNode())
13927       Worklist.push_back(N);
13928
13929   while (!Worklist.empty()) {
13930     const SDNode *M = Worklist.pop_back_val();
13931
13932     // We have already visited M, and want to make sure we've visited any uses
13933     // of M that we care about. For uses that we've not visisted, and don't
13934     // care about, queue them to the worklist.
13935
13936     for (SDNode::use_iterator UI = M->use_begin(),
13937          UIE = M->use_end(); UI != UIE; ++UI)
13938       if (UI.getUse().getValueType() == MVT::Other &&
13939           Visited.insert(*UI).second) {
13940         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13941           // We've not visited this use, and we care about it (it could have an
13942           // ordering dependency with the original node).
13943           Aliases.clear();
13944           Aliases.push_back(OriginalChain);
13945           return;
13946         }
13947
13948         // We've not visited this use, but we don't care about it. Mark it as
13949         // visited and enqueue it to the worklist.
13950         Worklist.push_back(*UI);
13951       }
13952   }
13953 }
13954
13955 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13956 /// (aliasing node.)
13957 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13958   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13959
13960   // Accumulate all the aliases to this node.
13961   GatherAllAliases(N, OldChain, Aliases);
13962
13963   // If no operands then chain to entry token.
13964   if (Aliases.size() == 0)
13965     return DAG.getEntryNode();
13966
13967   // If a single operand then chain to it.  We don't need to revisit it.
13968   if (Aliases.size() == 1)
13969     return Aliases[0];
13970
13971   // Construct a custom tailored token factor.
13972   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13973 }
13974
13975 /// This is the entry point for the file.
13976 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13977                            CodeGenOpt::Level OptLevel) {
13978   /// This is the main entry point to this class.
13979   DAGCombiner(*this, AA, OptLevel).Run(Level);
13980 }