too much space again; 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 visitFP_TO_FP16(SDNode *N);
311
312     SDValue visitFADDForFMACombine(SDNode *N);
313     SDValue visitFSUBForFMACombine(SDNode *N);
314
315     SDValue XformToShuffleWithZero(SDNode *N);
316     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
317
318     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
319
320     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
321     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
322     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
323     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
324                              SDValue N3, ISD::CondCode CC,
325                              bool NotExtCompare = false);
326     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
327                           SDLoc DL, bool foldBooleans = true);
328
329     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
330                            SDValue &CC) const;
331     bool isOneUseSetCC(SDValue N) const;
332
333     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
334                                          unsigned HiOp);
335     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
336     SDValue CombineExtLoad(SDNode *N);
337     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
338     SDValue BuildSDIV(SDNode *N);
339     SDValue BuildSDIVPow2(SDNode *N);
340     SDValue BuildUDIV(SDNode *N);
341     SDValue BuildReciprocalEstimate(SDValue Op);
342     SDValue BuildRsqrtEstimate(SDValue Op);
343     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
344     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
345     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
346                                bool DemandHighBits = true);
347     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
348     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
349                               SDValue InnerPos, SDValue InnerNeg,
350                               unsigned PosOpcode, unsigned NegOpcode,
351                               SDLoc DL);
352     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
353     SDValue ReduceLoadWidth(SDNode *N);
354     SDValue ReduceLoadOpStoreWidth(SDNode *N);
355     SDValue TransformFPLoadStorePair(SDNode *N);
356     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
357     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
358
359     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
360
361     /// Walk up chain skipping non-aliasing memory nodes,
362     /// looking for aliasing nodes and adding them to the Aliases vector.
363     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
364                           SmallVectorImpl<SDValue> &Aliases);
365
366     /// Return true if there is any possibility that the two addresses overlap.
367     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
368
369     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
370     /// chain (aliasing node.)
371     SDValue FindBetterChain(SDNode *N, SDValue Chain);
372
373     /// Holds a pointer to an LSBaseSDNode as well as information on where it
374     /// is located in a sequence of memory operations connected by a chain.
375     struct MemOpLink {
376       MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
377       MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
378       // Ptr to the mem node.
379       LSBaseSDNode *MemNode;
380       // Offset from the base ptr.
381       int64_t OffsetFromBase;
382       // What is the sequence number of this mem node.
383       // Lowest mem operand in the DAG starts at zero.
384       unsigned SequenceNum;
385     };
386
387     /// This is a helper function for MergeConsecutiveStores. When the source
388     /// elements of the consecutive stores are all constants or all extracted
389     /// vector elements, try to merge them into one larger store.
390     /// \return True if a merged store was created.
391     bool MergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
392                                          EVT MemVT, unsigned NumElem,
393                                          bool IsConstantSrc, bool UseVector);
394
395     /// Merge consecutive store operations into a wide store.
396     /// This optimization uses wide integers or vectors when possible.
397     /// \return True if some memory operations were changed.
398     bool MergeConsecutiveStores(StoreSDNode *N);
399
400     /// \brief Try to transform a truncation where C is a constant:
401     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
402     ///
403     /// \p N needs to be a truncation and its first operand an AND. Other
404     /// requirements are checked by the function (e.g. that trunc is
405     /// single-use) and if missed an empty SDValue is returned.
406     SDValue distributeTruncateThroughAnd(SDNode *N);
407
408   public:
409     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
410         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
411           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
412       auto *F = DAG.getMachineFunction().getFunction();
413       ForCodeSize = F->hasFnAttribute(Attribute::OptimizeForSize) ||
414                     F->hasFnAttribute(Attribute::MinSize);
415     }
416
417     /// Runs the dag combiner on all nodes in the work list
418     void Run(CombineLevel AtLevel);
419
420     SelectionDAG &getDAG() const { return DAG; }
421
422     /// Returns a type large enough to hold any valid shift amount - before type
423     /// legalization these can be huge.
424     EVT getShiftAmountTy(EVT LHSTy) {
425       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
426       if (LHSTy.isVector())
427         return LHSTy;
428       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
429                         : TLI.getPointerTy();
430     }
431
432     /// This method returns true if we are running before type legalization or
433     /// if the specified VT is legal.
434     bool isTypeLegal(const EVT &VT) {
435       if (!LegalTypes) return true;
436       return TLI.isTypeLegal(VT);
437     }
438
439     /// Convenience wrapper around TargetLowering::getSetCCResultType
440     EVT getSetCCResultType(EVT VT) const {
441       return TLI.getSetCCResultType(*DAG.getContext(), VT);
442     }
443   };
444 }
445
446
447 namespace {
448 /// This class is a DAGUpdateListener that removes any deleted
449 /// nodes from the worklist.
450 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
451   DAGCombiner &DC;
452 public:
453   explicit WorklistRemover(DAGCombiner &dc)
454     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
455
456   void NodeDeleted(SDNode *N, SDNode *E) override {
457     DC.removeFromWorklist(N);
458   }
459 };
460 }
461
462 //===----------------------------------------------------------------------===//
463 //  TargetLowering::DAGCombinerInfo implementation
464 //===----------------------------------------------------------------------===//
465
466 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
467   ((DAGCombiner*)DC)->AddToWorklist(N);
468 }
469
470 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
471   ((DAGCombiner*)DC)->removeFromWorklist(N);
472 }
473
474 SDValue TargetLowering::DAGCombinerInfo::
475 CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
476   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
477 }
478
479 SDValue TargetLowering::DAGCombinerInfo::
480 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
481   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
482 }
483
484
485 SDValue TargetLowering::DAGCombinerInfo::
486 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
487   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
488 }
489
490 void TargetLowering::DAGCombinerInfo::
491 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
492   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
493 }
494
495 //===----------------------------------------------------------------------===//
496 // Helper Functions
497 //===----------------------------------------------------------------------===//
498
499 void DAGCombiner::deleteAndRecombine(SDNode *N) {
500   removeFromWorklist(N);
501
502   // If the operands of this node are only used by the node, they will now be
503   // dead. Make sure to re-visit them and recursively delete dead nodes.
504   for (const SDValue &Op : N->ops())
505     // For an operand generating multiple values, one of the values may
506     // become dead allowing further simplification (e.g. split index
507     // arithmetic from an indexed load).
508     if (Op->hasOneUse() || Op->getNumValues() > 1)
509       AddToWorklist(Op.getNode());
510
511   DAG.DeleteNode(N);
512 }
513
514 /// Return 1 if we can compute the negated form of the specified expression for
515 /// the same cost as the expression itself, or 2 if we can compute the negated
516 /// form more cheaply than the expression itself.
517 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
518                                const TargetLowering &TLI,
519                                const TargetOptions *Options,
520                                unsigned Depth = 0) {
521   // fneg is removable even if it has multiple uses.
522   if (Op.getOpcode() == ISD::FNEG) return 2;
523
524   // Don't allow anything with multiple uses.
525   if (!Op.hasOneUse()) return 0;
526
527   // Don't recurse exponentially.
528   if (Depth > 6) return 0;
529
530   switch (Op.getOpcode()) {
531   default: return false;
532   case ISD::ConstantFP:
533     // Don't invert constant FP values after legalize.  The negated constant
534     // isn't necessarily legal.
535     return LegalOperations ? 0 : 1;
536   case ISD::FADD:
537     // FIXME: determine better conditions for this xform.
538     if (!Options->UnsafeFPMath) return 0;
539
540     // After operation legalization, it might not be legal to create new FSUBs.
541     if (LegalOperations &&
542         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
543       return 0;
544
545     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
546     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
547                                     Options, Depth + 1))
548       return V;
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
551                               Depth + 1);
552   case ISD::FSUB:
553     // We can't turn -(A-B) into B-A when we honor signed zeros.
554     if (!Options->UnsafeFPMath) return 0;
555
556     // fold (fneg (fsub A, B)) -> (fsub B, A)
557     return 1;
558
559   case ISD::FMUL:
560   case ISD::FDIV:
561     if (Options->HonorSignDependentRoundingFPMath()) return 0;
562
563     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
564     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
565                                     Options, Depth + 1))
566       return V;
567
568     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
569                               Depth + 1);
570
571   case ISD::FP_EXTEND:
572   case ISD::FP_ROUND:
573   case ISD::FSIN:
574     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
575                               Depth + 1);
576   }
577 }
578
579 /// If isNegatibleForFree returns true, return the newly negated expression.
580 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
581                                     bool LegalOperations, unsigned Depth = 0) {
582   const TargetOptions &Options = DAG.getTarget().Options;
583   // fneg is removable even if it has multiple uses.
584   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
585
586   // Don't allow anything with multiple uses.
587   assert(Op.hasOneUse() && "Unknown reuse!");
588
589   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
590   switch (Op.getOpcode()) {
591   default: llvm_unreachable("Unknown code");
592   case ISD::ConstantFP: {
593     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
594     V.changeSign();
595     return DAG.getConstantFP(V, SDLoc(Op), Op.getValueType());
596   }
597   case ISD::FADD:
598     // FIXME: determine better conditions for this xform.
599     assert(Options.UnsafeFPMath);
600
601     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
602     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
603                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
604       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
605                          GetNegatedExpression(Op.getOperand(0), DAG,
606                                               LegalOperations, Depth+1),
607                          Op.getOperand(1));
608     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
609     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
610                        GetNegatedExpression(Op.getOperand(1), DAG,
611                                             LegalOperations, Depth+1),
612                        Op.getOperand(0));
613   case ISD::FSUB:
614     // We can't turn -(A-B) into B-A when we honor signed zeros.
615     assert(Options.UnsafeFPMath);
616
617     // fold (fneg (fsub 0, B)) -> B
618     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
619       if (N0CFP->getValueAPF().isZero())
620         return Op.getOperand(1);
621
622     // fold (fneg (fsub A, B)) -> (fsub B, A)
623     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
624                        Op.getOperand(1), Op.getOperand(0));
625
626   case ISD::FMUL:
627   case ISD::FDIV:
628     assert(!Options.HonorSignDependentRoundingFPMath());
629
630     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
631     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
632                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
633       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
634                          GetNegatedExpression(Op.getOperand(0), DAG,
635                                               LegalOperations, Depth+1),
636                          Op.getOperand(1));
637
638     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
639     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
640                        Op.getOperand(0),
641                        GetNegatedExpression(Op.getOperand(1), DAG,
642                                             LegalOperations, Depth+1));
643
644   case ISD::FP_EXTEND:
645   case ISD::FSIN:
646     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
647                        GetNegatedExpression(Op.getOperand(0), DAG,
648                                             LegalOperations, Depth+1));
649   case ISD::FP_ROUND:
650       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
651                          GetNegatedExpression(Op.getOperand(0), DAG,
652                                               LegalOperations, Depth+1),
653                          Op.getOperand(1));
654   }
655 }
656
657 // Return true if this node is a setcc, or is a select_cc
658 // that selects between the target values used for true and false, making it
659 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
660 // the appropriate nodes based on the type of node we are checking. This
661 // simplifies life a bit for the callers.
662 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
663                                     SDValue &CC) const {
664   if (N.getOpcode() == ISD::SETCC) {
665     LHS = N.getOperand(0);
666     RHS = N.getOperand(1);
667     CC  = N.getOperand(2);
668     return true;
669   }
670
671   if (N.getOpcode() != ISD::SELECT_CC ||
672       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
673       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
674     return false;
675
676   if (TLI.getBooleanContents(N.getValueType()) ==
677       TargetLowering::UndefinedBooleanContent)
678     return false;
679
680   LHS = N.getOperand(0);
681   RHS = N.getOperand(1);
682   CC  = N.getOperand(4);
683   return true;
684 }
685
686 /// Return true if this is a SetCC-equivalent operation with only one use.
687 /// If this is true, it allows the users to invert the operation for free when
688 /// it is profitable to do so.
689 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
690   SDValue N0, N1, N2;
691   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
692     return true;
693   return false;
694 }
695
696 /// Returns true if N is a BUILD_VECTOR node whose
697 /// elements are all the same constant or undefined.
698 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
699   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
700   if (!C)
701     return false;
702
703   APInt SplatUndef;
704   unsigned SplatBitSize;
705   bool HasAnyUndefs;
706   EVT EltVT = N->getValueType(0).getVectorElementType();
707   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
708                              HasAnyUndefs) &&
709           EltVT.getSizeInBits() >= SplatBitSize);
710 }
711
712 // \brief Returns the SDNode if it is a constant integer BuildVector
713 // or constant integer.
714 static SDNode *isConstantIntBuildVectorOrConstantInt(SDValue N) {
715   if (isa<ConstantSDNode>(N))
716     return N.getNode();
717   if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
718     return N.getNode();
719   return nullptr;
720 }
721
722 // \brief Returns the SDNode if it is a constant float BuildVector
723 // or constant float.
724 static SDNode *isConstantFPBuildVectorOrConstantFP(SDValue N) {
725   if (isa<ConstantFPSDNode>(N))
726     return N.getNode();
727   if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
728     return N.getNode();
729   return nullptr;
730 }
731
732 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
733 // int.
734 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
735   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
736     return CN;
737
738   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
739     BitVector UndefElements;
740     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
741
742     // BuildVectors can truncate their operands. Ignore that case here.
743     // FIXME: We blindly ignore splats which include undef which is overly
744     // pessimistic.
745     if (CN && UndefElements.none() &&
746         CN->getValueType(0) == N.getValueType().getScalarType())
747       return CN;
748   }
749
750   return nullptr;
751 }
752
753 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
754 // float.
755 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
756   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
757     return CN;
758
759   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
760     BitVector UndefElements;
761     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
762
763     if (CN && UndefElements.none())
764       return CN;
765   }
766
767   return nullptr;
768 }
769
770 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
771                                     SDValue N0, SDValue N1) {
772   EVT VT = N0.getValueType();
773   if (N0.getOpcode() == Opc) {
774     if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0.getOperand(1))) {
775       if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1)) {
776         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
777         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, L, R))
778           return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
779         return SDValue();
780       }
781       if (N0.hasOneUse()) {
782         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
783         // use
784         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
785         if (!OpNode.getNode())
786           return SDValue();
787         AddToWorklist(OpNode.getNode());
788         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
789       }
790     }
791   }
792
793   if (N1.getOpcode() == Opc) {
794     if (SDNode *R = isConstantIntBuildVectorOrConstantInt(N1.getOperand(1))) {
795       if (SDNode *L = isConstantIntBuildVectorOrConstantInt(N0)) {
796         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
797         if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, R, L))
798           return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
799         return SDValue();
800       }
801       if (N1.hasOneUse()) {
802         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
803         // use
804         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
805         if (!OpNode.getNode())
806           return SDValue();
807         AddToWorklist(OpNode.getNode());
808         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
809       }
810     }
811   }
812
813   return SDValue();
814 }
815
816 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
817                                bool AddTo) {
818   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
819   ++NodesCombined;
820   DEBUG(dbgs() << "\nReplacing.1 ";
821         N->dump(&DAG);
822         dbgs() << "\nWith: ";
823         To[0].getNode()->dump(&DAG);
824         dbgs() << " and " << NumTo-1 << " other values\n");
825   for (unsigned i = 0, e = NumTo; i != e; ++i)
826     assert((!To[i].getNode() ||
827             N->getValueType(i) == To[i].getValueType()) &&
828            "Cannot combine value to value of different type!");
829
830   WorklistRemover DeadNodes(*this);
831   DAG.ReplaceAllUsesWith(N, To);
832   if (AddTo) {
833     // Push the new nodes and any users onto the worklist
834     for (unsigned i = 0, e = NumTo; i != e; ++i) {
835       if (To[i].getNode()) {
836         AddToWorklist(To[i].getNode());
837         AddUsersToWorklist(To[i].getNode());
838       }
839     }
840   }
841
842   // Finally, if the node is now dead, remove it from the graph.  The node
843   // may not be dead if the replacement process recursively simplified to
844   // something else needing this node.
845   if (N->use_empty())
846     deleteAndRecombine(N);
847   return SDValue(N, 0);
848 }
849
850 void DAGCombiner::
851 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
852   // Replace all uses.  If any nodes become isomorphic to other nodes and
853   // are deleted, make sure to remove them from our worklist.
854   WorklistRemover DeadNodes(*this);
855   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
856
857   // Push the new node and any (possibly new) users onto the worklist.
858   AddToWorklist(TLO.New.getNode());
859   AddUsersToWorklist(TLO.New.getNode());
860
861   // Finally, if the node is now dead, remove it from the graph.  The node
862   // may not be dead if the replacement process recursively simplified to
863   // something else needing this node.
864   if (TLO.Old.getNode()->use_empty())
865     deleteAndRecombine(TLO.Old.getNode());
866 }
867
868 /// Check the specified integer node value to see if it can be simplified or if
869 /// things it uses can be simplified by bit propagation. If so, return true.
870 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
871   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
872   APInt KnownZero, KnownOne;
873   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
874     return false;
875
876   // Revisit the node.
877   AddToWorklist(Op.getNode());
878
879   // Replace the old value with the new one.
880   ++NodesCombined;
881   DEBUG(dbgs() << "\nReplacing.2 ";
882         TLO.Old.getNode()->dump(&DAG);
883         dbgs() << "\nWith: ";
884         TLO.New.getNode()->dump(&DAG);
885         dbgs() << '\n');
886
887   CommitTargetLoweringOpt(TLO);
888   return true;
889 }
890
891 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
892   SDLoc dl(Load);
893   EVT VT = Load->getValueType(0);
894   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
895
896   DEBUG(dbgs() << "\nReplacing.9 ";
897         Load->dump(&DAG);
898         dbgs() << "\nWith: ";
899         Trunc.getNode()->dump(&DAG);
900         dbgs() << '\n');
901   WorklistRemover DeadNodes(*this);
902   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
903   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
904   deleteAndRecombine(Load);
905   AddToWorklist(Trunc.getNode());
906 }
907
908 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
909   Replace = false;
910   SDLoc dl(Op);
911   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
912     EVT MemVT = LD->getMemoryVT();
913     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
914       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
915                                                        : ISD::EXTLOAD)
916       : LD->getExtensionType();
917     Replace = true;
918     return DAG.getExtLoad(ExtType, dl, PVT,
919                           LD->getChain(), LD->getBasePtr(),
920                           MemVT, LD->getMemOperand());
921   }
922
923   unsigned Opc = Op.getOpcode();
924   switch (Opc) {
925   default: break;
926   case ISD::AssertSext:
927     return DAG.getNode(ISD::AssertSext, dl, PVT,
928                        SExtPromoteOperand(Op.getOperand(0), PVT),
929                        Op.getOperand(1));
930   case ISD::AssertZext:
931     return DAG.getNode(ISD::AssertZext, dl, PVT,
932                        ZExtPromoteOperand(Op.getOperand(0), PVT),
933                        Op.getOperand(1));
934   case ISD::Constant: {
935     unsigned ExtOpc =
936       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
937     return DAG.getNode(ExtOpc, dl, PVT, Op);
938   }
939   }
940
941   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
942     return SDValue();
943   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
944 }
945
946 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
947   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
948     return SDValue();
949   EVT OldVT = Op.getValueType();
950   SDLoc dl(Op);
951   bool Replace = false;
952   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
953   if (!NewOp.getNode())
954     return SDValue();
955   AddToWorklist(NewOp.getNode());
956
957   if (Replace)
958     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
959   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
960                      DAG.getValueType(OldVT));
961 }
962
963 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
964   EVT OldVT = Op.getValueType();
965   SDLoc dl(Op);
966   bool Replace = false;
967   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
968   if (!NewOp.getNode())
969     return SDValue();
970   AddToWorklist(NewOp.getNode());
971
972   if (Replace)
973     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
974   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
975 }
976
977 /// Promote the specified integer binary operation if the target indicates it is
978 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
979 /// i32 since i16 instructions are longer.
980 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
981   if (!LegalOperations)
982     return SDValue();
983
984   EVT VT = Op.getValueType();
985   if (VT.isVector() || !VT.isInteger())
986     return SDValue();
987
988   // If operation type is 'undesirable', e.g. i16 on x86, consider
989   // promoting it.
990   unsigned Opc = Op.getOpcode();
991   if (TLI.isTypeDesirableForOp(Opc, VT))
992     return SDValue();
993
994   EVT PVT = VT;
995   // Consult target whether it is a good idea to promote this operation and
996   // what's the right type to promote it to.
997   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
998     assert(PVT != VT && "Don't know what type to promote to!");
999
1000     bool Replace0 = false;
1001     SDValue N0 = Op.getOperand(0);
1002     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
1003     if (!NN0.getNode())
1004       return SDValue();
1005
1006     bool Replace1 = false;
1007     SDValue N1 = Op.getOperand(1);
1008     SDValue NN1;
1009     if (N0 == N1)
1010       NN1 = NN0;
1011     else {
1012       NN1 = PromoteOperand(N1, PVT, Replace1);
1013       if (!NN1.getNode())
1014         return SDValue();
1015     }
1016
1017     AddToWorklist(NN0.getNode());
1018     if (NN1.getNode())
1019       AddToWorklist(NN1.getNode());
1020
1021     if (Replace0)
1022       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
1023     if (Replace1)
1024       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
1025
1026     DEBUG(dbgs() << "\nPromoting ";
1027           Op.getNode()->dump(&DAG));
1028     SDLoc dl(Op);
1029     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1030                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
1031   }
1032   return SDValue();
1033 }
1034
1035 /// Promote the specified integer shift operation if the target indicates it is
1036 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1037 /// i32 since i16 instructions are longer.
1038 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1039   if (!LegalOperations)
1040     return SDValue();
1041
1042   EVT VT = Op.getValueType();
1043   if (VT.isVector() || !VT.isInteger())
1044     return SDValue();
1045
1046   // If operation type is 'undesirable', e.g. i16 on x86, consider
1047   // promoting it.
1048   unsigned Opc = Op.getOpcode();
1049   if (TLI.isTypeDesirableForOp(Opc, VT))
1050     return SDValue();
1051
1052   EVT PVT = VT;
1053   // Consult target whether it is a good idea to promote this operation and
1054   // what's the right type to promote it to.
1055   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056     assert(PVT != VT && "Don't know what type to promote to!");
1057
1058     bool Replace = false;
1059     SDValue N0 = Op.getOperand(0);
1060     if (Opc == ISD::SRA)
1061       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1062     else if (Opc == ISD::SRL)
1063       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1064     else
1065       N0 = PromoteOperand(N0, PVT, Replace);
1066     if (!N0.getNode())
1067       return SDValue();
1068
1069     AddToWorklist(N0.getNode());
1070     if (Replace)
1071       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           Op.getNode()->dump(&DAG));
1075     SDLoc dl(Op);
1076     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1077                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1078   }
1079   return SDValue();
1080 }
1081
1082 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1083   if (!LegalOperations)
1084     return SDValue();
1085
1086   EVT VT = Op.getValueType();
1087   if (VT.isVector() || !VT.isInteger())
1088     return SDValue();
1089
1090   // If operation type is 'undesirable', e.g. i16 on x86, consider
1091   // promoting it.
1092   unsigned Opc = Op.getOpcode();
1093   if (TLI.isTypeDesirableForOp(Opc, VT))
1094     return SDValue();
1095
1096   EVT PVT = VT;
1097   // Consult target whether it is a good idea to promote this operation and
1098   // what's the right type to promote it to.
1099   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1100     assert(PVT != VT && "Don't know what type to promote to!");
1101     // fold (aext (aext x)) -> (aext x)
1102     // fold (aext (zext x)) -> (zext x)
1103     // fold (aext (sext x)) -> (sext x)
1104     DEBUG(dbgs() << "\nPromoting ";
1105           Op.getNode()->dump(&DAG));
1106     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1107   }
1108   return SDValue();
1109 }
1110
1111 bool DAGCombiner::PromoteLoad(SDValue Op) {
1112   if (!LegalOperations)
1113     return false;
1114
1115   EVT VT = Op.getValueType();
1116   if (VT.isVector() || !VT.isInteger())
1117     return false;
1118
1119   // If operation type is 'undesirable', e.g. i16 on x86, consider
1120   // promoting it.
1121   unsigned Opc = Op.getOpcode();
1122   if (TLI.isTypeDesirableForOp(Opc, VT))
1123     return false;
1124
1125   EVT PVT = VT;
1126   // Consult target whether it is a good idea to promote this operation and
1127   // what's the right type to promote it to.
1128   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1129     assert(PVT != VT && "Don't know what type to promote to!");
1130
1131     SDLoc dl(Op);
1132     SDNode *N = Op.getNode();
1133     LoadSDNode *LD = cast<LoadSDNode>(N);
1134     EVT MemVT = LD->getMemoryVT();
1135     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1136       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1137                                                        : ISD::EXTLOAD)
1138       : LD->getExtensionType();
1139     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1140                                    LD->getChain(), LD->getBasePtr(),
1141                                    MemVT, LD->getMemOperand());
1142     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1143
1144     DEBUG(dbgs() << "\nPromoting ";
1145           N->dump(&DAG);
1146           dbgs() << "\nTo: ";
1147           Result.getNode()->dump(&DAG);
1148           dbgs() << '\n');
1149     WorklistRemover DeadNodes(*this);
1150     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1151     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1152     deleteAndRecombine(N);
1153     AddToWorklist(Result.getNode());
1154     return true;
1155   }
1156   return false;
1157 }
1158
1159 /// \brief Recursively delete a node which has no uses and any operands for
1160 /// which it is the only use.
1161 ///
1162 /// Note that this both deletes the nodes and removes them from the worklist.
1163 /// It also adds any nodes who have had a user deleted to the worklist as they
1164 /// may now have only one use and subject to other combines.
1165 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1166   if (!N->use_empty())
1167     return false;
1168
1169   SmallSetVector<SDNode *, 16> Nodes;
1170   Nodes.insert(N);
1171   do {
1172     N = Nodes.pop_back_val();
1173     if (!N)
1174       continue;
1175
1176     if (N->use_empty()) {
1177       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1178         Nodes.insert(N->getOperand(i).getNode());
1179
1180       removeFromWorklist(N);
1181       DAG.DeleteNode(N);
1182     } else {
1183       AddToWorklist(N);
1184     }
1185   } while (!Nodes.empty());
1186   return true;
1187 }
1188
1189 //===----------------------------------------------------------------------===//
1190 //  Main DAG Combiner implementation
1191 //===----------------------------------------------------------------------===//
1192
1193 void DAGCombiner::Run(CombineLevel AtLevel) {
1194   // set the instance variables, so that the various visit routines may use it.
1195   Level = AtLevel;
1196   LegalOperations = Level >= AfterLegalizeVectorOps;
1197   LegalTypes = Level >= AfterLegalizeTypes;
1198
1199   // Add all the dag nodes to the worklist.
1200   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1201        E = DAG.allnodes_end(); I != E; ++I)
1202     AddToWorklist(I);
1203
1204   // Create a dummy node (which is not added to allnodes), that adds a reference
1205   // to the root node, preventing it from being deleted, and tracking any
1206   // changes of the root.
1207   HandleSDNode Dummy(DAG.getRoot());
1208
1209   // while the worklist isn't empty, find a node and
1210   // try and combine it.
1211   while (!WorklistMap.empty()) {
1212     SDNode *N;
1213     // The Worklist holds the SDNodes in order, but it may contain null entries.
1214     do {
1215       N = Worklist.pop_back_val();
1216     } while (!N);
1217
1218     bool GoodWorklistEntry = WorklistMap.erase(N);
1219     (void)GoodWorklistEntry;
1220     assert(GoodWorklistEntry &&
1221            "Found a worklist entry without a corresponding map entry!");
1222
1223     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1224     // N is deleted from the DAG, since they too may now be dead or may have a
1225     // reduced number of uses, allowing other xforms.
1226     if (recursivelyDeleteUnusedNodes(N))
1227       continue;
1228
1229     WorklistRemover DeadNodes(*this);
1230
1231     // If this combine is running after legalizing the DAG, re-legalize any
1232     // nodes pulled off the worklist.
1233     if (Level == AfterLegalizeDAG) {
1234       SmallSetVector<SDNode *, 16> UpdatedNodes;
1235       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1236
1237       for (SDNode *LN : UpdatedNodes) {
1238         AddToWorklist(LN);
1239         AddUsersToWorklist(LN);
1240       }
1241       if (!NIsValid)
1242         continue;
1243     }
1244
1245     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1246
1247     // Add any operands of the new node which have not yet been combined to the
1248     // worklist as well. Because the worklist uniques things already, this
1249     // won't repeatedly process the same operand.
1250     CombinedNodes.insert(N);
1251     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1252       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1253         AddToWorklist(N->getOperand(i).getNode());
1254
1255     SDValue RV = combine(N);
1256
1257     if (!RV.getNode())
1258       continue;
1259
1260     ++NodesCombined;
1261
1262     // If we get back the same node we passed in, rather than a new node or
1263     // zero, we know that the node must have defined multiple values and
1264     // CombineTo was used.  Since CombineTo takes care of the worklist
1265     // mechanics for us, we have no work to do in this case.
1266     if (RV.getNode() == N)
1267       continue;
1268
1269     assert(N->getOpcode() != ISD::DELETED_NODE &&
1270            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1271            "Node was deleted but visit returned new node!");
1272
1273     DEBUG(dbgs() << " ... into: ";
1274           RV.getNode()->dump(&DAG));
1275
1276     // Transfer debug value.
1277     DAG.TransferDbgValues(SDValue(N, 0), RV);
1278     if (N->getNumValues() == RV.getNode()->getNumValues())
1279       DAG.ReplaceAllUsesWith(N, RV.getNode());
1280     else {
1281       assert(N->getValueType(0) == RV.getValueType() &&
1282              N->getNumValues() == 1 && "Type mismatch");
1283       SDValue OpV = RV;
1284       DAG.ReplaceAllUsesWith(N, &OpV);
1285     }
1286
1287     // Push the new node and any users onto the worklist
1288     AddToWorklist(RV.getNode());
1289     AddUsersToWorklist(RV.getNode());
1290
1291     // Finally, if the node is now dead, remove it from the graph.  The node
1292     // may not be dead if the replacement process recursively simplified to
1293     // something else needing this node. This will also take care of adding any
1294     // operands which have lost a user to the worklist.
1295     recursivelyDeleteUnusedNodes(N);
1296   }
1297
1298   // If the root changed (e.g. it was a dead load, update the root).
1299   DAG.setRoot(Dummy.getValue());
1300   DAG.RemoveDeadNodes();
1301 }
1302
1303 SDValue DAGCombiner::visit(SDNode *N) {
1304   switch (N->getOpcode()) {
1305   default: break;
1306   case ISD::TokenFactor:        return visitTokenFactor(N);
1307   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1308   case ISD::ADD:                return visitADD(N);
1309   case ISD::SUB:                return visitSUB(N);
1310   case ISD::ADDC:               return visitADDC(N);
1311   case ISD::SUBC:               return visitSUBC(N);
1312   case ISD::ADDE:               return visitADDE(N);
1313   case ISD::SUBE:               return visitSUBE(N);
1314   case ISD::MUL:                return visitMUL(N);
1315   case ISD::SDIV:               return visitSDIV(N);
1316   case ISD::UDIV:               return visitUDIV(N);
1317   case ISD::SREM:               return visitSREM(N);
1318   case ISD::UREM:               return visitUREM(N);
1319   case ISD::MULHU:              return visitMULHU(N);
1320   case ISD::MULHS:              return visitMULHS(N);
1321   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1322   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1323   case ISD::SMULO:              return visitSMULO(N);
1324   case ISD::UMULO:              return visitUMULO(N);
1325   case ISD::SDIVREM:            return visitSDIVREM(N);
1326   case ISD::UDIVREM:            return visitUDIVREM(N);
1327   case ISD::AND:                return visitAND(N);
1328   case ISD::OR:                 return visitOR(N);
1329   case ISD::XOR:                return visitXOR(N);
1330   case ISD::SHL:                return visitSHL(N);
1331   case ISD::SRA:                return visitSRA(N);
1332   case ISD::SRL:                return visitSRL(N);
1333   case ISD::ROTR:
1334   case ISD::ROTL:               return visitRotate(N);
1335   case ISD::CTLZ:               return visitCTLZ(N);
1336   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1337   case ISD::CTTZ:               return visitCTTZ(N);
1338   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1339   case ISD::CTPOP:              return visitCTPOP(N);
1340   case ISD::SELECT:             return visitSELECT(N);
1341   case ISD::VSELECT:            return visitVSELECT(N);
1342   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1343   case ISD::SETCC:              return visitSETCC(N);
1344   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1345   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1346   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1347   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1348   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1349   case ISD::BITCAST:            return visitBITCAST(N);
1350   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1351   case ISD::FADD:               return visitFADD(N);
1352   case ISD::FSUB:               return visitFSUB(N);
1353   case ISD::FMUL:               return visitFMUL(N);
1354   case ISD::FMA:                return visitFMA(N);
1355   case ISD::FDIV:               return visitFDIV(N);
1356   case ISD::FREM:               return visitFREM(N);
1357   case ISD::FSQRT:              return visitFSQRT(N);
1358   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1359   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1360   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1361   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1362   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1363   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1364   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1365   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1366   case ISD::FNEG:               return visitFNEG(N);
1367   case ISD::FABS:               return visitFABS(N);
1368   case ISD::FFLOOR:             return visitFFLOOR(N);
1369   case ISD::FMINNUM:            return visitFMINNUM(N);
1370   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1371   case ISD::FCEIL:              return visitFCEIL(N);
1372   case ISD::FTRUNC:             return visitFTRUNC(N);
1373   case ISD::BRCOND:             return visitBRCOND(N);
1374   case ISD::BR_CC:              return visitBR_CC(N);
1375   case ISD::LOAD:               return visitLOAD(N);
1376   case ISD::STORE:              return visitSTORE(N);
1377   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1378   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1379   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1380   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1381   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1382   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1383   case ISD::SCALAR_TO_VECTOR:   return visitSCALAR_TO_VECTOR(N);
1384   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1385   case ISD::MLOAD:              return visitMLOAD(N);
1386   case ISD::MSTORE:             return visitMSTORE(N);
1387   case ISD::FP_TO_FP16:         return visitFP_TO_FP16(N);
1388   }
1389   return SDValue();
1390 }
1391
1392 SDValue DAGCombiner::combine(SDNode *N) {
1393   SDValue RV = visit(N);
1394
1395   // If nothing happened, try a target-specific DAG combine.
1396   if (!RV.getNode()) {
1397     assert(N->getOpcode() != ISD::DELETED_NODE &&
1398            "Node was deleted but visit returned NULL!");
1399
1400     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1401         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1402
1403       // Expose the DAG combiner to the target combiner impls.
1404       TargetLowering::DAGCombinerInfo
1405         DagCombineInfo(DAG, Level, false, this);
1406
1407       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1408     }
1409   }
1410
1411   // If nothing happened still, try promoting the operation.
1412   if (!RV.getNode()) {
1413     switch (N->getOpcode()) {
1414     default: break;
1415     case ISD::ADD:
1416     case ISD::SUB:
1417     case ISD::MUL:
1418     case ISD::AND:
1419     case ISD::OR:
1420     case ISD::XOR:
1421       RV = PromoteIntBinOp(SDValue(N, 0));
1422       break;
1423     case ISD::SHL:
1424     case ISD::SRA:
1425     case ISD::SRL:
1426       RV = PromoteIntShiftOp(SDValue(N, 0));
1427       break;
1428     case ISD::SIGN_EXTEND:
1429     case ISD::ZERO_EXTEND:
1430     case ISD::ANY_EXTEND:
1431       RV = PromoteExtend(SDValue(N, 0));
1432       break;
1433     case ISD::LOAD:
1434       if (PromoteLoad(SDValue(N, 0)))
1435         RV = SDValue(N, 0);
1436       break;
1437     }
1438   }
1439
1440   // If N is a commutative binary node, try commuting it to enable more
1441   // sdisel CSE.
1442   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1443       N->getNumValues() == 1) {
1444     SDValue N0 = N->getOperand(0);
1445     SDValue N1 = N->getOperand(1);
1446
1447     // Constant operands are canonicalized to RHS.
1448     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1449       SDValue Ops[] = {N1, N0};
1450       SDNode *CSENode;
1451       if (const BinaryWithFlagsSDNode *BinNode =
1452               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1453         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
1454                                       BinNode->Flags.hasNoUnsignedWrap(),
1455                                       BinNode->Flags.hasNoSignedWrap(),
1456                                       BinNode->Flags.hasExact());
1457       } else {
1458         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1459       }
1460       if (CSENode)
1461         return SDValue(CSENode, 0);
1462     }
1463   }
1464
1465   return RV;
1466 }
1467
1468 /// Given a node, return its input chain if it has one, otherwise return a null
1469 /// sd operand.
1470 static SDValue getInputChainForNode(SDNode *N) {
1471   if (unsigned NumOps = N->getNumOperands()) {
1472     if (N->getOperand(0).getValueType() == MVT::Other)
1473       return N->getOperand(0);
1474     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1475       return N->getOperand(NumOps-1);
1476     for (unsigned i = 1; i < NumOps-1; ++i)
1477       if (N->getOperand(i).getValueType() == MVT::Other)
1478         return N->getOperand(i);
1479   }
1480   return SDValue();
1481 }
1482
1483 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1484   // If N has two operands, where one has an input chain equal to the other,
1485   // the 'other' chain is redundant.
1486   if (N->getNumOperands() == 2) {
1487     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1488       return N->getOperand(0);
1489     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1490       return N->getOperand(1);
1491   }
1492
1493   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1494   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1495   SmallPtrSet<SDNode*, 16> SeenOps;
1496   bool Changed = false;             // If we should replace this token factor.
1497
1498   // Start out with this token factor.
1499   TFs.push_back(N);
1500
1501   // Iterate through token factors.  The TFs grows when new token factors are
1502   // encountered.
1503   for (unsigned i = 0; i < TFs.size(); ++i) {
1504     SDNode *TF = TFs[i];
1505
1506     // Check each of the operands.
1507     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1508       SDValue Op = TF->getOperand(i);
1509
1510       switch (Op.getOpcode()) {
1511       case ISD::EntryToken:
1512         // Entry tokens don't need to be added to the list. They are
1513         // redundant.
1514         Changed = true;
1515         break;
1516
1517       case ISD::TokenFactor:
1518         if (Op.hasOneUse() &&
1519             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1520           // Queue up for processing.
1521           TFs.push_back(Op.getNode());
1522           // Clean up in case the token factor is removed.
1523           AddToWorklist(Op.getNode());
1524           Changed = true;
1525           break;
1526         }
1527         // Fall thru
1528
1529       default:
1530         // Only add if it isn't already in the list.
1531         if (SeenOps.insert(Op.getNode()).second)
1532           Ops.push_back(Op);
1533         else
1534           Changed = true;
1535         break;
1536       }
1537     }
1538   }
1539
1540   SDValue Result;
1541
1542   // If we've changed things around then replace token factor.
1543   if (Changed) {
1544     if (Ops.empty()) {
1545       // The entry token is the only possible outcome.
1546       Result = DAG.getEntryNode();
1547     } else {
1548       // New and improved token factor.
1549       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1550     }
1551
1552     // Add users to worklist if AA is enabled, since it may introduce
1553     // a lot of new chained token factors while removing memory deps.
1554     bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
1555       : DAG.getSubtarget().useAA();
1556     return CombineTo(N, Result, UseAA /*add to worklist*/);
1557   }
1558
1559   return Result;
1560 }
1561
1562 /// MERGE_VALUES can always be eliminated.
1563 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1564   WorklistRemover DeadNodes(*this);
1565   // Replacing results may cause a different MERGE_VALUES to suddenly
1566   // be CSE'd with N, and carry its uses with it. Iterate until no
1567   // uses remain, to ensure that the node can be safely deleted.
1568   // First add the users of this node to the work list so that they
1569   // can be tried again once they have new operands.
1570   AddUsersToWorklist(N);
1571   do {
1572     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1573       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1574   } while (!N->use_empty());
1575   deleteAndRecombine(N);
1576   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1577 }
1578
1579 SDValue DAGCombiner::visitADD(SDNode *N) {
1580   SDValue N0 = N->getOperand(0);
1581   SDValue N1 = N->getOperand(1);
1582   EVT VT = N0.getValueType();
1583
1584   // fold vector ops
1585   if (VT.isVector()) {
1586     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1587       return FoldedVOp;
1588
1589     // fold (add x, 0) -> x, vector edition
1590     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1591       return N0;
1592     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1593       return N1;
1594   }
1595
1596   // fold (add x, undef) -> undef
1597   if (N0.getOpcode() == ISD::UNDEF)
1598     return N0;
1599   if (N1.getOpcode() == ISD::UNDEF)
1600     return N1;
1601   // fold (add c1, c2) -> c1+c2
1602   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1603   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1604   if (N0C && N1C)
1605     return DAG.FoldConstantArithmetic(ISD::ADD, SDLoc(N), VT, N0C, N1C);
1606   // canonicalize constant to RHS
1607   if (isConstantIntBuildVectorOrConstantInt(N0) &&
1608      !isConstantIntBuildVectorOrConstantInt(N1))
1609     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1610   // fold (add x, 0) -> x
1611   if (N1C && N1C->isNullValue())
1612     return N0;
1613   // fold (add Sym, c) -> Sym+c
1614   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1615     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1616         GA->getOpcode() == ISD::GlobalAddress)
1617       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1618                                   GA->getOffset() +
1619                                     (uint64_t)N1C->getSExtValue());
1620   // fold ((c1-A)+c2) -> (c1+c2)-A
1621   if (N1C && N0.getOpcode() == ISD::SUB)
1622     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0))) {
1623       SDLoc DL(N);
1624       return DAG.getNode(ISD::SUB, DL, VT,
1625                          DAG.getConstant(N1C->getAPIntValue()+
1626                                          N0C->getAPIntValue(), DL, VT),
1627                          N0.getOperand(1));
1628     }
1629   // reassociate add
1630   if (SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1))
1631     return RADD;
1632   // fold ((0-A) + B) -> B-A
1633   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1634       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1635     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1636   // fold (A + (0-B)) -> A-B
1637   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1638       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1639     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1640   // fold (A+(B-A)) -> B
1641   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1642     return N1.getOperand(0);
1643   // fold ((B-A)+A) -> B
1644   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1645     return N0.getOperand(0);
1646   // fold (A+(B-(A+C))) to (B-C)
1647   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1648       N0 == N1.getOperand(1).getOperand(0))
1649     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1650                        N1.getOperand(1).getOperand(1));
1651   // fold (A+(B-(C+A))) to (B-C)
1652   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1653       N0 == N1.getOperand(1).getOperand(1))
1654     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1655                        N1.getOperand(1).getOperand(0));
1656   // fold (A+((B-A)+or-C)) to (B+or-C)
1657   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1658       N1.getOperand(0).getOpcode() == ISD::SUB &&
1659       N0 == N1.getOperand(0).getOperand(1))
1660     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1661                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1662
1663   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1664   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1665     SDValue N00 = N0.getOperand(0);
1666     SDValue N01 = N0.getOperand(1);
1667     SDValue N10 = N1.getOperand(0);
1668     SDValue N11 = N1.getOperand(1);
1669
1670     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1671       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1672                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1673                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1674   }
1675
1676   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1677     return SDValue(N, 0);
1678
1679   // fold (a+b) -> (a|b) iff a and b share no bits.
1680   if (VT.isInteger() && !VT.isVector()) {
1681     APInt LHSZero, LHSOne;
1682     APInt RHSZero, RHSOne;
1683     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1684
1685     if (LHSZero.getBoolValue()) {
1686       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1687
1688       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1689       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1690       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1691         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1692           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1693       }
1694     }
1695   }
1696
1697   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1698   if (N1.getOpcode() == ISD::SHL &&
1699       N1.getOperand(0).getOpcode() == ISD::SUB)
1700     if (ConstantSDNode *C =
1701           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1702       if (C->getAPIntValue() == 0)
1703         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1704                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1705                                        N1.getOperand(0).getOperand(1),
1706                                        N1.getOperand(1)));
1707   if (N0.getOpcode() == ISD::SHL &&
1708       N0.getOperand(0).getOpcode() == ISD::SUB)
1709     if (ConstantSDNode *C =
1710           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1711       if (C->getAPIntValue() == 0)
1712         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1713                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1714                                        N0.getOperand(0).getOperand(1),
1715                                        N0.getOperand(1)));
1716
1717   if (N1.getOpcode() == ISD::AND) {
1718     SDValue AndOp0 = N1.getOperand(0);
1719     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1720     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1721     unsigned DestBits = VT.getScalarType().getSizeInBits();
1722
1723     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1724     // and similar xforms where the inner op is either ~0 or 0.
1725     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1726       SDLoc DL(N);
1727       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1728     }
1729   }
1730
1731   // add (sext i1), X -> sub X, (zext i1)
1732   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1733       N0.getOperand(0).getValueType() == MVT::i1 &&
1734       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1735     SDLoc DL(N);
1736     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1737     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1738   }
1739
1740   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1741   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1742     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1743     if (TN->getVT() == MVT::i1) {
1744       SDLoc DL(N);
1745       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1746                                  DAG.getConstant(1, DL, VT));
1747       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1748     }
1749   }
1750
1751   return SDValue();
1752 }
1753
1754 SDValue DAGCombiner::visitADDC(SDNode *N) {
1755   SDValue N0 = N->getOperand(0);
1756   SDValue N1 = N->getOperand(1);
1757   EVT VT = N0.getValueType();
1758
1759   // If the flag result is dead, turn this into an ADD.
1760   if (!N->hasAnyUseOfValue(1))
1761     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1762                      DAG.getNode(ISD::CARRY_FALSE,
1763                                  SDLoc(N), MVT::Glue));
1764
1765   // canonicalize constant to RHS.
1766   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1767   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1770
1771   // fold (addc x, 0) -> x + no carry out
1772   if (N1C && N1C->isNullValue())
1773     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1774                                         SDLoc(N), MVT::Glue));
1775
1776   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1777   APInt LHSZero, LHSOne;
1778   APInt RHSZero, RHSOne;
1779   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1780
1781   if (LHSZero.getBoolValue()) {
1782     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1783
1784     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1785     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1786     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1787       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1788                        DAG.getNode(ISD::CARRY_FALSE,
1789                                    SDLoc(N), MVT::Glue));
1790   }
1791
1792   return SDValue();
1793 }
1794
1795 SDValue DAGCombiner::visitADDE(SDNode *N) {
1796   SDValue N0 = N->getOperand(0);
1797   SDValue N1 = N->getOperand(1);
1798   SDValue CarryIn = N->getOperand(2);
1799
1800   // canonicalize constant to RHS
1801   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1802   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1803   if (N0C && !N1C)
1804     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1805                        N1, N0, CarryIn);
1806
1807   // fold (adde x, y, false) -> (addc x, y)
1808   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1809     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1810
1811   return SDValue();
1812 }
1813
1814 // Since it may not be valid to emit a fold to zero for vector initializers
1815 // check if we can before folding.
1816 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1817                              SelectionDAG &DAG,
1818                              bool LegalOperations, bool LegalTypes) {
1819   if (!VT.isVector())
1820     return DAG.getConstant(0, DL, VT);
1821   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1822     return DAG.getConstant(0, DL, VT);
1823   return SDValue();
1824 }
1825
1826 SDValue DAGCombiner::visitSUB(SDNode *N) {
1827   SDValue N0 = N->getOperand(0);
1828   SDValue N1 = N->getOperand(1);
1829   EVT VT = N0.getValueType();
1830
1831   // fold vector ops
1832   if (VT.isVector()) {
1833     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1834       return FoldedVOp;
1835
1836     // fold (sub x, 0) -> x, vector edition
1837     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1838       return N0;
1839   }
1840
1841   // fold (sub x, x) -> 0
1842   // FIXME: Refactor this and xor and other similar operations together.
1843   if (N0 == N1)
1844     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1845   // fold (sub c1, c2) -> c1-c2
1846   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1847   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1848   if (N0C && N1C)
1849     return DAG.FoldConstantArithmetic(ISD::SUB, SDLoc(N), VT, N0C, N1C);
1850   // fold (sub x, c) -> (add x, -c)
1851   if (N1C) {
1852     SDLoc DL(N);
1853     return DAG.getNode(ISD::ADD, DL, VT, N0,
1854                        DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
1855   }
1856   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1857   if (N0C && N0C->isAllOnesValue())
1858     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1859   // fold A-(A-B) -> B
1860   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1861     return N1.getOperand(1);
1862   // fold (A+B)-A -> B
1863   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1864     return N0.getOperand(1);
1865   // fold (A+B)-B -> A
1866   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1867     return N0.getOperand(0);
1868   // fold C2-(A+C1) -> (C2-C1)-A
1869   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1870     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1871   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1872     SDLoc DL(N);
1873     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1874                                    DL, VT);
1875     return DAG.getNode(ISD::SUB, DL, VT, NewC,
1876                        N1.getOperand(0));
1877   }
1878   // fold ((A+(B+or-C))-B) -> A+or-C
1879   if (N0.getOpcode() == ISD::ADD &&
1880       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1881        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1882       N0.getOperand(1).getOperand(0) == N1)
1883     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1884                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1885   // fold ((A+(C+B))-B) -> A+C
1886   if (N0.getOpcode() == ISD::ADD &&
1887       N0.getOperand(1).getOpcode() == ISD::ADD &&
1888       N0.getOperand(1).getOperand(1) == N1)
1889     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1890                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1891   // fold ((A-(B-C))-C) -> A-B
1892   if (N0.getOpcode() == ISD::SUB &&
1893       N0.getOperand(1).getOpcode() == ISD::SUB &&
1894       N0.getOperand(1).getOperand(1) == N1)
1895     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1896                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1897
1898   // If either operand of a sub is undef, the result is undef
1899   if (N0.getOpcode() == ISD::UNDEF)
1900     return N0;
1901   if (N1.getOpcode() == ISD::UNDEF)
1902     return N1;
1903
1904   // If the relocation model supports it, consider symbol offsets.
1905   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1906     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1907       // fold (sub Sym, c) -> Sym-c
1908       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1909         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1910                                     GA->getOffset() -
1911                                       (uint64_t)N1C->getSExtValue());
1912       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1913       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1914         if (GA->getGlobal() == GB->getGlobal())
1915           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1916                                  SDLoc(N), VT);
1917     }
1918
1919   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1920   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1921     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1922     if (TN->getVT() == MVT::i1) {
1923       SDLoc DL(N);
1924       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1925                                  DAG.getConstant(1, DL, VT));
1926       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1927     }
1928   }
1929
1930   return SDValue();
1931 }
1932
1933 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1934   SDValue N0 = N->getOperand(0);
1935   SDValue N1 = N->getOperand(1);
1936   EVT VT = N0.getValueType();
1937
1938   // If the flag result is dead, turn this into an SUB.
1939   if (!N->hasAnyUseOfValue(1))
1940     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1941                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1942                                  MVT::Glue));
1943
1944   // fold (subc x, x) -> 0 + no borrow
1945   if (N0 == N1) {
1946     SDLoc DL(N);
1947     return CombineTo(N, DAG.getConstant(0, DL, VT),
1948                      DAG.getNode(ISD::CARRY_FALSE, DL,
1949                                  MVT::Glue));
1950   }
1951
1952   // fold (subc x, 0) -> x + no borrow
1953   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1954   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1955   if (N1C && N1C->isNullValue())
1956     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1957                                         MVT::Glue));
1958
1959   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1960   if (N0C && N0C->isAllOnesValue())
1961     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1962                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1963                                  MVT::Glue));
1964
1965   return SDValue();
1966 }
1967
1968 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1969   SDValue N0 = N->getOperand(0);
1970   SDValue N1 = N->getOperand(1);
1971   SDValue CarryIn = N->getOperand(2);
1972
1973   // fold (sube x, y, false) -> (subc x, y)
1974   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1975     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1976
1977   return SDValue();
1978 }
1979
1980 SDValue DAGCombiner::visitMUL(SDNode *N) {
1981   SDValue N0 = N->getOperand(0);
1982   SDValue N1 = N->getOperand(1);
1983   EVT VT = N0.getValueType();
1984
1985   // fold (mul x, undef) -> 0
1986   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1987     return DAG.getConstant(0, SDLoc(N), VT);
1988
1989   bool N0IsConst = false;
1990   bool N1IsConst = false;
1991   APInt ConstValue0, ConstValue1;
1992   // fold vector ops
1993   if (VT.isVector()) {
1994     if (SDValue FoldedVOp = SimplifyVBinOp(N))
1995       return FoldedVOp;
1996
1997     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1998     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1999   } else {
2000     N0IsConst = isa<ConstantSDNode>(N0);
2001     if (N0IsConst)
2002       ConstValue0 = cast<ConstantSDNode>(N0)->getAPIntValue();
2003     N1IsConst = isa<ConstantSDNode>(N1);
2004     if (N1IsConst)
2005       ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
2006   }
2007
2008   // fold (mul c1, c2) -> c1*c2
2009   if (N0IsConst && N1IsConst)
2010     return DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT,
2011                                       N0.getNode(), N1.getNode());
2012
2013   // canonicalize constant to RHS (vector doesn't have to splat)
2014   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2015      !isConstantIntBuildVectorOrConstantInt(N1))
2016     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
2017   // fold (mul x, 0) -> 0
2018   if (N1IsConst && ConstValue1 == 0)
2019     return N1;
2020   // We require a splat of the entire scalar bit width for non-contiguous
2021   // bit patterns.
2022   bool IsFullSplat =
2023     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
2024   // fold (mul x, 1) -> x
2025   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
2026     return N0;
2027   // fold (mul x, -1) -> 0-x
2028   if (N1IsConst && ConstValue1.isAllOnesValue()) {
2029     SDLoc DL(N);
2030     return DAG.getNode(ISD::SUB, DL, VT,
2031                        DAG.getConstant(0, DL, VT), N0);
2032   }
2033   // fold (mul x, (1 << c)) -> x << c
2034   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat) {
2035     SDLoc DL(N);
2036     return DAG.getNode(ISD::SHL, DL, VT, N0,
2037                        DAG.getConstant(ConstValue1.logBase2(), DL,
2038                                        getShiftAmountTy(N0.getValueType())));
2039   }
2040   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
2041   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
2042     unsigned Log2Val = (-ConstValue1).logBase2();
2043     SDLoc DL(N);
2044     // FIXME: If the input is something that is easily negated (e.g. a
2045     // single-use add), we should put the negate there.
2046     return DAG.getNode(ISD::SUB, DL, VT,
2047                        DAG.getConstant(0, DL, VT),
2048                        DAG.getNode(ISD::SHL, DL, VT, N0,
2049                             DAG.getConstant(Log2Val, DL,
2050                                       getShiftAmountTy(N0.getValueType()))));
2051   }
2052
2053   APInt Val;
2054   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2055   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2056       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2057                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2058     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2059                              N1, N0.getOperand(1));
2060     AddToWorklist(C3.getNode());
2061     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2062                        N0.getOperand(0), C3);
2063   }
2064
2065   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2066   // use.
2067   {
2068     SDValue Sh(nullptr,0), Y(nullptr,0);
2069     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2070     if (N0.getOpcode() == ISD::SHL &&
2071         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2072                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2073         N0.getNode()->hasOneUse()) {
2074       Sh = N0; Y = N1;
2075     } else if (N1.getOpcode() == ISD::SHL &&
2076                isa<ConstantSDNode>(N1.getOperand(1)) &&
2077                N1.getNode()->hasOneUse()) {
2078       Sh = N1; Y = N0;
2079     }
2080
2081     if (Sh.getNode()) {
2082       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2083                                 Sh.getOperand(0), Y);
2084       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2085                          Mul, Sh.getOperand(1));
2086     }
2087   }
2088
2089   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2090   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2091       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2092                      isa<ConstantSDNode>(N0.getOperand(1))))
2093     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2094                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2095                                    N0.getOperand(0), N1),
2096                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2097                                    N0.getOperand(1), N1));
2098
2099   // reassociate mul
2100   if (SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1))
2101     return RMUL;
2102
2103   return SDValue();
2104 }
2105
2106 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2107   SDValue N0 = N->getOperand(0);
2108   SDValue N1 = N->getOperand(1);
2109   EVT VT = N->getValueType(0);
2110
2111   // fold vector ops
2112   if (VT.isVector())
2113     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2114       return FoldedVOp;
2115
2116   // fold (sdiv c1, c2) -> c1/c2
2117   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2118   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2119   if (N0C && N1C && !N1C->isNullValue())
2120     return DAG.FoldConstantArithmetic(ISD::SDIV, SDLoc(N), VT, N0C, N1C);
2121   // fold (sdiv X, 1) -> X
2122   if (N1C && N1C->getAPIntValue() == 1LL)
2123     return N0;
2124   // fold (sdiv X, -1) -> 0-X
2125   if (N1C && N1C->isAllOnesValue()) {
2126     SDLoc DL(N);
2127     return DAG.getNode(ISD::SUB, DL, VT,
2128                        DAG.getConstant(0, DL, VT), N0);
2129   }
2130   // If we know the sign bits of both operands are zero, strength reduce to a
2131   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2132   if (!VT.isVector()) {
2133     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2134       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2135                          N0, N1);
2136   }
2137
2138   // fold (sdiv X, pow2) -> simple ops after legalize
2139   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2140                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2141     // If dividing by powers of two is cheap, then don't perform the following
2142     // fold.
2143     if (TLI.isPow2SDivCheap())
2144       return SDValue();
2145
2146     // Target-specific implementation of sdiv x, pow2.
2147     SDValue Res = BuildSDIVPow2(N);
2148     if (Res.getNode())
2149       return Res;
2150
2151     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2152     SDLoc DL(N);
2153
2154     // Splat the sign bit into the register
2155     SDValue SGN =
2156         DAG.getNode(ISD::SRA, DL, VT, N0,
2157                     DAG.getConstant(VT.getScalarSizeInBits() - 1, DL,
2158                                     getShiftAmountTy(N0.getValueType())));
2159     AddToWorklist(SGN.getNode());
2160
2161     // Add (N0 < 0) ? abs2 - 1 : 0;
2162     SDValue SRL =
2163         DAG.getNode(ISD::SRL, DL, VT, SGN,
2164                     DAG.getConstant(VT.getScalarSizeInBits() - lg2, DL,
2165                                     getShiftAmountTy(SGN.getValueType())));
2166     SDValue ADD = DAG.getNode(ISD::ADD, DL, VT, N0, SRL);
2167     AddToWorklist(SRL.getNode());
2168     AddToWorklist(ADD.getNode());    // Divide by pow2
2169     SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, ADD,
2170                   DAG.getConstant(lg2, DL,
2171                                   getShiftAmountTy(ADD.getValueType())));
2172
2173     // If we're dividing by a positive value, we're done.  Otherwise, we must
2174     // negate the result.
2175     if (N1C->getAPIntValue().isNonNegative())
2176       return SRA;
2177
2178     AddToWorklist(SRA.getNode());
2179     return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
2180   }
2181
2182   // If integer divide is expensive and we satisfy the requirements, emit an
2183   // alternate sequence.
2184   if (N1C && !TLI.isIntDivCheap()) {
2185     SDValue Op = BuildSDIV(N);
2186     if (Op.getNode()) return Op;
2187   }
2188
2189   // undef / X -> 0
2190   if (N0.getOpcode() == ISD::UNDEF)
2191     return DAG.getConstant(0, SDLoc(N), VT);
2192   // X / undef -> undef
2193   if (N1.getOpcode() == ISD::UNDEF)
2194     return N1;
2195
2196   return SDValue();
2197 }
2198
2199 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2200   SDValue N0 = N->getOperand(0);
2201   SDValue N1 = N->getOperand(1);
2202   EVT VT = N->getValueType(0);
2203
2204   // fold vector ops
2205   if (VT.isVector())
2206     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2207       return FoldedVOp;
2208
2209   // fold (udiv c1, c2) -> c1/c2
2210   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2211   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2212   if (N0C && N1C && !N1C->isNullValue())
2213     return DAG.FoldConstantArithmetic(ISD::UDIV, SDLoc(N), VT, N0C, N1C);
2214   // fold (udiv x, (1 << c)) -> x >>u c
2215   if (N1C && N1C->getAPIntValue().isPowerOf2()) {
2216     SDLoc DL(N);
2217     return DAG.getNode(ISD::SRL, DL, VT, N0,
2218                        DAG.getConstant(N1C->getAPIntValue().logBase2(), DL,
2219                                        getShiftAmountTy(N0.getValueType())));
2220   }
2221   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2222   if (N1.getOpcode() == ISD::SHL) {
2223     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2224       if (SHC->getAPIntValue().isPowerOf2()) {
2225         EVT ADDVT = N1.getOperand(1).getValueType();
2226         SDLoc DL(N);
2227         SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT,
2228                                   N1.getOperand(1),
2229                                   DAG.getConstant(SHC->getAPIntValue()
2230                                                                   .logBase2(),
2231                                                   DL, ADDVT));
2232         AddToWorklist(Add.getNode());
2233         return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
2234       }
2235     }
2236   }
2237   // fold (udiv x, c) -> alternate
2238   if (N1C && !TLI.isIntDivCheap()) {
2239     SDValue Op = BuildUDIV(N);
2240     if (Op.getNode()) return Op;
2241   }
2242
2243   // undef / X -> 0
2244   if (N0.getOpcode() == ISD::UNDEF)
2245     return DAG.getConstant(0, SDLoc(N), VT);
2246   // X / undef -> undef
2247   if (N1.getOpcode() == ISD::UNDEF)
2248     return N1;
2249
2250   return SDValue();
2251 }
2252
2253 SDValue DAGCombiner::visitSREM(SDNode *N) {
2254   SDValue N0 = N->getOperand(0);
2255   SDValue N1 = N->getOperand(1);
2256   EVT VT = N->getValueType(0);
2257
2258   // fold (srem c1, c2) -> c1%c2
2259   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2260   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2261   if (N0C && N1C && !N1C->isNullValue())
2262     return DAG.FoldConstantArithmetic(ISD::SREM, SDLoc(N), VT, N0C, N1C);
2263   // If we know the sign bits of both operands are zero, strength reduce to a
2264   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2265   if (!VT.isVector()) {
2266     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2267       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2268   }
2269
2270   // If X/C can be simplified by the division-by-constant logic, lower
2271   // X%C to the equivalent of X-X/C*C.
2272   if (N1C && !N1C->isNullValue()) {
2273     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2274     AddToWorklist(Div.getNode());
2275     SDValue OptimizedDiv = combine(Div.getNode());
2276     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2277       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2278                                 OptimizedDiv, N1);
2279       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2280       AddToWorklist(Mul.getNode());
2281       return Sub;
2282     }
2283   }
2284
2285   // undef % X -> 0
2286   if (N0.getOpcode() == ISD::UNDEF)
2287     return DAG.getConstant(0, SDLoc(N), VT);
2288   // X % undef -> undef
2289   if (N1.getOpcode() == ISD::UNDEF)
2290     return N1;
2291
2292   return SDValue();
2293 }
2294
2295 SDValue DAGCombiner::visitUREM(SDNode *N) {
2296   SDValue N0 = N->getOperand(0);
2297   SDValue N1 = N->getOperand(1);
2298   EVT VT = N->getValueType(0);
2299
2300   // fold (urem c1, c2) -> c1%c2
2301   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2302   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2303   if (N0C && N1C && !N1C->isNullValue())
2304     return DAG.FoldConstantArithmetic(ISD::UREM, SDLoc(N), VT, N0C, N1C);
2305   // fold (urem x, pow2) -> (and x, pow2-1)
2306   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2()) {
2307     SDLoc DL(N);
2308     return DAG.getNode(ISD::AND, DL, VT, N0,
2309                        DAG.getConstant(N1C->getAPIntValue() - 1, DL, VT));
2310   }
2311   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2312   if (N1.getOpcode() == ISD::SHL) {
2313     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2314       if (SHC->getAPIntValue().isPowerOf2()) {
2315         SDLoc DL(N);
2316         SDValue Add =
2317           DAG.getNode(ISD::ADD, DL, VT, N1,
2318                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL,
2319                                  VT));
2320         AddToWorklist(Add.getNode());
2321         return DAG.getNode(ISD::AND, DL, VT, N0, Add);
2322       }
2323     }
2324   }
2325
2326   // If X/C can be simplified by the division-by-constant logic, lower
2327   // X%C to the equivalent of X-X/C*C.
2328   if (N1C && !N1C->isNullValue()) {
2329     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2330     AddToWorklist(Div.getNode());
2331     SDValue OptimizedDiv = combine(Div.getNode());
2332     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2333       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2334                                 OptimizedDiv, N1);
2335       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2336       AddToWorklist(Mul.getNode());
2337       return Sub;
2338     }
2339   }
2340
2341   // undef % X -> 0
2342   if (N0.getOpcode() == ISD::UNDEF)
2343     return DAG.getConstant(0, SDLoc(N), VT);
2344   // X % undef -> undef
2345   if (N1.getOpcode() == ISD::UNDEF)
2346     return N1;
2347
2348   return SDValue();
2349 }
2350
2351 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2352   SDValue N0 = N->getOperand(0);
2353   SDValue N1 = N->getOperand(1);
2354   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2355   EVT VT = N->getValueType(0);
2356   SDLoc DL(N);
2357
2358   // fold (mulhs x, 0) -> 0
2359   if (N1C && N1C->isNullValue())
2360     return N1;
2361   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2362   if (N1C && N1C->getAPIntValue() == 1) {
2363     SDLoc DL(N);
2364     return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
2365                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2366                                        DL,
2367                                        getShiftAmountTy(N0.getValueType())));
2368   }
2369   // fold (mulhs x, undef) -> 0
2370   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2371     return DAG.getConstant(0, SDLoc(N), VT);
2372
2373   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2374   // plus a shift.
2375   if (VT.isSimple() && !VT.isVector()) {
2376     MVT Simple = VT.getSimpleVT();
2377     unsigned SimpleSize = Simple.getSizeInBits();
2378     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2379     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2380       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2381       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2382       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2383       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2384             DAG.getConstant(SimpleSize, DL,
2385                             getShiftAmountTy(N1.getValueType())));
2386       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2387     }
2388   }
2389
2390   return SDValue();
2391 }
2392
2393 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2394   SDValue N0 = N->getOperand(0);
2395   SDValue N1 = N->getOperand(1);
2396   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2397   EVT VT = N->getValueType(0);
2398   SDLoc DL(N);
2399
2400   // fold (mulhu x, 0) -> 0
2401   if (N1C && N1C->isNullValue())
2402     return N1;
2403   // fold (mulhu x, 1) -> 0
2404   if (N1C && N1C->getAPIntValue() == 1)
2405     return DAG.getConstant(0, DL, N0.getValueType());
2406   // fold (mulhu x, undef) -> 0
2407   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2408     return DAG.getConstant(0, DL, VT);
2409
2410   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2411   // plus a shift.
2412   if (VT.isSimple() && !VT.isVector()) {
2413     MVT Simple = VT.getSimpleVT();
2414     unsigned SimpleSize = Simple.getSizeInBits();
2415     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2416     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2417       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2418       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2419       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2420       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2421             DAG.getConstant(SimpleSize, DL,
2422                             getShiftAmountTy(N1.getValueType())));
2423       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2424     }
2425   }
2426
2427   return SDValue();
2428 }
2429
2430 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2431 /// give the opcodes for the two computations that are being performed. Return
2432 /// true if a simplification was made.
2433 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2434                                                 unsigned HiOp) {
2435   // If the high half is not needed, just compute the low half.
2436   bool HiExists = N->hasAnyUseOfValue(1);
2437   if (!HiExists &&
2438       (!LegalOperations ||
2439        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2440     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2441     return CombineTo(N, Res, Res);
2442   }
2443
2444   // If the low half is not needed, just compute the high half.
2445   bool LoExists = N->hasAnyUseOfValue(0);
2446   if (!LoExists &&
2447       (!LegalOperations ||
2448        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2449     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2450     return CombineTo(N, Res, Res);
2451   }
2452
2453   // If both halves are used, return as it is.
2454   if (LoExists && HiExists)
2455     return SDValue();
2456
2457   // If the two computed results can be simplified separately, separate them.
2458   if (LoExists) {
2459     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2460     AddToWorklist(Lo.getNode());
2461     SDValue LoOpt = combine(Lo.getNode());
2462     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2463         (!LegalOperations ||
2464          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2465       return CombineTo(N, LoOpt, LoOpt);
2466   }
2467
2468   if (HiExists) {
2469     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2470     AddToWorklist(Hi.getNode());
2471     SDValue HiOpt = combine(Hi.getNode());
2472     if (HiOpt.getNode() && HiOpt != Hi &&
2473         (!LegalOperations ||
2474          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2475       return CombineTo(N, HiOpt, HiOpt);
2476   }
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2482   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2483   if (Res.getNode()) return Res;
2484
2485   EVT VT = N->getValueType(0);
2486   SDLoc DL(N);
2487
2488   // If the type is twice as wide is legal, transform the mulhu to a wider
2489   // multiply plus a shift.
2490   if (VT.isSimple() && !VT.isVector()) {
2491     MVT Simple = VT.getSimpleVT();
2492     unsigned SimpleSize = Simple.getSizeInBits();
2493     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2494     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2495       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2496       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2497       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2498       // Compute the high part as N1.
2499       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2500             DAG.getConstant(SimpleSize, DL,
2501                             getShiftAmountTy(Lo.getValueType())));
2502       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2503       // Compute the low part as N0.
2504       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2505       return CombineTo(N, Lo, Hi);
2506     }
2507   }
2508
2509   return SDValue();
2510 }
2511
2512 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2513   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2514   if (Res.getNode()) return Res;
2515
2516   EVT VT = N->getValueType(0);
2517   SDLoc DL(N);
2518
2519   // If the type is twice as wide is legal, transform the mulhu to a wider
2520   // multiply plus a shift.
2521   if (VT.isSimple() && !VT.isVector()) {
2522     MVT Simple = VT.getSimpleVT();
2523     unsigned SimpleSize = Simple.getSizeInBits();
2524     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2525     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2526       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2527       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2528       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2529       // Compute the high part as N1.
2530       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2531             DAG.getConstant(SimpleSize, DL,
2532                             getShiftAmountTy(Lo.getValueType())));
2533       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2534       // Compute the low part as N0.
2535       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2536       return CombineTo(N, Lo, Hi);
2537     }
2538   }
2539
2540   return SDValue();
2541 }
2542
2543 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2544   // (smulo x, 2) -> (saddo x, x)
2545   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2546     if (C2->getAPIntValue() == 2)
2547       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2548                          N->getOperand(0), N->getOperand(0));
2549
2550   return SDValue();
2551 }
2552
2553 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2554   // (umulo x, 2) -> (uaddo x, x)
2555   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2556     if (C2->getAPIntValue() == 2)
2557       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2558                          N->getOperand(0), N->getOperand(0));
2559
2560   return SDValue();
2561 }
2562
2563 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2564   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2565   if (Res.getNode()) return Res;
2566
2567   return SDValue();
2568 }
2569
2570 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2571   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2572   if (Res.getNode()) return Res;
2573
2574   return SDValue();
2575 }
2576
2577 /// If this is a binary operator with two operands of the same opcode, try to
2578 /// simplify it.
2579 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2580   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2581   EVT VT = N0.getValueType();
2582   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2583
2584   // Bail early if none of these transforms apply.
2585   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2586
2587   // For each of OP in AND/OR/XOR:
2588   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2589   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2590   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2591   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2592   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2593   //
2594   // do not sink logical op inside of a vector extend, since it may combine
2595   // into a vsetcc.
2596   EVT Op0VT = N0.getOperand(0).getValueType();
2597   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2598        N0.getOpcode() == ISD::SIGN_EXTEND ||
2599        N0.getOpcode() == ISD::BSWAP ||
2600        // Avoid infinite looping with PromoteIntBinOp.
2601        (N0.getOpcode() == ISD::ANY_EXTEND &&
2602         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2603        (N0.getOpcode() == ISD::TRUNCATE &&
2604         (!TLI.isZExtFree(VT, Op0VT) ||
2605          !TLI.isTruncateFree(Op0VT, VT)) &&
2606         TLI.isTypeLegal(Op0VT))) &&
2607       !VT.isVector() &&
2608       Op0VT == N1.getOperand(0).getValueType() &&
2609       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2610     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2611                                  N0.getOperand(0).getValueType(),
2612                                  N0.getOperand(0), N1.getOperand(0));
2613     AddToWorklist(ORNode.getNode());
2614     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2615   }
2616
2617   // For each of OP in SHL/SRL/SRA/AND...
2618   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2619   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2620   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2621   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2622        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2623       N0.getOperand(1) == N1.getOperand(1)) {
2624     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2625                                  N0.getOperand(0).getValueType(),
2626                                  N0.getOperand(0), N1.getOperand(0));
2627     AddToWorklist(ORNode.getNode());
2628     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2629                        ORNode, N0.getOperand(1));
2630   }
2631
2632   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2633   // Only perform this optimization after type legalization and before
2634   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2635   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2636   // we don't want to undo this promotion.
2637   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2638   // on scalars.
2639   if ((N0.getOpcode() == ISD::BITCAST ||
2640        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2641       Level == AfterLegalizeTypes) {
2642     SDValue In0 = N0.getOperand(0);
2643     SDValue In1 = N1.getOperand(0);
2644     EVT In0Ty = In0.getValueType();
2645     EVT In1Ty = In1.getValueType();
2646     SDLoc DL(N);
2647     // If both incoming values are integers, and the original types are the
2648     // same.
2649     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2650       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2651       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2652       AddToWorklist(Op.getNode());
2653       return BC;
2654     }
2655   }
2656
2657   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2658   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2659   // If both shuffles use the same mask, and both shuffle within a single
2660   // vector, then it is worthwhile to move the swizzle after the operation.
2661   // The type-legalizer generates this pattern when loading illegal
2662   // vector types from memory. In many cases this allows additional shuffle
2663   // optimizations.
2664   // There are other cases where moving the shuffle after the xor/and/or
2665   // is profitable even if shuffles don't perform a swizzle.
2666   // If both shuffles use the same mask, and both shuffles have the same first
2667   // or second operand, then it might still be profitable to move the shuffle
2668   // after the xor/and/or operation.
2669   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2670     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2671     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2672
2673     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2674            "Inputs to shuffles are not the same type");
2675
2676     // Check that both shuffles use the same mask. The masks are known to be of
2677     // the same length because the result vector type is the same.
2678     // Check also that shuffles have only one use to avoid introducing extra
2679     // instructions.
2680     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2681         SVN0->getMask().equals(SVN1->getMask())) {
2682       SDValue ShOp = N0->getOperand(1);
2683
2684       // Don't try to fold this node if it requires introducing a
2685       // build vector of all zeros that might be illegal at this stage.
2686       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2687         if (!LegalTypes)
2688           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2689         else
2690           ShOp = SDValue();
2691       }
2692
2693       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2694       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2695       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2696       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2697         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2698                                       N0->getOperand(0), N1->getOperand(0));
2699         AddToWorklist(NewNode.getNode());
2700         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2701                                     &SVN0->getMask()[0]);
2702       }
2703
2704       // Don't try to fold this node if it requires introducing a
2705       // build vector of all zeros that might be illegal at this stage.
2706       ShOp = N0->getOperand(0);
2707       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2708         if (!LegalTypes)
2709           ShOp = DAG.getConstant(0, SDLoc(N), VT);
2710         else
2711           ShOp = SDValue();
2712       }
2713
2714       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2715       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2716       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2717       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2718         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2719                                       N0->getOperand(1), N1->getOperand(1));
2720         AddToWorklist(NewNode.getNode());
2721         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2722                                     &SVN0->getMask()[0]);
2723       }
2724     }
2725   }
2726
2727   return SDValue();
2728 }
2729
2730 /// This contains all DAGCombine rules which reduce two values combined by
2731 /// an And operation to a single value. This makes them reusable in the context
2732 /// of visitSELECT(). Rules involving constants are not included as
2733 /// visitSELECT() already handles those cases.
2734 SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1,
2735                                   SDNode *LocReference) {
2736   EVT VT = N1.getValueType();
2737
2738   // fold (and x, undef) -> 0
2739   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2740     return DAG.getConstant(0, SDLoc(LocReference), VT);
2741   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2742   SDValue LL, LR, RL, RR, CC0, CC1;
2743   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2744     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2745     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2746
2747     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2748         LL.getValueType().isInteger()) {
2749       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2750       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2751         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2752                                      LR.getValueType(), LL, RL);
2753         AddToWorklist(ORNode.getNode());
2754         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2755       }
2756       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2757       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2758         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2759                                       LR.getValueType(), LL, RL);
2760         AddToWorklist(ANDNode.getNode());
2761         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
2762       }
2763       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2764       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2765         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2766                                      LR.getValueType(), LL, RL);
2767         AddToWorklist(ORNode.getNode());
2768         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
2769       }
2770     }
2771     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2772     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2773         Op0 == Op1 && LL.getValueType().isInteger() &&
2774       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2775                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2776                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2777                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2778       SDLoc DL(N0);
2779       SDValue ADDNode = DAG.getNode(ISD::ADD, DL, LL.getValueType(),
2780                                     LL, DAG.getConstant(1, DL,
2781                                                         LL.getValueType()));
2782       AddToWorklist(ADDNode.getNode());
2783       return DAG.getSetCC(SDLoc(LocReference), VT, ADDNode,
2784                           DAG.getConstant(2, DL, LL.getValueType()),
2785                           ISD::SETUGE);
2786     }
2787     // canonicalize equivalent to ll == rl
2788     if (LL == RR && LR == RL) {
2789       Op1 = ISD::getSetCCSwappedOperands(Op1);
2790       std::swap(RL, RR);
2791     }
2792     if (LL == RL && LR == RR) {
2793       bool isInteger = LL.getValueType().isInteger();
2794       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2795       if (Result != ISD::SETCC_INVALID &&
2796           (!LegalOperations ||
2797            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2798             TLI.isOperationLegal(ISD::SETCC,
2799                             getSetCCResultType(N0.getSimpleValueType())))))
2800         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
2801                             LL, LR, Result);
2802     }
2803   }
2804
2805   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2806       VT.getSizeInBits() <= 64) {
2807     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2808       APInt ADDC = ADDI->getAPIntValue();
2809       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2810         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2811         // immediate for an add, but it is legal if its top c2 bits are set,
2812         // transform the ADD so the immediate doesn't need to be materialized
2813         // in a register.
2814         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2815           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2816                                              SRLI->getZExtValue());
2817           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2818             ADDC |= Mask;
2819             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2820               SDLoc DL(N0);
2821               SDValue NewAdd =
2822                 DAG.getNode(ISD::ADD, DL, VT,
2823                             N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
2824               CombineTo(N0.getNode(), NewAdd);
2825               // Return N so it doesn't get rechecked!
2826               return SDValue(LocReference, 0);
2827             }
2828           }
2829         }
2830       }
2831     }
2832   }
2833
2834   return SDValue();
2835 }
2836
2837 SDValue DAGCombiner::visitAND(SDNode *N) {
2838   SDValue N0 = N->getOperand(0);
2839   SDValue N1 = N->getOperand(1);
2840   EVT VT = N1.getValueType();
2841
2842   // fold vector ops
2843   if (VT.isVector()) {
2844     if (SDValue FoldedVOp = SimplifyVBinOp(N))
2845       return FoldedVOp;
2846
2847     // fold (and x, 0) -> 0, vector edition
2848     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2849       // do not return N0, because undef node may exist in N0
2850       return DAG.getConstant(
2851           APInt::getNullValue(
2852               N0.getValueType().getScalarType().getSizeInBits()),
2853           SDLoc(N), N0.getValueType());
2854     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2855       // do not return N1, because undef node may exist in N1
2856       return DAG.getConstant(
2857           APInt::getNullValue(
2858               N1.getValueType().getScalarType().getSizeInBits()),
2859           SDLoc(N), N1.getValueType());
2860
2861     // fold (and x, -1) -> x, vector edition
2862     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2863       return N1;
2864     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2865       return N0;
2866   }
2867
2868   // fold (and c1, c2) -> c1&c2
2869   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2870   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2871   if (N0C && N1C)
2872     return DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, N0C, N1C);
2873   // canonicalize constant to RHS
2874   if (isConstantIntBuildVectorOrConstantInt(N0) &&
2875      !isConstantIntBuildVectorOrConstantInt(N1))
2876     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2877   // fold (and x, -1) -> x
2878   if (N1C && N1C->isAllOnesValue())
2879     return N0;
2880   // if (and x, c) is known to be zero, return 0
2881   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2882   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2883                                    APInt::getAllOnesValue(BitWidth)))
2884     return DAG.getConstant(0, SDLoc(N), VT);
2885   // reassociate and
2886   if (SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1))
2887     return RAND;
2888   // fold (and (or x, C), D) -> D if (C & D) == D
2889   if (N1C && N0.getOpcode() == ISD::OR)
2890     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2891       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2892         return N1;
2893   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2894   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2895     SDValue N0Op0 = N0.getOperand(0);
2896     APInt Mask = ~N1C->getAPIntValue();
2897     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2898     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2899       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2900                                  N0.getValueType(), N0Op0);
2901
2902       // Replace uses of the AND with uses of the Zero extend node.
2903       CombineTo(N, Zext);
2904
2905       // We actually want to replace all uses of the any_extend with the
2906       // zero_extend, to avoid duplicating things.  This will later cause this
2907       // AND to be folded.
2908       CombineTo(N0.getNode(), Zext);
2909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2910     }
2911   }
2912   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2913   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2914   // already be zero by virtue of the width of the base type of the load.
2915   //
2916   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2917   // more cases.
2918   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2919        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2920       N0.getOpcode() == ISD::LOAD) {
2921     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2922                                          N0 : N0.getOperand(0) );
2923
2924     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2925     // This can be a pure constant or a vector splat, in which case we treat the
2926     // vector as a scalar and use the splat value.
2927     APInt Constant = APInt::getNullValue(1);
2928     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2929       Constant = C->getAPIntValue();
2930     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2931       APInt SplatValue, SplatUndef;
2932       unsigned SplatBitSize;
2933       bool HasAnyUndefs;
2934       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2935                                              SplatBitSize, HasAnyUndefs);
2936       if (IsSplat) {
2937         // Undef bits can contribute to a possible optimisation if set, so
2938         // set them.
2939         SplatValue |= SplatUndef;
2940
2941         // The splat value may be something like "0x00FFFFFF", which means 0 for
2942         // the first vector value and FF for the rest, repeating. We need a mask
2943         // that will apply equally to all members of the vector, so AND all the
2944         // lanes of the constant together.
2945         EVT VT = Vector->getValueType(0);
2946         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2947
2948         // If the splat value has been compressed to a bitlength lower
2949         // than the size of the vector lane, we need to re-expand it to
2950         // the lane size.
2951         if (BitWidth > SplatBitSize)
2952           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2953                SplatBitSize < BitWidth;
2954                SplatBitSize = SplatBitSize * 2)
2955             SplatValue |= SplatValue.shl(SplatBitSize);
2956
2957         // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
2958         // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
2959         if (SplatBitSize % BitWidth == 0) {
2960           Constant = APInt::getAllOnesValue(BitWidth);
2961           for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2962             Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2963         }
2964       }
2965     }
2966
2967     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2968     // actually legal and isn't going to get expanded, else this is a false
2969     // optimisation.
2970     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2971                                                     Load->getValueType(0),
2972                                                     Load->getMemoryVT());
2973
2974     // Resize the constant to the same size as the original memory access before
2975     // extension. If it is still the AllOnesValue then this AND is completely
2976     // unneeded.
2977     Constant =
2978       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2979
2980     bool B;
2981     switch (Load->getExtensionType()) {
2982     default: B = false; break;
2983     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2984     case ISD::ZEXTLOAD:
2985     case ISD::NON_EXTLOAD: B = true; break;
2986     }
2987
2988     if (B && Constant.isAllOnesValue()) {
2989       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2990       // preserve semantics once we get rid of the AND.
2991       SDValue NewLoad(Load, 0);
2992       if (Load->getExtensionType() == ISD::EXTLOAD) {
2993         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2994                               Load->getValueType(0), SDLoc(Load),
2995                               Load->getChain(), Load->getBasePtr(),
2996                               Load->getOffset(), Load->getMemoryVT(),
2997                               Load->getMemOperand());
2998         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2999         if (Load->getNumValues() == 3) {
3000           // PRE/POST_INC loads have 3 values.
3001           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
3002                            NewLoad.getValue(2) };
3003           CombineTo(Load, To, 3, true);
3004         } else {
3005           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
3006         }
3007       }
3008
3009       // Fold the AND away, taking care not to fold to the old load node if we
3010       // replaced it.
3011       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
3012
3013       return SDValue(N, 0); // Return N so it doesn't get rechecked!
3014     }
3015   }
3016
3017   // fold (and (load x), 255) -> (zextload x, i8)
3018   // fold (and (extload x, i16), 255) -> (zextload x, i8)
3019   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
3020   if (N1C && (N0.getOpcode() == ISD::LOAD ||
3021               (N0.getOpcode() == ISD::ANY_EXTEND &&
3022                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
3023     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
3024     LoadSDNode *LN0 = HasAnyExt
3025       ? cast<LoadSDNode>(N0.getOperand(0))
3026       : cast<LoadSDNode>(N0);
3027     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
3028         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
3029       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
3030       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
3031         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
3032         EVT LoadedVT = LN0->getMemoryVT();
3033         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3034
3035         if (ExtVT == LoadedVT &&
3036             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3037                                                     ExtVT))) {
3038
3039           SDValue NewLoad =
3040             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3041                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
3042                            LN0->getMemOperand());
3043           AddToWorklist(N);
3044           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
3045           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3046         }
3047
3048         // Do not change the width of a volatile load.
3049         // Do not generate loads of non-round integer types since these can
3050         // be expensive (and would be wrong if the type is not byte sized).
3051         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
3052             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
3053                                                     ExtVT))) {
3054           EVT PtrType = LN0->getOperand(1).getValueType();
3055
3056           unsigned Alignment = LN0->getAlignment();
3057           SDValue NewPtr = LN0->getBasePtr();
3058
3059           // For big endian targets, we need to add an offset to the pointer
3060           // to load the correct bytes.  For little endian systems, we merely
3061           // need to read fewer bytes from the same pointer.
3062           if (TLI.isBigEndian()) {
3063             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3064             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3065             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3066             SDLoc DL(LN0);
3067             NewPtr = DAG.getNode(ISD::ADD, DL, PtrType,
3068                                  NewPtr, DAG.getConstant(PtrOff, DL, PtrType));
3069             Alignment = MinAlign(Alignment, PtrOff);
3070           }
3071
3072           AddToWorklist(NewPtr.getNode());
3073
3074           SDValue Load =
3075             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3076                            LN0->getChain(), NewPtr,
3077                            LN0->getPointerInfo(),
3078                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3079                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3080           AddToWorklist(N);
3081           CombineTo(LN0, Load, Load.getValue(1));
3082           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3083         }
3084       }
3085     }
3086   }
3087
3088   if (SDValue Combined = visitANDLike(N0, N1, N))
3089     return Combined;
3090
3091   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
3092   if (N0.getOpcode() == N1.getOpcode()) {
3093     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3094     if (Tmp.getNode()) return Tmp;
3095   }
3096
3097   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
3098   // fold (and (sra)) -> (and (srl)) when possible.
3099   if (!VT.isVector() &&
3100       SimplifyDemandedBits(SDValue(N, 0)))
3101     return SDValue(N, 0);
3102
3103   // fold (zext_inreg (extload x)) -> (zextload x)
3104   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
3105     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3106     EVT MemVT = LN0->getMemoryVT();
3107     // If we zero all the possible extended bits, then we can turn this into
3108     // a zextload if we are running before legalize or the operation is legal.
3109     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3110     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3111                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3112         ((!LegalOperations && !LN0->isVolatile()) ||
3113          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3114       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3115                                        LN0->getChain(), LN0->getBasePtr(),
3116                                        MemVT, LN0->getMemOperand());
3117       AddToWorklist(N);
3118       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3119       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3120     }
3121   }
3122   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
3123   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3124       N0.hasOneUse()) {
3125     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3126     EVT MemVT = LN0->getMemoryVT();
3127     // If we zero all the possible extended bits, then we can turn this into
3128     // a zextload if we are running before legalize or the operation is legal.
3129     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
3130     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
3131                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
3132         ((!LegalOperations && !LN0->isVolatile()) ||
3133          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
3134       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
3135                                        LN0->getChain(), LN0->getBasePtr(),
3136                                        MemVT, LN0->getMemOperand());
3137       AddToWorklist(N);
3138       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3139       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3140     }
3141   }
3142   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3143   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3144     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3145                                        N0.getOperand(1), false);
3146     if (BSwap.getNode())
3147       return BSwap;
3148   }
3149
3150   return SDValue();
3151 }
3152
3153 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3154 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3155                                         bool DemandHighBits) {
3156   if (!LegalOperations)
3157     return SDValue();
3158
3159   EVT VT = N->getValueType(0);
3160   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3161     return SDValue();
3162   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3163     return SDValue();
3164
3165   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3166   bool LookPassAnd0 = false;
3167   bool LookPassAnd1 = false;
3168   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3169       std::swap(N0, N1);
3170   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3171       std::swap(N0, N1);
3172   if (N0.getOpcode() == ISD::AND) {
3173     if (!N0.getNode()->hasOneUse())
3174       return SDValue();
3175     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3176     if (!N01C || N01C->getZExtValue() != 0xFF00)
3177       return SDValue();
3178     N0 = N0.getOperand(0);
3179     LookPassAnd0 = true;
3180   }
3181
3182   if (N1.getOpcode() == ISD::AND) {
3183     if (!N1.getNode()->hasOneUse())
3184       return SDValue();
3185     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3186     if (!N11C || N11C->getZExtValue() != 0xFF)
3187       return SDValue();
3188     N1 = N1.getOperand(0);
3189     LookPassAnd1 = true;
3190   }
3191
3192   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3193     std::swap(N0, N1);
3194   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3195     return SDValue();
3196   if (!N0.getNode()->hasOneUse() ||
3197       !N1.getNode()->hasOneUse())
3198     return SDValue();
3199
3200   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3202   if (!N01C || !N11C)
3203     return SDValue();
3204   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3205     return SDValue();
3206
3207   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3208   SDValue N00 = N0->getOperand(0);
3209   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3210     if (!N00.getNode()->hasOneUse())
3211       return SDValue();
3212     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3213     if (!N001C || N001C->getZExtValue() != 0xFF)
3214       return SDValue();
3215     N00 = N00.getOperand(0);
3216     LookPassAnd0 = true;
3217   }
3218
3219   SDValue N10 = N1->getOperand(0);
3220   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3221     if (!N10.getNode()->hasOneUse())
3222       return SDValue();
3223     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3224     if (!N101C || N101C->getZExtValue() != 0xFF00)
3225       return SDValue();
3226     N10 = N10.getOperand(0);
3227     LookPassAnd1 = true;
3228   }
3229
3230   if (N00 != N10)
3231     return SDValue();
3232
3233   // Make sure everything beyond the low halfword gets set to zero since the SRL
3234   // 16 will clear the top bits.
3235   unsigned OpSizeInBits = VT.getSizeInBits();
3236   if (DemandHighBits && OpSizeInBits > 16) {
3237     // If the left-shift isn't masked out then the only way this is a bswap is
3238     // if all bits beyond the low 8 are 0. In that case the entire pattern
3239     // reduces to a left shift anyway: leave it for other parts of the combiner.
3240     if (!LookPassAnd0)
3241       return SDValue();
3242
3243     // However, if the right shift isn't masked out then it might be because
3244     // it's not needed. See if we can spot that too.
3245     if (!LookPassAnd1 &&
3246         !DAG.MaskedValueIsZero(
3247             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3248       return SDValue();
3249   }
3250
3251   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3252   if (OpSizeInBits > 16) {
3253     SDLoc DL(N);
3254     Res = DAG.getNode(ISD::SRL, DL, VT, Res,
3255                       DAG.getConstant(OpSizeInBits - 16, DL,
3256                                       getShiftAmountTy(VT)));
3257   }
3258   return Res;
3259 }
3260
3261 /// Return true if the specified node is an element that makes up a 32-bit
3262 /// packed halfword byteswap.
3263 /// ((x & 0x000000ff) << 8) |
3264 /// ((x & 0x0000ff00) >> 8) |
3265 /// ((x & 0x00ff0000) << 8) |
3266 /// ((x & 0xff000000) >> 8)
3267 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3268   if (!N.getNode()->hasOneUse())
3269     return false;
3270
3271   unsigned Opc = N.getOpcode();
3272   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3273     return false;
3274
3275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3276   if (!N1C)
3277     return false;
3278
3279   unsigned Num;
3280   switch (N1C->getZExtValue()) {
3281   default:
3282     return false;
3283   case 0xFF:       Num = 0; break;
3284   case 0xFF00:     Num = 1; break;
3285   case 0xFF0000:   Num = 2; break;
3286   case 0xFF000000: Num = 3; break;
3287   }
3288
3289   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3290   SDValue N0 = N.getOperand(0);
3291   if (Opc == ISD::AND) {
3292     if (Num == 0 || Num == 2) {
3293       // (x >> 8) & 0xff
3294       // (x >> 8) & 0xff0000
3295       if (N0.getOpcode() != ISD::SRL)
3296         return false;
3297       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3298       if (!C || C->getZExtValue() != 8)
3299         return false;
3300     } else {
3301       // (x << 8) & 0xff00
3302       // (x << 8) & 0xff000000
3303       if (N0.getOpcode() != ISD::SHL)
3304         return false;
3305       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3306       if (!C || C->getZExtValue() != 8)
3307         return false;
3308     }
3309   } else if (Opc == ISD::SHL) {
3310     // (x & 0xff) << 8
3311     // (x & 0xff0000) << 8
3312     if (Num != 0 && Num != 2)
3313       return false;
3314     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3315     if (!C || C->getZExtValue() != 8)
3316       return false;
3317   } else { // Opc == ISD::SRL
3318     // (x & 0xff00) >> 8
3319     // (x & 0xff000000) >> 8
3320     if (Num != 1 && Num != 3)
3321       return false;
3322     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3323     if (!C || C->getZExtValue() != 8)
3324       return false;
3325   }
3326
3327   if (Parts[Num])
3328     return false;
3329
3330   Parts[Num] = N0.getOperand(0).getNode();
3331   return true;
3332 }
3333
3334 /// Match a 32-bit packed halfword bswap. That is
3335 /// ((x & 0x000000ff) << 8) |
3336 /// ((x & 0x0000ff00) >> 8) |
3337 /// ((x & 0x00ff0000) << 8) |
3338 /// ((x & 0xff000000) >> 8)
3339 /// => (rotl (bswap x), 16)
3340 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3341   if (!LegalOperations)
3342     return SDValue();
3343
3344   EVT VT = N->getValueType(0);
3345   if (VT != MVT::i32)
3346     return SDValue();
3347   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3348     return SDValue();
3349
3350   // Look for either
3351   // (or (or (and), (and)), (or (and), (and)))
3352   // (or (or (or (and), (and)), (and)), (and))
3353   if (N0.getOpcode() != ISD::OR)
3354     return SDValue();
3355   SDValue N00 = N0.getOperand(0);
3356   SDValue N01 = N0.getOperand(1);
3357   SDNode *Parts[4] = {};
3358
3359   if (N1.getOpcode() == ISD::OR &&
3360       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3361     // (or (or (and), (and)), (or (and), (and)))
3362     SDValue N000 = N00.getOperand(0);
3363     if (!isBSwapHWordElement(N000, Parts))
3364       return SDValue();
3365
3366     SDValue N001 = N00.getOperand(1);
3367     if (!isBSwapHWordElement(N001, Parts))
3368       return SDValue();
3369     SDValue N010 = N01.getOperand(0);
3370     if (!isBSwapHWordElement(N010, Parts))
3371       return SDValue();
3372     SDValue N011 = N01.getOperand(1);
3373     if (!isBSwapHWordElement(N011, Parts))
3374       return SDValue();
3375   } else {
3376     // (or (or (or (and), (and)), (and)), (and))
3377     if (!isBSwapHWordElement(N1, Parts))
3378       return SDValue();
3379     if (!isBSwapHWordElement(N01, Parts))
3380       return SDValue();
3381     if (N00.getOpcode() != ISD::OR)
3382       return SDValue();
3383     SDValue N000 = N00.getOperand(0);
3384     if (!isBSwapHWordElement(N000, Parts))
3385       return SDValue();
3386     SDValue N001 = N00.getOperand(1);
3387     if (!isBSwapHWordElement(N001, Parts))
3388       return SDValue();
3389   }
3390
3391   // Make sure the parts are all coming from the same node.
3392   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3393     return SDValue();
3394
3395   SDLoc DL(N);
3396   SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
3397                               SDValue(Parts[0], 0));
3398
3399   // Result of the bswap should be rotated by 16. If it's not legal, then
3400   // do  (x << 16) | (x >> 16).
3401   SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
3402   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3403     return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
3404   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3405     return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
3406   return DAG.getNode(ISD::OR, DL, VT,
3407                      DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
3408                      DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
3409 }
3410
3411 /// This contains all DAGCombine rules which reduce two values combined by
3412 /// an Or operation to a single value \see visitANDLike().
3413 SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *LocReference) {
3414   EVT VT = N1.getValueType();
3415   // fold (or x, undef) -> -1
3416   if (!LegalOperations &&
3417       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3418     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3419     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()),
3420                            SDLoc(LocReference), VT);
3421   }
3422   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3423   SDValue LL, LR, RL, RR, CC0, CC1;
3424   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3425     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3426     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3427
3428     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3429         LL.getValueType().isInteger()) {
3430       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3431       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3432       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3433           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3434         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3435                                      LR.getValueType(), LL, RL);
3436         AddToWorklist(ORNode.getNode());
3437         return DAG.getSetCC(SDLoc(LocReference), VT, ORNode, LR, Op1);
3438       }
3439       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3440       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3441       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3442           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3443         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3444                                       LR.getValueType(), LL, RL);
3445         AddToWorklist(ANDNode.getNode());
3446         return DAG.getSetCC(SDLoc(LocReference), VT, ANDNode, LR, Op1);
3447       }
3448     }
3449     // canonicalize equivalent to ll == rl
3450     if (LL == RR && LR == RL) {
3451       Op1 = ISD::getSetCCSwappedOperands(Op1);
3452       std::swap(RL, RR);
3453     }
3454     if (LL == RL && LR == RR) {
3455       bool isInteger = LL.getValueType().isInteger();
3456       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3457       if (Result != ISD::SETCC_INVALID &&
3458           (!LegalOperations ||
3459            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3460             TLI.isOperationLegal(ISD::SETCC,
3461               getSetCCResultType(N0.getValueType())))))
3462         return DAG.getSetCC(SDLoc(LocReference), N0.getValueType(),
3463                             LL, LR, Result);
3464     }
3465   }
3466
3467   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3468   if (N0.getOpcode() == ISD::AND &&
3469       N1.getOpcode() == ISD::AND &&
3470       N0.getOperand(1).getOpcode() == ISD::Constant &&
3471       N1.getOperand(1).getOpcode() == ISD::Constant &&
3472       // Don't increase # computations.
3473       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3474     // We can only do this xform if we know that bits from X that are set in C2
3475     // but not in C1 are already zero.  Likewise for Y.
3476     const APInt &LHSMask =
3477       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3478     const APInt &RHSMask =
3479       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3480
3481     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3482         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3483       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3484                               N0.getOperand(0), N1.getOperand(0));
3485       SDLoc DL(LocReference);
3486       return DAG.getNode(ISD::AND, DL, VT, X,
3487                          DAG.getConstant(LHSMask | RHSMask, DL, VT));
3488     }
3489   }
3490
3491   // (or (and X, M), (and X, N)) -> (and X, (or M, N))
3492   if (N0.getOpcode() == ISD::AND &&
3493       N1.getOpcode() == ISD::AND &&
3494       N0.getOperand(0) == N1.getOperand(0) &&
3495       // Don't increase # computations.
3496       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3497     SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3498                             N0.getOperand(1), N1.getOperand(1));
3499     return DAG.getNode(ISD::AND, SDLoc(LocReference), VT, N0.getOperand(0), X);
3500   }
3501
3502   return SDValue();
3503 }
3504
3505 SDValue DAGCombiner::visitOR(SDNode *N) {
3506   SDValue N0 = N->getOperand(0);
3507   SDValue N1 = N->getOperand(1);
3508   EVT VT = N1.getValueType();
3509
3510   // fold vector ops
3511   if (VT.isVector()) {
3512     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3513       return FoldedVOp;
3514
3515     // fold (or x, 0) -> x, vector edition
3516     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3517       return N1;
3518     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3519       return N0;
3520
3521     // fold (or x, -1) -> -1, vector edition
3522     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3523       // do not return N0, because undef node may exist in N0
3524       return DAG.getConstant(
3525           APInt::getAllOnesValue(
3526               N0.getValueType().getScalarType().getSizeInBits()),
3527           SDLoc(N), N0.getValueType());
3528     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3529       // do not return N1, because undef node may exist in N1
3530       return DAG.getConstant(
3531           APInt::getAllOnesValue(
3532               N1.getValueType().getScalarType().getSizeInBits()),
3533           SDLoc(N), N1.getValueType());
3534
3535     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3536     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3537     // Do this only if the resulting shuffle is legal.
3538     if (isa<ShuffleVectorSDNode>(N0) &&
3539         isa<ShuffleVectorSDNode>(N1) &&
3540         // Avoid folding a node with illegal type.
3541         TLI.isTypeLegal(VT) &&
3542         N0->getOperand(1) == N1->getOperand(1) &&
3543         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3544       bool CanFold = true;
3545       unsigned NumElts = VT.getVectorNumElements();
3546       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3547       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3548       // We construct two shuffle masks:
3549       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3550       // and N1 as the second operand.
3551       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3552       // and N0 as the second operand.
3553       // We do this because OR is commutable and therefore there might be
3554       // two ways to fold this node into a shuffle.
3555       SmallVector<int,4> Mask1;
3556       SmallVector<int,4> Mask2;
3557
3558       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3559         int M0 = SV0->getMaskElt(i);
3560         int M1 = SV1->getMaskElt(i);
3561
3562         // Both shuffle indexes are undef. Propagate Undef.
3563         if (M0 < 0 && M1 < 0) {
3564           Mask1.push_back(M0);
3565           Mask2.push_back(M0);
3566           continue;
3567         }
3568
3569         if (M0 < 0 || M1 < 0 ||
3570             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3571             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3572           CanFold = false;
3573           break;
3574         }
3575
3576         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3577         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3578       }
3579
3580       if (CanFold) {
3581         // Fold this sequence only if the resulting shuffle is 'legal'.
3582         if (TLI.isShuffleMaskLegal(Mask1, VT))
3583           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3584                                       N1->getOperand(0), &Mask1[0]);
3585         if (TLI.isShuffleMaskLegal(Mask2, VT))
3586           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3587                                       N0->getOperand(0), &Mask2[0]);
3588       }
3589     }
3590   }
3591
3592   // fold (or c1, c2) -> c1|c2
3593   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3594   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3595   if (N0C && N1C)
3596     return DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, N0C, N1C);
3597   // canonicalize constant to RHS
3598   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3599      !isConstantIntBuildVectorOrConstantInt(N1))
3600     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3601   // fold (or x, 0) -> x
3602   if (N1C && N1C->isNullValue())
3603     return N0;
3604   // fold (or x, -1) -> -1
3605   if (N1C && N1C->isAllOnesValue())
3606     return N1;
3607   // fold (or x, c) -> c iff (x & ~c) == 0
3608   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3609     return N1;
3610
3611   if (SDValue Combined = visitORLike(N0, N1, N))
3612     return Combined;
3613
3614   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3615   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3616   if (BSwap.getNode())
3617     return BSwap;
3618   BSwap = MatchBSwapHWordLow(N, N0, N1);
3619   if (BSwap.getNode())
3620     return BSwap;
3621
3622   // reassociate or
3623   if (SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1))
3624     return ROR;
3625   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3626   // iff (c1 & c2) == 0.
3627   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3628              isa<ConstantSDNode>(N0.getOperand(1))) {
3629     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3630     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3631       if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
3632                                                    N1C, C1))
3633         return DAG.getNode(
3634             ISD::AND, SDLoc(N), VT,
3635             DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1), COR);
3636       return SDValue();
3637     }
3638   }
3639   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3640   if (N0.getOpcode() == N1.getOpcode()) {
3641     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3642     if (Tmp.getNode()) return Tmp;
3643   }
3644
3645   // See if this is some rotate idiom.
3646   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3647     return SDValue(Rot, 0);
3648
3649   // Simplify the operands using demanded-bits information.
3650   if (!VT.isVector() &&
3651       SimplifyDemandedBits(SDValue(N, 0)))
3652     return SDValue(N, 0);
3653
3654   return SDValue();
3655 }
3656
3657 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3658 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3659   if (Op.getOpcode() == ISD::AND) {
3660     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3661       Mask = Op.getOperand(1);
3662       Op = Op.getOperand(0);
3663     } else {
3664       return false;
3665     }
3666   }
3667
3668   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3669     Shift = Op;
3670     return true;
3671   }
3672
3673   return false;
3674 }
3675
3676 // Return true if we can prove that, whenever Neg and Pos are both in the
3677 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3678 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3679 //
3680 //     (or (shift1 X, Neg), (shift2 X, Pos))
3681 //
3682 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3683 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3684 // to consider shift amounts with defined behavior.
3685 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3686   // If OpSize is a power of 2 then:
3687   //
3688   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3689   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3690   //
3691   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3692   // for the stronger condition:
3693   //
3694   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3695   //
3696   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3697   // we can just replace Neg with Neg' for the rest of the function.
3698   //
3699   // In other cases we check for the even stronger condition:
3700   //
3701   //     Neg == OpSize - Pos                                    [B]
3702   //
3703   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3704   // behavior if Pos == 0 (and consequently Neg == OpSize).
3705   //
3706   // We could actually use [A] whenever OpSize is a power of 2, but the
3707   // only extra cases that it would match are those uninteresting ones
3708   // where Neg and Pos are never in range at the same time.  E.g. for
3709   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3710   // as well as (sub 32, Pos), but:
3711   //
3712   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3713   //
3714   // always invokes undefined behavior for 32-bit X.
3715   //
3716   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3717   unsigned MaskLoBits = 0;
3718   if (Neg.getOpcode() == ISD::AND &&
3719       isPowerOf2_64(OpSize) &&
3720       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3721       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3722     Neg = Neg.getOperand(0);
3723     MaskLoBits = Log2_64(OpSize);
3724   }
3725
3726   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3727   if (Neg.getOpcode() != ISD::SUB)
3728     return 0;
3729   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3730   if (!NegC)
3731     return 0;
3732   SDValue NegOp1 = Neg.getOperand(1);
3733
3734   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3735   // Pos'.  The truncation is redundant for the purpose of the equality.
3736   if (MaskLoBits &&
3737       Pos.getOpcode() == ISD::AND &&
3738       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3739       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3740     Pos = Pos.getOperand(0);
3741
3742   // The condition we need is now:
3743   //
3744   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3745   //
3746   // If NegOp1 == Pos then we need:
3747   //
3748   //              OpSize & Mask == NegC & Mask
3749   //
3750   // (because "x & Mask" is a truncation and distributes through subtraction).
3751   APInt Width;
3752   if (Pos == NegOp1)
3753     Width = NegC->getAPIntValue();
3754   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3755   // Then the condition we want to prove becomes:
3756   //
3757   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3758   //
3759   // which, again because "x & Mask" is a truncation, becomes:
3760   //
3761   //                NegC & Mask == (OpSize - PosC) & Mask
3762   //              OpSize & Mask == (NegC + PosC) & Mask
3763   else if (Pos.getOpcode() == ISD::ADD &&
3764            Pos.getOperand(0) == NegOp1 &&
3765            Pos.getOperand(1).getOpcode() == ISD::Constant)
3766     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3767              NegC->getAPIntValue());
3768   else
3769     return false;
3770
3771   // Now we just need to check that OpSize & Mask == Width & Mask.
3772   if (MaskLoBits)
3773     // Opsize & Mask is 0 since Mask is Opsize - 1.
3774     return Width.getLoBits(MaskLoBits) == 0;
3775   return Width == OpSize;
3776 }
3777
3778 // A subroutine of MatchRotate used once we have found an OR of two opposite
3779 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3780 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3781 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3782 // Neg with outer conversions stripped away.
3783 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3784                                        SDValue Neg, SDValue InnerPos,
3785                                        SDValue InnerNeg, unsigned PosOpcode,
3786                                        unsigned NegOpcode, SDLoc DL) {
3787   // fold (or (shl x, (*ext y)),
3788   //          (srl x, (*ext (sub 32, y)))) ->
3789   //   (rotl x, y) or (rotr x, (sub 32, y))
3790   //
3791   // fold (or (shl x, (*ext (sub 32, y))),
3792   //          (srl x, (*ext y))) ->
3793   //   (rotr x, y) or (rotl x, (sub 32, y))
3794   EVT VT = Shifted.getValueType();
3795   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3796     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3797     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3798                        HasPos ? Pos : Neg).getNode();
3799   }
3800
3801   return nullptr;
3802 }
3803
3804 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3805 // idioms for rotate, and if the target supports rotation instructions, generate
3806 // a rot[lr].
3807 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3808   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3809   EVT VT = LHS.getValueType();
3810   if (!TLI.isTypeLegal(VT)) return nullptr;
3811
3812   // The target must have at least one rotate flavor.
3813   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3814   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3815   if (!HasROTL && !HasROTR) return nullptr;
3816
3817   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3818   SDValue LHSShift;   // The shift.
3819   SDValue LHSMask;    // AND value if any.
3820   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3821     return nullptr; // Not part of a rotate.
3822
3823   SDValue RHSShift;   // The shift.
3824   SDValue RHSMask;    // AND value if any.
3825   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3826     return nullptr; // Not part of a rotate.
3827
3828   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3829     return nullptr;   // Not shifting the same value.
3830
3831   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3832     return nullptr;   // Shifts must disagree.
3833
3834   // Canonicalize shl to left side in a shl/srl pair.
3835   if (RHSShift.getOpcode() == ISD::SHL) {
3836     std::swap(LHS, RHS);
3837     std::swap(LHSShift, RHSShift);
3838     std::swap(LHSMask , RHSMask );
3839   }
3840
3841   unsigned OpSizeInBits = VT.getSizeInBits();
3842   SDValue LHSShiftArg = LHSShift.getOperand(0);
3843   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3844   SDValue RHSShiftArg = RHSShift.getOperand(0);
3845   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3846
3847   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3848   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3849   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3850       RHSShiftAmt.getOpcode() == ISD::Constant) {
3851     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3852     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3853     if ((LShVal + RShVal) != OpSizeInBits)
3854       return nullptr;
3855
3856     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3857                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3858
3859     // If there is an AND of either shifted operand, apply it to the result.
3860     if (LHSMask.getNode() || RHSMask.getNode()) {
3861       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3862
3863       if (LHSMask.getNode()) {
3864         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3865         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3866       }
3867       if (RHSMask.getNode()) {
3868         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3869         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3870       }
3871
3872       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, DL, VT));
3873     }
3874
3875     return Rot.getNode();
3876   }
3877
3878   // If there is a mask here, and we have a variable shift, we can't be sure
3879   // that we're masking out the right stuff.
3880   if (LHSMask.getNode() || RHSMask.getNode())
3881     return nullptr;
3882
3883   // If the shift amount is sign/zext/any-extended just peel it off.
3884   SDValue LExtOp0 = LHSShiftAmt;
3885   SDValue RExtOp0 = RHSShiftAmt;
3886   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3887        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3888        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3889        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3890       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3891        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3892        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3893        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3894     LExtOp0 = LHSShiftAmt.getOperand(0);
3895     RExtOp0 = RHSShiftAmt.getOperand(0);
3896   }
3897
3898   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3899                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3900   if (TryL)
3901     return TryL;
3902
3903   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3904                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3905   if (TryR)
3906     return TryR;
3907
3908   return nullptr;
3909 }
3910
3911 SDValue DAGCombiner::visitXOR(SDNode *N) {
3912   SDValue N0 = N->getOperand(0);
3913   SDValue N1 = N->getOperand(1);
3914   EVT VT = N0.getValueType();
3915
3916   // fold vector ops
3917   if (VT.isVector()) {
3918     if (SDValue FoldedVOp = SimplifyVBinOp(N))
3919       return FoldedVOp;
3920
3921     // fold (xor x, 0) -> x, vector edition
3922     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3923       return N1;
3924     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3925       return N0;
3926   }
3927
3928   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3929   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3930     return DAG.getConstant(0, SDLoc(N), VT);
3931   // fold (xor x, undef) -> undef
3932   if (N0.getOpcode() == ISD::UNDEF)
3933     return N0;
3934   if (N1.getOpcode() == ISD::UNDEF)
3935     return N1;
3936   // fold (xor c1, c2) -> c1^c2
3937   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3938   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3939   if (N0C && N1C)
3940     return DAG.FoldConstantArithmetic(ISD::XOR, SDLoc(N), VT, N0C, N1C);
3941   // canonicalize constant to RHS
3942   if (isConstantIntBuildVectorOrConstantInt(N0) &&
3943      !isConstantIntBuildVectorOrConstantInt(N1))
3944     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3945   // fold (xor x, 0) -> x
3946   if (N1C && N1C->isNullValue())
3947     return N0;
3948   // reassociate xor
3949   if (SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1))
3950     return RXOR;
3951
3952   // fold !(x cc y) -> (x !cc y)
3953   SDValue LHS, RHS, CC;
3954   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3955     bool isInt = LHS.getValueType().isInteger();
3956     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3957                                                isInt);
3958
3959     if (!LegalOperations ||
3960         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3961       switch (N0.getOpcode()) {
3962       default:
3963         llvm_unreachable("Unhandled SetCC Equivalent!");
3964       case ISD::SETCC:
3965         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3966       case ISD::SELECT_CC:
3967         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3968                                N0.getOperand(3), NotCC);
3969       }
3970     }
3971   }
3972
3973   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3974   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3975       N0.getNode()->hasOneUse() &&
3976       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3977     SDValue V = N0.getOperand(0);
3978     SDLoc DL(N0);
3979     V = DAG.getNode(ISD::XOR, DL, V.getValueType(), V,
3980                     DAG.getConstant(1, DL, V.getValueType()));
3981     AddToWorklist(V.getNode());
3982     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3983   }
3984
3985   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3986   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3987       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3988     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3989     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3990       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3991       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3992       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3993       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3994       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3995     }
3996   }
3997   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3998   if (N1C && N1C->isAllOnesValue() &&
3999       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
4000     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4001     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
4002       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
4003       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
4004       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
4005       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
4006       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
4007     }
4008   }
4009   // fold (xor (and x, y), y) -> (and (not x), y)
4010   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
4011       N0->getOperand(1) == N1) {
4012     SDValue X = N0->getOperand(0);
4013     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
4014     AddToWorklist(NotX.getNode());
4015     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
4016   }
4017   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
4018   if (N1C && N0.getOpcode() == ISD::XOR) {
4019     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
4020     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4021     if (N00C) {
4022       SDLoc DL(N);
4023       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
4024                          DAG.getConstant(N1C->getAPIntValue() ^
4025                                          N00C->getAPIntValue(), DL, VT));
4026     }
4027     if (N01C) {
4028       SDLoc DL(N);
4029       return DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
4030                          DAG.getConstant(N1C->getAPIntValue() ^
4031                                          N01C->getAPIntValue(), DL, VT));
4032     }
4033   }
4034   // fold (xor x, x) -> 0
4035   if (N0 == N1)
4036     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
4037
4038   // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
4039   // Here is a concrete example of this equivalence:
4040   // i16   x ==  14
4041   // i16 shl ==   1 << 14  == 16384 == 0b0100000000000000
4042   // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
4043   //
4044   // =>
4045   //
4046   // i16     ~1      == 0b1111111111111110
4047   // i16 rol(~1, 14) == 0b1011111111111111
4048   //
4049   // Some additional tips to help conceptualize this transform:
4050   // - Try to see the operation as placing a single zero in a value of all ones.
4051   // - There exists no value for x which would allow the result to contain zero.
4052   // - Values of x larger than the bitwidth are undefined and do not require a
4053   //   consistent result.
4054   // - Pushing the zero left requires shifting one bits in from the right.
4055   // A rotate left of ~1 is a nice way of achieving the desired result.
4056   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
4057     if (auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode()))
4058       if (N0.getOpcode() == ISD::SHL)
4059         if (auto *ShlLHS = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
4060           if (N1C->isAllOnesValue() && ShlLHS->isOne()) {
4061             SDLoc DL(N);
4062             return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
4063                                N0.getOperand(1));
4064           }
4065
4066   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
4067   if (N0.getOpcode() == N1.getOpcode()) {
4068     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
4069     if (Tmp.getNode()) return Tmp;
4070   }
4071
4072   // Simplify the expression using non-local knowledge.
4073   if (!VT.isVector() &&
4074       SimplifyDemandedBits(SDValue(N, 0)))
4075     return SDValue(N, 0);
4076
4077   return SDValue();
4078 }
4079
4080 /// Handle transforms common to the three shifts, when the shift amount is a
4081 /// constant.
4082 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
4083   // We can't and shouldn't fold opaque constants.
4084   if (Amt->isOpaque())
4085     return SDValue();
4086
4087   SDNode *LHS = N->getOperand(0).getNode();
4088   if (!LHS->hasOneUse()) return SDValue();
4089
4090   // We want to pull some binops through shifts, so that we have (and (shift))
4091   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
4092   // thing happens with address calculations, so it's important to canonicalize
4093   // it.
4094   bool HighBitSet = false;  // Can we transform this if the high bit is set?
4095
4096   switch (LHS->getOpcode()) {
4097   default: return SDValue();
4098   case ISD::OR:
4099   case ISD::XOR:
4100     HighBitSet = false; // We can only transform sra if the high bit is clear.
4101     break;
4102   case ISD::AND:
4103     HighBitSet = true;  // We can only transform sra if the high bit is set.
4104     break;
4105   case ISD::ADD:
4106     if (N->getOpcode() != ISD::SHL)
4107       return SDValue(); // only shl(add) not sr[al](add).
4108     HighBitSet = false; // We can only transform sra if the high bit is clear.
4109     break;
4110   }
4111
4112   // We require the RHS of the binop to be a constant and not opaque as well.
4113   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
4114   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
4115
4116   // FIXME: disable this unless the input to the binop is a shift by a constant.
4117   // If it is not a shift, it pessimizes some common cases like:
4118   //
4119   //    void foo(int *X, int i) { X[i & 1235] = 1; }
4120   //    int bar(int *X, int i) { return X[i & 255]; }
4121   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
4122   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
4123        BinOpLHSVal->getOpcode() != ISD::SRA &&
4124        BinOpLHSVal->getOpcode() != ISD::SRL) ||
4125       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
4126     return SDValue();
4127
4128   EVT VT = N->getValueType(0);
4129
4130   // If this is a signed shift right, and the high bit is modified by the
4131   // logical operation, do not perform the transformation. The highBitSet
4132   // boolean indicates the value of the high bit of the constant which would
4133   // cause it to be modified for this operation.
4134   if (N->getOpcode() == ISD::SRA) {
4135     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
4136     if (BinOpRHSSignSet != HighBitSet)
4137       return SDValue();
4138   }
4139
4140   if (!TLI.isDesirableToCommuteWithShift(LHS))
4141     return SDValue();
4142
4143   // Fold the constants, shifting the binop RHS by the shift amount.
4144   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4145                                N->getValueType(0),
4146                                LHS->getOperand(1), N->getOperand(1));
4147   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4148
4149   // Create the new shift.
4150   SDValue NewShift = DAG.getNode(N->getOpcode(),
4151                                  SDLoc(LHS->getOperand(0)),
4152                                  VT, LHS->getOperand(0), N->getOperand(1));
4153
4154   // Create the new binop.
4155   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4156 }
4157
4158 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4159   assert(N->getOpcode() == ISD::TRUNCATE);
4160   assert(N->getOperand(0).getOpcode() == ISD::AND);
4161
4162   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4163   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4164     SDValue N01 = N->getOperand(0).getOperand(1);
4165
4166     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4167       EVT TruncVT = N->getValueType(0);
4168       SDValue N00 = N->getOperand(0).getOperand(0);
4169       APInt TruncC = N01C->getAPIntValue();
4170       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4171       SDLoc DL(N);
4172
4173       return DAG.getNode(ISD::AND, DL, TruncVT,
4174                          DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00),
4175                          DAG.getConstant(TruncC, DL, TruncVT));
4176     }
4177   }
4178
4179   return SDValue();
4180 }
4181
4182 SDValue DAGCombiner::visitRotate(SDNode *N) {
4183   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4184   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4185       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4186     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4187     if (NewOp1.getNode())
4188       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4189                          N->getOperand(0), NewOp1);
4190   }
4191   return SDValue();
4192 }
4193
4194 SDValue DAGCombiner::visitSHL(SDNode *N) {
4195   SDValue N0 = N->getOperand(0);
4196   SDValue N1 = N->getOperand(1);
4197   EVT VT = N0.getValueType();
4198   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4199
4200   // fold vector ops
4201   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4202   if (VT.isVector()) {
4203     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4204       return FoldedVOp;
4205
4206     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4207     // If setcc produces all-one true value then:
4208     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4209     if (N1CV && N1CV->isConstant()) {
4210       if (N0.getOpcode() == ISD::AND) {
4211         SDValue N00 = N0->getOperand(0);
4212         SDValue N01 = N0->getOperand(1);
4213         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4214
4215         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4216             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4217                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4218           if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT,
4219                                                      N01CV, N1CV))
4220             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4221         }
4222       } else {
4223         N1C = isConstOrConstSplat(N1);
4224       }
4225     }
4226   }
4227
4228   // fold (shl c1, c2) -> c1<<c2
4229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230   if (N0C && N1C)
4231     return DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, N0C, N1C);
4232   // fold (shl 0, x) -> 0
4233   if (N0C && N0C->isNullValue())
4234     return N0;
4235   // fold (shl x, c >= size(x)) -> undef
4236   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4237     return DAG.getUNDEF(VT);
4238   // fold (shl x, 0) -> x
4239   if (N1C && N1C->isNullValue())
4240     return N0;
4241   // fold (shl undef, x) -> 0
4242   if (N0.getOpcode() == ISD::UNDEF)
4243     return DAG.getConstant(0, SDLoc(N), VT);
4244   // if (shl x, c) is known to be zero, return 0
4245   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4246                             APInt::getAllOnesValue(OpSizeInBits)))
4247     return DAG.getConstant(0, SDLoc(N), VT);
4248   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4249   if (N1.getOpcode() == ISD::TRUNCATE &&
4250       N1.getOperand(0).getOpcode() == ISD::AND) {
4251     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4252     if (NewOp1.getNode())
4253       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4254   }
4255
4256   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4257     return SDValue(N, 0);
4258
4259   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4260   if (N1C && N0.getOpcode() == ISD::SHL) {
4261     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4262       uint64_t c1 = N0C1->getZExtValue();
4263       uint64_t c2 = N1C->getZExtValue();
4264       SDLoc DL(N);
4265       if (c1 + c2 >= OpSizeInBits)
4266         return DAG.getConstant(0, DL, VT);
4267       return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4268                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4269     }
4270   }
4271
4272   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4273   // For this to be valid, the second form must not preserve any of the bits
4274   // that are shifted out by the inner shift in the first form.  This means
4275   // the outer shift size must be >= the number of bits added by the ext.
4276   // As a corollary, we don't care what kind of ext it is.
4277   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4278               N0.getOpcode() == ISD::ANY_EXTEND ||
4279               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4280       N0.getOperand(0).getOpcode() == ISD::SHL) {
4281     SDValue N0Op0 = N0.getOperand(0);
4282     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4283       uint64_t c1 = N0Op0C1->getZExtValue();
4284       uint64_t c2 = N1C->getZExtValue();
4285       EVT InnerShiftVT = N0Op0.getValueType();
4286       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4287       if (c2 >= OpSizeInBits - InnerShiftSize) {
4288         SDLoc DL(N0);
4289         if (c1 + c2 >= OpSizeInBits)
4290           return DAG.getConstant(0, DL, VT);
4291         return DAG.getNode(ISD::SHL, DL, VT,
4292                            DAG.getNode(N0.getOpcode(), DL, VT,
4293                                        N0Op0->getOperand(0)),
4294                            DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4295       }
4296     }
4297   }
4298
4299   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4300   // Only fold this if the inner zext has no other uses to avoid increasing
4301   // the total number of instructions.
4302   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4303       N0.getOperand(0).getOpcode() == ISD::SRL) {
4304     SDValue N0Op0 = N0.getOperand(0);
4305     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4306       uint64_t c1 = N0Op0C1->getZExtValue();
4307       if (c1 < VT.getScalarSizeInBits()) {
4308         uint64_t c2 = N1C->getZExtValue();
4309         if (c1 == c2) {
4310           SDValue NewOp0 = N0.getOperand(0);
4311           EVT CountVT = NewOp0.getOperand(1).getValueType();
4312           SDLoc DL(N);
4313           SDValue NewSHL = DAG.getNode(ISD::SHL, DL, NewOp0.getValueType(),
4314                                        NewOp0,
4315                                        DAG.getConstant(c2, DL, CountVT));
4316           AddToWorklist(NewSHL.getNode());
4317           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4318         }
4319       }
4320     }
4321   }
4322
4323   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4324   //                               (and (srl x, (sub c1, c2), MASK)
4325   // Only fold this if the inner shift has no other uses -- if it does, folding
4326   // this will increase the total number of instructions.
4327   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4328     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4329       uint64_t c1 = N0C1->getZExtValue();
4330       if (c1 < OpSizeInBits) {
4331         uint64_t c2 = N1C->getZExtValue();
4332         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4333         SDValue Shift;
4334         if (c2 > c1) {
4335           Mask = Mask.shl(c2 - c1);
4336           SDLoc DL(N);
4337           Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
4338                               DAG.getConstant(c2 - c1, DL, N1.getValueType()));
4339         } else {
4340           Mask = Mask.lshr(c1 - c2);
4341           SDLoc DL(N);
4342           Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4343                               DAG.getConstant(c1 - c2, DL, N1.getValueType()));
4344         }
4345         SDLoc DL(N0);
4346         return DAG.getNode(ISD::AND, DL, VT, Shift,
4347                            DAG.getConstant(Mask, DL, VT));
4348       }
4349     }
4350   }
4351   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4352   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4353     unsigned BitSize = VT.getScalarSizeInBits();
4354     SDLoc DL(N);
4355     SDValue HiBitsMask =
4356       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4357                                             BitSize - N1C->getZExtValue()),
4358                       DL, VT);
4359     return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4360                        HiBitsMask);
4361   }
4362
4363   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4364   // Variant of version done on multiply, except mul by a power of 2 is turned
4365   // into a shift.
4366   APInt Val;
4367   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4368       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4369        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4370     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4371     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4372     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4373   }
4374
4375   if (N1C) {
4376     SDValue NewSHL = visitShiftByConstant(N, N1C);
4377     if (NewSHL.getNode())
4378       return NewSHL;
4379   }
4380
4381   return SDValue();
4382 }
4383
4384 SDValue DAGCombiner::visitSRA(SDNode *N) {
4385   SDValue N0 = N->getOperand(0);
4386   SDValue N1 = N->getOperand(1);
4387   EVT VT = N0.getValueType();
4388   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4389
4390   // fold vector ops
4391   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4392   if (VT.isVector()) {
4393     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4394       return FoldedVOp;
4395
4396     N1C = isConstOrConstSplat(N1);
4397   }
4398
4399   // fold (sra c1, c2) -> (sra c1, c2)
4400   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4401   if (N0C && N1C)
4402     return DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, N0C, N1C);
4403   // fold (sra 0, x) -> 0
4404   if (N0C && N0C->isNullValue())
4405     return N0;
4406   // fold (sra -1, x) -> -1
4407   if (N0C && N0C->isAllOnesValue())
4408     return N0;
4409   // fold (sra x, (setge c, size(x))) -> undef
4410   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4411     return DAG.getUNDEF(VT);
4412   // fold (sra x, 0) -> x
4413   if (N1C && N1C->isNullValue())
4414     return N0;
4415   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4416   // sext_inreg.
4417   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4418     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4419     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4420     if (VT.isVector())
4421       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4422                                ExtVT, VT.getVectorNumElements());
4423     if ((!LegalOperations ||
4424          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4425       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4426                          N0.getOperand(0), DAG.getValueType(ExtVT));
4427   }
4428
4429   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4430   if (N1C && N0.getOpcode() == ISD::SRA) {
4431     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4432       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4433       if (Sum >= OpSizeInBits)
4434         Sum = OpSizeInBits - 1;
4435       SDLoc DL(N);
4436       return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0),
4437                          DAG.getConstant(Sum, DL, N1.getValueType()));
4438     }
4439   }
4440
4441   // fold (sra (shl X, m), (sub result_size, n))
4442   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4443   // result_size - n != m.
4444   // If truncate is free for the target sext(shl) is likely to result in better
4445   // code.
4446   if (N0.getOpcode() == ISD::SHL && N1C) {
4447     // Get the two constanst of the shifts, CN0 = m, CN = n.
4448     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4449     if (N01C) {
4450       LLVMContext &Ctx = *DAG.getContext();
4451       // Determine what the truncate's result bitsize and type would be.
4452       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4453
4454       if (VT.isVector())
4455         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4456
4457       // Determine the residual right-shift amount.
4458       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4459
4460       // If the shift is not a no-op (in which case this should be just a sign
4461       // extend already), the truncated to type is legal, sign_extend is legal
4462       // on that type, and the truncate to that type is both legal and free,
4463       // perform the transform.
4464       if ((ShiftAmt > 0) &&
4465           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4466           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4467           TLI.isTruncateFree(VT, TruncVT)) {
4468
4469         SDLoc DL(N);
4470         SDValue Amt = DAG.getConstant(ShiftAmt, DL,
4471             getShiftAmountTy(N0.getOperand(0).getValueType()));
4472         SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
4473                                     N0.getOperand(0), Amt);
4474         SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
4475                                     Shift);
4476         return DAG.getNode(ISD::SIGN_EXTEND, DL,
4477                            N->getValueType(0), Trunc);
4478       }
4479     }
4480   }
4481
4482   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4483   if (N1.getOpcode() == ISD::TRUNCATE &&
4484       N1.getOperand(0).getOpcode() == ISD::AND) {
4485     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4486     if (NewOp1.getNode())
4487       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4488   }
4489
4490   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4491   //      if c1 is equal to the number of bits the trunc removes
4492   if (N0.getOpcode() == ISD::TRUNCATE &&
4493       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4494        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4495       N0.getOperand(0).hasOneUse() &&
4496       N0.getOperand(0).getOperand(1).hasOneUse() &&
4497       N1C) {
4498     SDValue N0Op0 = N0.getOperand(0);
4499     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4500       unsigned LargeShiftVal = LargeShift->getZExtValue();
4501       EVT LargeVT = N0Op0.getValueType();
4502
4503       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4504         SDLoc DL(N);
4505         SDValue Amt =
4506           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(), DL,
4507                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4508         SDValue SRA = DAG.getNode(ISD::SRA, DL, LargeVT,
4509                                   N0Op0.getOperand(0), Amt);
4510         return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
4511       }
4512     }
4513   }
4514
4515   // Simplify, based on bits shifted out of the LHS.
4516   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4517     return SDValue(N, 0);
4518
4519
4520   // If the sign bit is known to be zero, switch this to a SRL.
4521   if (DAG.SignBitIsZero(N0))
4522     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4523
4524   if (N1C) {
4525     SDValue NewSRA = visitShiftByConstant(N, N1C);
4526     if (NewSRA.getNode())
4527       return NewSRA;
4528   }
4529
4530   return SDValue();
4531 }
4532
4533 SDValue DAGCombiner::visitSRL(SDNode *N) {
4534   SDValue N0 = N->getOperand(0);
4535   SDValue N1 = N->getOperand(1);
4536   EVT VT = N0.getValueType();
4537   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4538
4539   // fold vector ops
4540   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4541   if (VT.isVector()) {
4542     if (SDValue FoldedVOp = SimplifyVBinOp(N))
4543       return FoldedVOp;
4544
4545     N1C = isConstOrConstSplat(N1);
4546   }
4547
4548   // fold (srl c1, c2) -> c1 >>u c2
4549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4550   if (N0C && N1C)
4551     return DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, N0C, N1C);
4552   // fold (srl 0, x) -> 0
4553   if (N0C && N0C->isNullValue())
4554     return N0;
4555   // fold (srl x, c >= size(x)) -> undef
4556   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4557     return DAG.getUNDEF(VT);
4558   // fold (srl x, 0) -> x
4559   if (N1C && N1C->isNullValue())
4560     return N0;
4561   // if (srl x, c) is known to be zero, return 0
4562   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4563                                    APInt::getAllOnesValue(OpSizeInBits)))
4564     return DAG.getConstant(0, SDLoc(N), VT);
4565
4566   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4567   if (N1C && N0.getOpcode() == ISD::SRL) {
4568     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4569       uint64_t c1 = N01C->getZExtValue();
4570       uint64_t c2 = N1C->getZExtValue();
4571       SDLoc DL(N);
4572       if (c1 + c2 >= OpSizeInBits)
4573         return DAG.getConstant(0, DL, VT);
4574       return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
4575                          DAG.getConstant(c1 + c2, DL, N1.getValueType()));
4576     }
4577   }
4578
4579   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4580   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4581       N0.getOperand(0).getOpcode() == ISD::SRL &&
4582       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4583     uint64_t c1 =
4584       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4585     uint64_t c2 = N1C->getZExtValue();
4586     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4587     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4588     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4589     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4590     if (c1 + OpSizeInBits == InnerShiftSize) {
4591       SDLoc DL(N0);
4592       if (c1 + c2 >= InnerShiftSize)
4593         return DAG.getConstant(0, DL, VT);
4594       return DAG.getNode(ISD::TRUNCATE, DL, VT,
4595                          DAG.getNode(ISD::SRL, DL, InnerShiftVT,
4596                                      N0.getOperand(0)->getOperand(0),
4597                                      DAG.getConstant(c1 + c2, DL,
4598                                                      ShiftCountVT)));
4599     }
4600   }
4601
4602   // fold (srl (shl x, c), c) -> (and x, cst2)
4603   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4604     unsigned BitSize = N0.getScalarValueSizeInBits();
4605     if (BitSize <= 64) {
4606       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4607       SDLoc DL(N);
4608       return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0),
4609                          DAG.getConstant(~0ULL >> ShAmt, DL, VT));
4610     }
4611   }
4612
4613   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4614   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4615     // Shifting in all undef bits?
4616     EVT SmallVT = N0.getOperand(0).getValueType();
4617     unsigned BitSize = SmallVT.getScalarSizeInBits();
4618     if (N1C->getZExtValue() >= BitSize)
4619       return DAG.getUNDEF(VT);
4620
4621     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4622       uint64_t ShiftAmt = N1C->getZExtValue();
4623       SDLoc DL0(N0);
4624       SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
4625                                        N0.getOperand(0),
4626                           DAG.getConstant(ShiftAmt, DL0,
4627                                           getShiftAmountTy(SmallVT)));
4628       AddToWorklist(SmallShift.getNode());
4629       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4630       SDLoc DL(N);
4631       return DAG.getNode(ISD::AND, DL, VT,
4632                          DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
4633                          DAG.getConstant(Mask, DL, VT));
4634     }
4635   }
4636
4637   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4638   // bit, which is unmodified by sra.
4639   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4640     if (N0.getOpcode() == ISD::SRA)
4641       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4642   }
4643
4644   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4645   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4646       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4647     APInt KnownZero, KnownOne;
4648     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4649
4650     // If any of the input bits are KnownOne, then the input couldn't be all
4651     // zeros, thus the result of the srl will always be zero.
4652     if (KnownOne.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
4653
4654     // If all of the bits input the to ctlz node are known to be zero, then
4655     // the result of the ctlz is "32" and the result of the shift is one.
4656     APInt UnknownBits = ~KnownZero;
4657     if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
4658
4659     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4660     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4661       // Okay, we know that only that the single bit specified by UnknownBits
4662       // could be set on input to the CTLZ node. If this bit is set, the SRL
4663       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4664       // to an SRL/XOR pair, which is likely to simplify more.
4665       unsigned ShAmt = UnknownBits.countTrailingZeros();
4666       SDValue Op = N0.getOperand(0);
4667
4668       if (ShAmt) {
4669         SDLoc DL(N0);
4670         Op = DAG.getNode(ISD::SRL, DL, VT, Op,
4671                   DAG.getConstant(ShAmt, DL,
4672                                   getShiftAmountTy(Op.getValueType())));
4673         AddToWorklist(Op.getNode());
4674       }
4675
4676       SDLoc DL(N);
4677       return DAG.getNode(ISD::XOR, DL, VT,
4678                          Op, DAG.getConstant(1, DL, VT));
4679     }
4680   }
4681
4682   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4683   if (N1.getOpcode() == ISD::TRUNCATE &&
4684       N1.getOperand(0).getOpcode() == ISD::AND) {
4685     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4686     if (NewOp1.getNode())
4687       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4688   }
4689
4690   // fold operands of srl based on knowledge that the low bits are not
4691   // demanded.
4692   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4693     return SDValue(N, 0);
4694
4695   if (N1C) {
4696     SDValue NewSRL = visitShiftByConstant(N, N1C);
4697     if (NewSRL.getNode())
4698       return NewSRL;
4699   }
4700
4701   // Attempt to convert a srl of a load into a narrower zero-extending load.
4702   SDValue NarrowLoad = ReduceLoadWidth(N);
4703   if (NarrowLoad.getNode())
4704     return NarrowLoad;
4705
4706   // Here is a common situation. We want to optimize:
4707   //
4708   //   %a = ...
4709   //   %b = and i32 %a, 2
4710   //   %c = srl i32 %b, 1
4711   //   brcond i32 %c ...
4712   //
4713   // into
4714   //
4715   //   %a = ...
4716   //   %b = and %a, 2
4717   //   %c = setcc eq %b, 0
4718   //   brcond %c ...
4719   //
4720   // However when after the source operand of SRL is optimized into AND, the SRL
4721   // itself may not be optimized further. Look for it and add the BRCOND into
4722   // the worklist.
4723   if (N->hasOneUse()) {
4724     SDNode *Use = *N->use_begin();
4725     if (Use->getOpcode() == ISD::BRCOND)
4726       AddToWorklist(Use);
4727     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4728       // Also look pass the truncate.
4729       Use = *Use->use_begin();
4730       if (Use->getOpcode() == ISD::BRCOND)
4731         AddToWorklist(Use);
4732     }
4733   }
4734
4735   return SDValue();
4736 }
4737
4738 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4739   SDValue N0 = N->getOperand(0);
4740   EVT VT = N->getValueType(0);
4741
4742   // fold (ctlz c1) -> c2
4743   if (isa<ConstantSDNode>(N0))
4744     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4745   return SDValue();
4746 }
4747
4748 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4749   SDValue N0 = N->getOperand(0);
4750   EVT VT = N->getValueType(0);
4751
4752   // fold (ctlz_zero_undef c1) -> c2
4753   if (isa<ConstantSDNode>(N0))
4754     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4755   return SDValue();
4756 }
4757
4758 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4759   SDValue N0 = N->getOperand(0);
4760   EVT VT = N->getValueType(0);
4761
4762   // fold (cttz c1) -> c2
4763   if (isa<ConstantSDNode>(N0))
4764     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4765   return SDValue();
4766 }
4767
4768 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4769   SDValue N0 = N->getOperand(0);
4770   EVT VT = N->getValueType(0);
4771
4772   // fold (cttz_zero_undef c1) -> c2
4773   if (isa<ConstantSDNode>(N0))
4774     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4775   return SDValue();
4776 }
4777
4778 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4779   SDValue N0 = N->getOperand(0);
4780   EVT VT = N->getValueType(0);
4781
4782   // fold (ctpop c1) -> c2
4783   if (isa<ConstantSDNode>(N0))
4784     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4785   return SDValue();
4786 }
4787
4788
4789 /// \brief Generate Min/Max node
4790 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4791                                    SDValue True, SDValue False,
4792                                    ISD::CondCode CC, const TargetLowering &TLI,
4793                                    SelectionDAG &DAG) {
4794   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4795     return SDValue();
4796
4797   switch (CC) {
4798   case ISD::SETOLT:
4799   case ISD::SETOLE:
4800   case ISD::SETLT:
4801   case ISD::SETLE:
4802   case ISD::SETULT:
4803   case ISD::SETULE: {
4804     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4805     if (TLI.isOperationLegal(Opcode, VT))
4806       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4807     return SDValue();
4808   }
4809   case ISD::SETOGT:
4810   case ISD::SETOGE:
4811   case ISD::SETGT:
4812   case ISD::SETGE:
4813   case ISD::SETUGT:
4814   case ISD::SETUGE: {
4815     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4816     if (TLI.isOperationLegal(Opcode, VT))
4817       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4818     return SDValue();
4819   }
4820   default:
4821     return SDValue();
4822   }
4823 }
4824
4825 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4826   SDValue N0 = N->getOperand(0);
4827   SDValue N1 = N->getOperand(1);
4828   SDValue N2 = N->getOperand(2);
4829   EVT VT = N->getValueType(0);
4830   EVT VT0 = N0.getValueType();
4831
4832   // fold (select C, X, X) -> X
4833   if (N1 == N2)
4834     return N1;
4835   // fold (select true, X, Y) -> X
4836   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4837   if (N0C && !N0C->isNullValue())
4838     return N1;
4839   // fold (select false, X, Y) -> Y
4840   if (N0C && N0C->isNullValue())
4841     return N2;
4842   // fold (select C, 1, X) -> (or C, X)
4843   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4844   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4845     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4846   // fold (select C, 0, 1) -> (xor C, 1)
4847   // We can't do this reliably if integer based booleans have different contents
4848   // to floating point based booleans. This is because we can't tell whether we
4849   // have an integer-based boolean or a floating-point-based boolean unless we
4850   // can find the SETCC that produced it and inspect its operands. This is
4851   // fairly easy if C is the SETCC node, but it can potentially be
4852   // undiscoverable (or not reasonably discoverable). For example, it could be
4853   // in another basic block or it could require searching a complicated
4854   // expression.
4855   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4856   if (VT.isInteger() &&
4857       (VT0 == MVT::i1 || (VT0.isInteger() &&
4858                           TLI.getBooleanContents(false, false) ==
4859                               TLI.getBooleanContents(false, true) &&
4860                           TLI.getBooleanContents(false, false) ==
4861                               TargetLowering::ZeroOrOneBooleanContent)) &&
4862       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4863     SDValue XORNode;
4864     if (VT == VT0) {
4865       SDLoc DL(N);
4866       return DAG.getNode(ISD::XOR, DL, VT0,
4867                          N0, DAG.getConstant(1, DL, VT0));
4868     }
4869     SDLoc DL0(N0);
4870     XORNode = DAG.getNode(ISD::XOR, DL0, VT0,
4871                           N0, DAG.getConstant(1, DL0, VT0));
4872     AddToWorklist(XORNode.getNode());
4873     if (VT.bitsGT(VT0))
4874       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4875     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4876   }
4877   // fold (select C, 0, X) -> (and (not C), X)
4878   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4879     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4880     AddToWorklist(NOTNode.getNode());
4881     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4882   }
4883   // fold (select C, X, 1) -> (or (not C), X)
4884   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4885     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4886     AddToWorklist(NOTNode.getNode());
4887     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4888   }
4889   // fold (select C, X, 0) -> (and C, X)
4890   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4891     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4892   // fold (select X, X, Y) -> (or X, Y)
4893   // fold (select X, 1, Y) -> (or X, Y)
4894   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4895     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4896   // fold (select X, Y, X) -> (and X, Y)
4897   // fold (select X, Y, 0) -> (and X, Y)
4898   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4899     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4900
4901   // If we can fold this based on the true/false value, do so.
4902   if (SimplifySelectOps(N, N1, N2))
4903     return SDValue(N, 0);  // Don't revisit N.
4904
4905   // fold selects based on a setcc into other things, such as min/max/abs
4906   if (N0.getOpcode() == ISD::SETCC) {
4907     // select x, y (fcmp lt x, y) -> fminnum x, y
4908     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4909     //
4910     // This is OK if we don't care about what happens if either operand is a
4911     // NaN.
4912     //
4913
4914     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4915     // no signed zeros as well as no nans.
4916     const TargetOptions &Options = DAG.getTarget().Options;
4917     if (Options.UnsafeFPMath &&
4918         VT.isFloatingPoint() && N0.hasOneUse() &&
4919         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4920       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4921
4922       SDValue FMinMax =
4923           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4924                               N1, N2, CC, TLI, DAG);
4925       if (FMinMax)
4926         return FMinMax;
4927     }
4928
4929     if ((!LegalOperations &&
4930          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4931         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4932       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4933                          N0.getOperand(0), N0.getOperand(1),
4934                          N1, N2, N0.getOperand(2));
4935     return SimplifySelect(SDLoc(N), N0, N1, N2);
4936   }
4937
4938   if (VT0 == MVT::i1) {
4939     if (TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4940       // select (and Cond0, Cond1), X, Y
4941       //   -> select Cond0, (select Cond1, X, Y), Y
4942       if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
4943         SDValue Cond0 = N0->getOperand(0);
4944         SDValue Cond1 = N0->getOperand(1);
4945         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4946                                           N1.getValueType(), Cond1, N1, N2);
4947         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0,
4948                            InnerSelect, N2);
4949       }
4950       // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
4951       if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
4952         SDValue Cond0 = N0->getOperand(0);
4953         SDValue Cond1 = N0->getOperand(1);
4954         SDValue InnerSelect = DAG.getNode(ISD::SELECT, SDLoc(N),
4955                                           N1.getValueType(), Cond1, N1, N2);
4956         return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Cond0, N1,
4957                            InnerSelect);
4958       }
4959     }
4960
4961     // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
4962     if (N1->getOpcode() == ISD::SELECT) {
4963       SDValue N1_0 = N1->getOperand(0);
4964       SDValue N1_1 = N1->getOperand(1);
4965       SDValue N1_2 = N1->getOperand(2);
4966       if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
4967         // Create the actual and node if we can generate good code for it.
4968         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4969           SDValue And = DAG.getNode(ISD::AND, SDLoc(N), N0.getValueType(),
4970                                     N0, N1_0);
4971           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), And,
4972                              N1_1, N2);
4973         }
4974         // Otherwise see if we can optimize the "and" to a better pattern.
4975         if (SDValue Combined = visitANDLike(N0, N1_0, N))
4976           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4977                              N1_1, N2);
4978       }
4979     }
4980     // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
4981     if (N2->getOpcode() == ISD::SELECT) {
4982       SDValue N2_0 = N2->getOperand(0);
4983       SDValue N2_1 = N2->getOperand(1);
4984       SDValue N2_2 = N2->getOperand(2);
4985       if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
4986         // Create the actual or node if we can generate good code for it.
4987         if (!TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT)) {
4988           SDValue Or = DAG.getNode(ISD::OR, SDLoc(N), N0.getValueType(),
4989                                    N0, N2_0);
4990           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Or,
4991                              N1, N2_2);
4992         }
4993         // Otherwise see if we can optimize to a better pattern.
4994         if (SDValue Combined = visitORLike(N0, N2_0, N))
4995           return DAG.getNode(ISD::SELECT, SDLoc(N), N1.getValueType(), Combined,
4996                              N1, N2_2);
4997       }
4998     }
4999   }
5000
5001   return SDValue();
5002 }
5003
5004 static
5005 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
5006   SDLoc DL(N);
5007   EVT LoVT, HiVT;
5008   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
5009
5010   // Split the inputs.
5011   SDValue Lo, Hi, LL, LH, RL, RH;
5012   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
5013   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
5014
5015   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
5016   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
5017
5018   return std::make_pair(Lo, Hi);
5019 }
5020
5021 // This function assumes all the vselect's arguments are CONCAT_VECTOR
5022 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
5023 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
5024   SDLoc dl(N);
5025   SDValue Cond = N->getOperand(0);
5026   SDValue LHS = N->getOperand(1);
5027   SDValue RHS = N->getOperand(2);
5028   EVT VT = N->getValueType(0);
5029   int NumElems = VT.getVectorNumElements();
5030   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
5031          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
5032          Cond.getOpcode() == ISD::BUILD_VECTOR);
5033
5034   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
5035   // binary ones here.
5036   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
5037     return SDValue();
5038
5039   // We're sure we have an even number of elements due to the
5040   // concat_vectors we have as arguments to vselect.
5041   // Skip BV elements until we find one that's not an UNDEF
5042   // After we find an UNDEF element, keep looping until we get to half the
5043   // length of the BV and see if all the non-undef nodes are the same.
5044   ConstantSDNode *BottomHalf = nullptr;
5045   for (int i = 0; i < NumElems / 2; ++i) {
5046     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5047       continue;
5048
5049     if (BottomHalf == nullptr)
5050       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5051     else if (Cond->getOperand(i).getNode() != BottomHalf)
5052       return SDValue();
5053   }
5054
5055   // Do the same for the second half of the BuildVector
5056   ConstantSDNode *TopHalf = nullptr;
5057   for (int i = NumElems / 2; i < NumElems; ++i) {
5058     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
5059       continue;
5060
5061     if (TopHalf == nullptr)
5062       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
5063     else if (Cond->getOperand(i).getNode() != TopHalf)
5064       return SDValue();
5065   }
5066
5067   assert(TopHalf && BottomHalf &&
5068          "One half of the selector was all UNDEFs and the other was all the "
5069          "same value. This should have been addressed before this function.");
5070   return DAG.getNode(
5071       ISD::CONCAT_VECTORS, dl, VT,
5072       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
5073       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
5074 }
5075
5076 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
5077
5078   if (Level >= AfterLegalizeTypes)
5079     return SDValue();
5080
5081   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
5082   SDValue Mask = MST->getMask();
5083   SDValue Data  = MST->getValue();
5084   SDLoc DL(N);
5085
5086   // If the MSTORE data type requires splitting and the mask is provided by a
5087   // SETCC, then split both nodes and its operands before legalization. This
5088   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5089   // and enables future optimizations (e.g. min/max pattern matching on X86).
5090   if (Mask.getOpcode() == ISD::SETCC) {
5091
5092     // Check if any splitting is required.
5093     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
5094         TargetLowering::TypeSplitVector)
5095       return SDValue();
5096
5097     SDValue MaskLo, MaskHi, Lo, Hi;
5098     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5099
5100     EVT LoVT, HiVT;
5101     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
5102
5103     SDValue Chain = MST->getChain();
5104     SDValue Ptr   = MST->getBasePtr();
5105
5106     EVT MemoryVT = MST->getMemoryVT();
5107     unsigned Alignment = MST->getOriginalAlignment();
5108
5109     // if Alignment is equal to the vector size,
5110     // take the half of it for the second part
5111     unsigned SecondHalfAlignment =
5112       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
5113          Alignment/2 : Alignment;
5114
5115     EVT LoMemVT, HiMemVT;
5116     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5117
5118     SDValue DataLo, DataHi;
5119     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
5120
5121     MachineMemOperand *MMO = DAG.getMachineFunction().
5122       getMachineMemOperand(MST->getPointerInfo(),
5123                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
5124                            Alignment, MST->getAAInfo(), MST->getRanges());
5125
5126     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
5127                             MST->isTruncatingStore());
5128
5129     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5130     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5131                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5132
5133     MMO = DAG.getMachineFunction().
5134       getMachineMemOperand(MST->getPointerInfo(),
5135                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
5136                            SecondHalfAlignment, MST->getAAInfo(),
5137                            MST->getRanges());
5138
5139     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
5140                             MST->isTruncatingStore());
5141
5142     AddToWorklist(Lo.getNode());
5143     AddToWorklist(Hi.getNode());
5144
5145     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
5146   }
5147   return SDValue();
5148 }
5149
5150 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
5151
5152   if (Level >= AfterLegalizeTypes)
5153     return SDValue();
5154
5155   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
5156   SDValue Mask = MLD->getMask();
5157   SDLoc DL(N);
5158
5159   // If the MLOAD result requires splitting and the mask is provided by a
5160   // SETCC, then split both nodes and its operands before legalization. This
5161   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5162   // and enables future optimizations (e.g. min/max pattern matching on X86).
5163
5164   if (Mask.getOpcode() == ISD::SETCC) {
5165     EVT VT = N->getValueType(0);
5166
5167     // Check if any splitting is required.
5168     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5169         TargetLowering::TypeSplitVector)
5170       return SDValue();
5171
5172     SDValue MaskLo, MaskHi, Lo, Hi;
5173     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
5174
5175     SDValue Src0 = MLD->getSrc0();
5176     SDValue Src0Lo, Src0Hi;
5177     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
5178
5179     EVT LoVT, HiVT;
5180     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
5181
5182     SDValue Chain = MLD->getChain();
5183     SDValue Ptr   = MLD->getBasePtr();
5184     EVT MemoryVT = MLD->getMemoryVT();
5185     unsigned Alignment = MLD->getOriginalAlignment();
5186
5187     // if Alignment is equal to the vector size,
5188     // take the half of it for the second part
5189     unsigned SecondHalfAlignment =
5190       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
5191          Alignment/2 : Alignment;
5192
5193     EVT LoMemVT, HiMemVT;
5194     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
5195
5196     MachineMemOperand *MMO = DAG.getMachineFunction().
5197     getMachineMemOperand(MLD->getPointerInfo(),
5198                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
5199                          Alignment, MLD->getAAInfo(), MLD->getRanges());
5200
5201     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
5202                            ISD::NON_EXTLOAD);
5203
5204     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
5205     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
5206                       DAG.getConstant(IncrementSize, DL, Ptr.getValueType()));
5207
5208     MMO = DAG.getMachineFunction().
5209     getMachineMemOperand(MLD->getPointerInfo(),
5210                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
5211                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
5212
5213     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
5214                            ISD::NON_EXTLOAD);
5215
5216     AddToWorklist(Lo.getNode());
5217     AddToWorklist(Hi.getNode());
5218
5219     // Build a factor node to remember that this load is independent of the
5220     // other one.
5221     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
5222                         Hi.getValue(1));
5223
5224     // Legalized the chain result - switch anything that used the old chain to
5225     // use the new one.
5226     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
5227
5228     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5229
5230     SDValue RetOps[] = { LoadRes, Chain };
5231     return DAG.getMergeValues(RetOps, DL);
5232   }
5233   return SDValue();
5234 }
5235
5236 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
5237   SDValue N0 = N->getOperand(0);
5238   SDValue N1 = N->getOperand(1);
5239   SDValue N2 = N->getOperand(2);
5240   SDLoc DL(N);
5241
5242   // Canonicalize integer abs.
5243   // vselect (setg[te] X,  0),  X, -X ->
5244   // vselect (setgt    X, -1),  X, -X ->
5245   // vselect (setl[te] X,  0), -X,  X ->
5246   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5247   if (N0.getOpcode() == ISD::SETCC) {
5248     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5249     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5250     bool isAbs = false;
5251     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5252
5253     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5254          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5255         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5256       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5257     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5258              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5259       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5260
5261     if (isAbs) {
5262       EVT VT = LHS.getValueType();
5263       SDValue Shift = DAG.getNode(
5264           ISD::SRA, DL, VT, LHS,
5265           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, DL, VT));
5266       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5267       AddToWorklist(Shift.getNode());
5268       AddToWorklist(Add.getNode());
5269       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5270     }
5271   }
5272
5273   if (SimplifySelectOps(N, N1, N2))
5274     return SDValue(N, 0);  // Don't revisit N.
5275
5276   // If the VSELECT result requires splitting and the mask is provided by a
5277   // SETCC, then split both nodes and its operands before legalization. This
5278   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5279   // and enables future optimizations (e.g. min/max pattern matching on X86).
5280   if (N0.getOpcode() == ISD::SETCC) {
5281     EVT VT = N->getValueType(0);
5282
5283     // Check if any splitting is required.
5284     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5285         TargetLowering::TypeSplitVector)
5286       return SDValue();
5287
5288     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5289     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5290     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5291     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5292
5293     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5294     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5295
5296     // Add the new VSELECT nodes to the work list in case they need to be split
5297     // again.
5298     AddToWorklist(Lo.getNode());
5299     AddToWorklist(Hi.getNode());
5300
5301     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5302   }
5303
5304   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5305   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5306     return N1;
5307   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5308   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5309     return N2;
5310
5311   // The ConvertSelectToConcatVector function is assuming both the above
5312   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5313   // and addressed.
5314   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5315       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5316       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5317     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5318     if (CV.getNode())
5319       return CV;
5320   }
5321
5322   return SDValue();
5323 }
5324
5325 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5326   SDValue N0 = N->getOperand(0);
5327   SDValue N1 = N->getOperand(1);
5328   SDValue N2 = N->getOperand(2);
5329   SDValue N3 = N->getOperand(3);
5330   SDValue N4 = N->getOperand(4);
5331   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5332
5333   // fold select_cc lhs, rhs, x, x, cc -> x
5334   if (N2 == N3)
5335     return N2;
5336
5337   // Determine if the condition we're dealing with is constant
5338   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5339                               N0, N1, CC, SDLoc(N), false);
5340   if (SCC.getNode()) {
5341     AddToWorklist(SCC.getNode());
5342
5343     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5344       if (!SCCC->isNullValue())
5345         return N2;    // cond always true -> true val
5346       else
5347         return N3;    // cond always false -> false val
5348     } else if (SCC->getOpcode() == ISD::UNDEF) {
5349       // When the condition is UNDEF, just return the first operand. This is
5350       // coherent the DAG creation, no setcc node is created in this case
5351       return N2;
5352     } else if (SCC.getOpcode() == ISD::SETCC) {
5353       // Fold to a simpler select_cc
5354       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5355                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5356                          SCC.getOperand(2));
5357     }
5358   }
5359
5360   // If we can fold this based on the true/false value, do so.
5361   if (SimplifySelectOps(N, N2, N3))
5362     return SDValue(N, 0);  // Don't revisit N.
5363
5364   // fold select_cc into other things, such as min/max/abs
5365   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5366 }
5367
5368 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5369   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5370                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5371                        SDLoc(N));
5372 }
5373
5374 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5375 // dag node into a ConstantSDNode or a build_vector of constants.
5376 // This function is called by the DAGCombiner when visiting sext/zext/aext
5377 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5378 // Vector extends are not folded if operations are legal; this is to
5379 // avoid introducing illegal build_vector dag nodes.
5380 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5381                                          SelectionDAG &DAG, bool LegalTypes,
5382                                          bool LegalOperations) {
5383   unsigned Opcode = N->getOpcode();
5384   SDValue N0 = N->getOperand(0);
5385   EVT VT = N->getValueType(0);
5386
5387   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5388          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5389
5390   // fold (sext c1) -> c1
5391   // fold (zext c1) -> c1
5392   // fold (aext c1) -> c1
5393   if (isa<ConstantSDNode>(N0))
5394     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5395
5396   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5397   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5398   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5399   EVT SVT = VT.getScalarType();
5400   if (!(VT.isVector() &&
5401       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5402       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5403     return nullptr;
5404
5405   // We can fold this node into a build_vector.
5406   unsigned VTBits = SVT.getSizeInBits();
5407   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5408   unsigned ShAmt = VTBits - EVTBits;
5409   SmallVector<SDValue, 8> Elts;
5410   unsigned NumElts = N0->getNumOperands();
5411   SDLoc DL(N);
5412
5413   for (unsigned i=0; i != NumElts; ++i) {
5414     SDValue Op = N0->getOperand(i);
5415     if (Op->getOpcode() == ISD::UNDEF) {
5416       Elts.push_back(DAG.getUNDEF(SVT));
5417       continue;
5418     }
5419
5420     SDLoc DL(Op);
5421     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5422     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5423     if (Opcode == ISD::SIGN_EXTEND)
5424       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5425                                      DL, SVT));
5426     else
5427       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5428                                      DL, SVT));
5429   }
5430
5431   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5432 }
5433
5434 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5435 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5436 // transformation. Returns true if extension are possible and the above
5437 // mentioned transformation is profitable.
5438 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5439                                     unsigned ExtOpc,
5440                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5441                                     const TargetLowering &TLI) {
5442   bool HasCopyToRegUses = false;
5443   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5444   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5445                             UE = N0.getNode()->use_end();
5446        UI != UE; ++UI) {
5447     SDNode *User = *UI;
5448     if (User == N)
5449       continue;
5450     if (UI.getUse().getResNo() != N0.getResNo())
5451       continue;
5452     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5453     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5454       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5455       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5456         // Sign bits will be lost after a zext.
5457         return false;
5458       bool Add = false;
5459       for (unsigned i = 0; i != 2; ++i) {
5460         SDValue UseOp = User->getOperand(i);
5461         if (UseOp == N0)
5462           continue;
5463         if (!isa<ConstantSDNode>(UseOp))
5464           return false;
5465         Add = true;
5466       }
5467       if (Add)
5468         ExtendNodes.push_back(User);
5469       continue;
5470     }
5471     // If truncates aren't free and there are users we can't
5472     // extend, it isn't worthwhile.
5473     if (!isTruncFree)
5474       return false;
5475     // Remember if this value is live-out.
5476     if (User->getOpcode() == ISD::CopyToReg)
5477       HasCopyToRegUses = true;
5478   }
5479
5480   if (HasCopyToRegUses) {
5481     bool BothLiveOut = false;
5482     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5483          UI != UE; ++UI) {
5484       SDUse &Use = UI.getUse();
5485       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5486         BothLiveOut = true;
5487         break;
5488       }
5489     }
5490     if (BothLiveOut)
5491       // Both unextended and extended values are live out. There had better be
5492       // a good reason for the transformation.
5493       return ExtendNodes.size();
5494   }
5495   return true;
5496 }
5497
5498 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5499                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5500                                   ISD::NodeType ExtType) {
5501   // Extend SetCC uses if necessary.
5502   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5503     SDNode *SetCC = SetCCs[i];
5504     SmallVector<SDValue, 4> Ops;
5505
5506     for (unsigned j = 0; j != 2; ++j) {
5507       SDValue SOp = SetCC->getOperand(j);
5508       if (SOp == Trunc)
5509         Ops.push_back(ExtLoad);
5510       else
5511         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5512     }
5513
5514     Ops.push_back(SetCC->getOperand(2));
5515     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5516   }
5517 }
5518
5519 // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
5520 SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
5521   SDValue N0 = N->getOperand(0);
5522   EVT DstVT = N->getValueType(0);
5523   EVT SrcVT = N0.getValueType();
5524
5525   assert((N->getOpcode() == ISD::SIGN_EXTEND ||
5526           N->getOpcode() == ISD::ZERO_EXTEND) &&
5527          "Unexpected node type (not an extend)!");
5528
5529   // fold (sext (load x)) to multiple smaller sextloads; same for zext.
5530   // For example, on a target with legal v4i32, but illegal v8i32, turn:
5531   //   (v8i32 (sext (v8i16 (load x))))
5532   // into:
5533   //   (v8i32 (concat_vectors (v4i32 (sextload x)),
5534   //                          (v4i32 (sextload (x + 16)))))
5535   // Where uses of the original load, i.e.:
5536   //   (v8i16 (load x))
5537   // are replaced with:
5538   //   (v8i16 (truncate
5539   //     (v8i32 (concat_vectors (v4i32 (sextload x)),
5540   //                            (v4i32 (sextload (x + 16)))))))
5541   //
5542   // This combine is only applicable to illegal, but splittable, vectors.
5543   // All legal types, and illegal non-vector types, are handled elsewhere.
5544   // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
5545   //
5546   if (N0->getOpcode() != ISD::LOAD)
5547     return SDValue();
5548
5549   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5550
5551   if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
5552       !N0.hasOneUse() || LN0->isVolatile() || !DstVT.isVector() ||
5553       !DstVT.isPow2VectorType() || !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
5554     return SDValue();
5555
5556   SmallVector<SDNode *, 4> SetCCs;
5557   if (!ExtendUsesToFormExtLoad(N, N0, N->getOpcode(), SetCCs, TLI))
5558     return SDValue();
5559
5560   ISD::LoadExtType ExtType =
5561       N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
5562
5563   // Try to split the vector types to get down to legal types.
5564   EVT SplitSrcVT = SrcVT;
5565   EVT SplitDstVT = DstVT;
5566   while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
5567          SplitSrcVT.getVectorNumElements() > 1) {
5568     SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
5569     SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
5570   }
5571
5572   if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
5573     return SDValue();
5574
5575   SDLoc DL(N);
5576   const unsigned NumSplits =
5577       DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
5578   const unsigned Stride = SplitSrcVT.getStoreSize();
5579   SmallVector<SDValue, 4> Loads;
5580   SmallVector<SDValue, 4> Chains;
5581
5582   SDValue BasePtr = LN0->getBasePtr();
5583   for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
5584     const unsigned Offset = Idx * Stride;
5585     const unsigned Align = MinAlign(LN0->getAlignment(), Offset);
5586
5587     SDValue SplitLoad = DAG.getExtLoad(
5588         ExtType, DL, SplitDstVT, LN0->getChain(), BasePtr,
5589         LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT,
5590         LN0->isVolatile(), LN0->isNonTemporal(), LN0->isInvariant(),
5591         Align, LN0->getAAInfo());
5592
5593     BasePtr = DAG.getNode(ISD::ADD, DL, BasePtr.getValueType(), BasePtr,
5594                           DAG.getConstant(Stride, DL, BasePtr.getValueType()));
5595
5596     Loads.push_back(SplitLoad.getValue(0));
5597     Chains.push_back(SplitLoad.getValue(1));
5598   }
5599
5600   SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
5601   SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
5602
5603   CombineTo(N, NewValue);
5604
5605   // Replace uses of the original load (before extension)
5606   // with a truncate of the concatenated sextloaded vectors.
5607   SDValue Trunc =
5608       DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
5609   CombineTo(N0.getNode(), Trunc, NewChain);
5610   ExtendSetCCUses(SetCCs, Trunc, NewValue, DL,
5611                   (ISD::NodeType)N->getOpcode());
5612   return SDValue(N, 0); // Return N so it doesn't get rechecked!
5613 }
5614
5615 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5616   SDValue N0 = N->getOperand(0);
5617   EVT VT = N->getValueType(0);
5618
5619   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5620                                               LegalOperations))
5621     return SDValue(Res, 0);
5622
5623   // fold (sext (sext x)) -> (sext x)
5624   // fold (sext (aext x)) -> (sext x)
5625   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5626     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5627                        N0.getOperand(0));
5628
5629   if (N0.getOpcode() == ISD::TRUNCATE) {
5630     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5631     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5632     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5633     if (NarrowLoad.getNode()) {
5634       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5635       if (NarrowLoad.getNode() != N0.getNode()) {
5636         CombineTo(N0.getNode(), NarrowLoad);
5637         // CombineTo deleted the truncate, if needed, but not what's under it.
5638         AddToWorklist(oye);
5639       }
5640       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5641     }
5642
5643     // See if the value being truncated is already sign extended.  If so, just
5644     // eliminate the trunc/sext pair.
5645     SDValue Op = N0.getOperand(0);
5646     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5647     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5648     unsigned DestBits = VT.getScalarType().getSizeInBits();
5649     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5650
5651     if (OpBits == DestBits) {
5652       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5653       // bits, it is already ready.
5654       if (NumSignBits > DestBits-MidBits)
5655         return Op;
5656     } else if (OpBits < DestBits) {
5657       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5658       // bits, just sext from i32.
5659       if (NumSignBits > OpBits-MidBits)
5660         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5661     } else {
5662       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5663       // bits, just truncate to i32.
5664       if (NumSignBits > OpBits-MidBits)
5665         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5666     }
5667
5668     // fold (sext (truncate x)) -> (sextinreg x).
5669     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5670                                                  N0.getValueType())) {
5671       if (OpBits < DestBits)
5672         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5673       else if (OpBits > DestBits)
5674         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5675       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5676                          DAG.getValueType(N0.getValueType()));
5677     }
5678   }
5679
5680   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5681   // Only generate vector extloads when 1) they're legal, and 2) they are
5682   // deemed desirable by the target.
5683   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5684       ((!LegalOperations && !VT.isVector() &&
5685         !cast<LoadSDNode>(N0)->isVolatile()) ||
5686        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5687     bool DoXform = true;
5688     SmallVector<SDNode*, 4> SetCCs;
5689     if (!N0.hasOneUse())
5690       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5691     if (VT.isVector())
5692       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5693     if (DoXform) {
5694       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5695       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5696                                        LN0->getChain(),
5697                                        LN0->getBasePtr(), N0.getValueType(),
5698                                        LN0->getMemOperand());
5699       CombineTo(N, ExtLoad);
5700       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5701                                   N0.getValueType(), ExtLoad);
5702       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5703       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5704                       ISD::SIGN_EXTEND);
5705       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5706     }
5707   }
5708
5709   // fold (sext (load x)) to multiple smaller sextloads.
5710   // Only on illegal but splittable vectors.
5711   if (SDValue ExtLoad = CombineExtLoad(N))
5712     return ExtLoad;
5713
5714   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5715   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5716   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5717       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5718     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5719     EVT MemVT = LN0->getMemoryVT();
5720     if ((!LegalOperations && !LN0->isVolatile()) ||
5721         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5722       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5723                                        LN0->getChain(),
5724                                        LN0->getBasePtr(), MemVT,
5725                                        LN0->getMemOperand());
5726       CombineTo(N, ExtLoad);
5727       CombineTo(N0.getNode(),
5728                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5729                             N0.getValueType(), ExtLoad),
5730                 ExtLoad.getValue(1));
5731       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5732     }
5733   }
5734
5735   // fold (sext (and/or/xor (load x), cst)) ->
5736   //      (and/or/xor (sextload x), (sext cst))
5737   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5738        N0.getOpcode() == ISD::XOR) &&
5739       isa<LoadSDNode>(N0.getOperand(0)) &&
5740       N0.getOperand(1).getOpcode() == ISD::Constant &&
5741       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5742       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5743     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5744     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5745       bool DoXform = true;
5746       SmallVector<SDNode*, 4> SetCCs;
5747       if (!N0.hasOneUse())
5748         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5749                                           SetCCs, TLI);
5750       if (DoXform) {
5751         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5752                                          LN0->getChain(), LN0->getBasePtr(),
5753                                          LN0->getMemoryVT(),
5754                                          LN0->getMemOperand());
5755         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5756         Mask = Mask.sext(VT.getSizeInBits());
5757         SDLoc DL(N);
5758         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
5759                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
5760         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5761                                     SDLoc(N0.getOperand(0)),
5762                                     N0.getOperand(0).getValueType(), ExtLoad);
5763         CombineTo(N, And);
5764         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5765         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
5766                         ISD::SIGN_EXTEND);
5767         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5768       }
5769     }
5770   }
5771
5772   if (N0.getOpcode() == ISD::SETCC) {
5773     EVT N0VT = N0.getOperand(0).getValueType();
5774     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5775     // Only do this before legalize for now.
5776     if (VT.isVector() && !LegalOperations &&
5777         TLI.getBooleanContents(N0VT) ==
5778             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5779       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5780       // of the same size as the compared operands. Only optimize sext(setcc())
5781       // if this is the case.
5782       EVT SVT = getSetCCResultType(N0VT);
5783
5784       // We know that the # elements of the results is the same as the
5785       // # elements of the compare (and the # elements of the compare result
5786       // for that matter).  Check to see that they are the same size.  If so,
5787       // we know that the element size of the sext'd result matches the
5788       // element size of the compare operands.
5789       if (VT.getSizeInBits() == SVT.getSizeInBits())
5790         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5791                              N0.getOperand(1),
5792                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5793
5794       // If the desired elements are smaller or larger than the source
5795       // elements we can use a matching integer vector type and then
5796       // truncate/sign extend
5797       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5798       if (SVT == MatchingVectorType) {
5799         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5800                                N0.getOperand(0), N0.getOperand(1),
5801                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5802         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5803       }
5804     }
5805
5806     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5807     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5808     SDLoc DL(N);
5809     SDValue NegOne =
5810       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), DL, VT);
5811     SDValue SCC =
5812       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
5813                        NegOne, DAG.getConstant(0, DL, VT),
5814                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5815     if (SCC.getNode()) return SCC;
5816
5817     if (!VT.isVector()) {
5818       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5819       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5820         SDLoc DL(N);
5821         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5822         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5823                                      N0.getOperand(0), N0.getOperand(1), CC);
5824         return DAG.getSelect(DL, VT, SetCC,
5825                              NegOne, DAG.getConstant(0, DL, VT));
5826       }
5827     }
5828   }
5829
5830   // fold (sext x) -> (zext x) if the sign bit is known zero.
5831   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5832       DAG.SignBitIsZero(N0))
5833     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5834
5835   return SDValue();
5836 }
5837
5838 // isTruncateOf - If N is a truncate of some other value, return true, record
5839 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5840 // This function computes KnownZero to avoid a duplicated call to
5841 // computeKnownBits in the caller.
5842 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5843                          APInt &KnownZero) {
5844   APInt KnownOne;
5845   if (N->getOpcode() == ISD::TRUNCATE) {
5846     Op = N->getOperand(0);
5847     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5848     return true;
5849   }
5850
5851   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5852       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5853     return false;
5854
5855   SDValue Op0 = N->getOperand(0);
5856   SDValue Op1 = N->getOperand(1);
5857   assert(Op0.getValueType() == Op1.getValueType());
5858
5859   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5860   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5861   if (COp0 && COp0->isNullValue())
5862     Op = Op1;
5863   else if (COp1 && COp1->isNullValue())
5864     Op = Op0;
5865   else
5866     return false;
5867
5868   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5869
5870   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5871     return false;
5872
5873   return true;
5874 }
5875
5876 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5877   SDValue N0 = N->getOperand(0);
5878   EVT VT = N->getValueType(0);
5879
5880   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5881                                               LegalOperations))
5882     return SDValue(Res, 0);
5883
5884   // fold (zext (zext x)) -> (zext x)
5885   // fold (zext (aext x)) -> (zext x)
5886   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5887     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5888                        N0.getOperand(0));
5889
5890   // fold (zext (truncate x)) -> (zext x) or
5891   //      (zext (truncate x)) -> (truncate x)
5892   // This is valid when the truncated bits of x are already zero.
5893   // FIXME: We should extend this to work for vectors too.
5894   SDValue Op;
5895   APInt KnownZero;
5896   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5897     APInt TruncatedBits =
5898       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5899       APInt(Op.getValueSizeInBits(), 0) :
5900       APInt::getBitsSet(Op.getValueSizeInBits(),
5901                         N0.getValueSizeInBits(),
5902                         std::min(Op.getValueSizeInBits(),
5903                                  VT.getSizeInBits()));
5904     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5905       if (VT.bitsGT(Op.getValueType()))
5906         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5907       if (VT.bitsLT(Op.getValueType()))
5908         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5909
5910       return Op;
5911     }
5912   }
5913
5914   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5915   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5916   if (N0.getOpcode() == ISD::TRUNCATE) {
5917     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5918     if (NarrowLoad.getNode()) {
5919       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5920       if (NarrowLoad.getNode() != N0.getNode()) {
5921         CombineTo(N0.getNode(), NarrowLoad);
5922         // CombineTo deleted the truncate, if needed, but not what's under it.
5923         AddToWorklist(oye);
5924       }
5925       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5926     }
5927   }
5928
5929   // fold (zext (truncate x)) -> (and x, mask)
5930   if (N0.getOpcode() == ISD::TRUNCATE &&
5931       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5932
5933     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5934     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5935     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5936     if (NarrowLoad.getNode()) {
5937       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5938       if (NarrowLoad.getNode() != N0.getNode()) {
5939         CombineTo(N0.getNode(), NarrowLoad);
5940         // CombineTo deleted the truncate, if needed, but not what's under it.
5941         AddToWorklist(oye);
5942       }
5943       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5944     }
5945
5946     SDValue Op = N0.getOperand(0);
5947     if (Op.getValueType().bitsLT(VT)) {
5948       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5949       AddToWorklist(Op.getNode());
5950     } else if (Op.getValueType().bitsGT(VT)) {
5951       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5952       AddToWorklist(Op.getNode());
5953     }
5954     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5955                                   N0.getValueType().getScalarType());
5956   }
5957
5958   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5959   // if either of the casts is not free.
5960   if (N0.getOpcode() == ISD::AND &&
5961       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5962       N0.getOperand(1).getOpcode() == ISD::Constant &&
5963       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5964                            N0.getValueType()) ||
5965        !TLI.isZExtFree(N0.getValueType(), VT))) {
5966     SDValue X = N0.getOperand(0).getOperand(0);
5967     if (X.getValueType().bitsLT(VT)) {
5968       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5969     } else if (X.getValueType().bitsGT(VT)) {
5970       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5971     }
5972     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5973     Mask = Mask.zext(VT.getSizeInBits());
5974     SDLoc DL(N);
5975     return DAG.getNode(ISD::AND, DL, VT,
5976                        X, DAG.getConstant(Mask, DL, VT));
5977   }
5978
5979   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5980   // Only generate vector extloads when 1) they're legal, and 2) they are
5981   // deemed desirable by the target.
5982   if (ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5983       ((!LegalOperations && !VT.isVector() &&
5984         !cast<LoadSDNode>(N0)->isVolatile()) ||
5985        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5986     bool DoXform = true;
5987     SmallVector<SDNode*, 4> SetCCs;
5988     if (!N0.hasOneUse())
5989       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5990     if (VT.isVector())
5991       DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
5992     if (DoXform) {
5993       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5994       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5995                                        LN0->getChain(),
5996                                        LN0->getBasePtr(), N0.getValueType(),
5997                                        LN0->getMemOperand());
5998       CombineTo(N, ExtLoad);
5999       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6000                                   N0.getValueType(), ExtLoad);
6001       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6002
6003       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6004                       ISD::ZERO_EXTEND);
6005       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6006     }
6007   }
6008
6009   // fold (zext (load x)) to multiple smaller zextloads.
6010   // Only on illegal but splittable vectors.
6011   if (SDValue ExtLoad = CombineExtLoad(N))
6012     return ExtLoad;
6013
6014   // fold (zext (and/or/xor (load x), cst)) ->
6015   //      (and/or/xor (zextload x), (zext cst))
6016   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
6017        N0.getOpcode() == ISD::XOR) &&
6018       isa<LoadSDNode>(N0.getOperand(0)) &&
6019       N0.getOperand(1).getOpcode() == ISD::Constant &&
6020       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
6021       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
6022     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
6023     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
6024       bool DoXform = true;
6025       SmallVector<SDNode*, 4> SetCCs;
6026       if (!N0.hasOneUse())
6027         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
6028                                           SetCCs, TLI);
6029       if (DoXform) {
6030         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
6031                                          LN0->getChain(), LN0->getBasePtr(),
6032                                          LN0->getMemoryVT(),
6033                                          LN0->getMemOperand());
6034         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6035         Mask = Mask.zext(VT.getSizeInBits());
6036         SDLoc DL(N);
6037         SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
6038                                   ExtLoad, DAG.getConstant(Mask, DL, VT));
6039         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
6040                                     SDLoc(N0.getOperand(0)),
6041                                     N0.getOperand(0).getValueType(), ExtLoad);
6042         CombineTo(N, And);
6043         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
6044         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, DL,
6045                         ISD::ZERO_EXTEND);
6046         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6047       }
6048     }
6049   }
6050
6051   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
6052   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
6053   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
6054       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
6055     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6056     EVT MemVT = LN0->getMemoryVT();
6057     if ((!LegalOperations && !LN0->isVolatile()) ||
6058         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
6059       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
6060                                        LN0->getChain(),
6061                                        LN0->getBasePtr(), MemVT,
6062                                        LN0->getMemOperand());
6063       CombineTo(N, ExtLoad);
6064       CombineTo(N0.getNode(),
6065                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
6066                             ExtLoad),
6067                 ExtLoad.getValue(1));
6068       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6069     }
6070   }
6071
6072   if (N0.getOpcode() == ISD::SETCC) {
6073     if (!LegalOperations && VT.isVector() &&
6074         N0.getValueType().getVectorElementType() == MVT::i1) {
6075       EVT N0VT = N0.getOperand(0).getValueType();
6076       if (getSetCCResultType(N0VT) == N0.getValueType())
6077         return SDValue();
6078
6079       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
6080       // Only do this before legalize for now.
6081       EVT EltVT = VT.getVectorElementType();
6082       SDLoc DL(N);
6083       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
6084                                     DAG.getConstant(1, DL, EltVT));
6085       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6086         // We know that the # elements of the results is the same as the
6087         // # elements of the compare (and the # elements of the compare result
6088         // for that matter).  Check to see that they are the same size.  If so,
6089         // we know that the element size of the sext'd result matches the
6090         // element size of the compare operands.
6091         return DAG.getNode(ISD::AND, DL, VT,
6092                            DAG.getSetCC(DL, VT, N0.getOperand(0),
6093                                          N0.getOperand(1),
6094                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
6095                            DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
6096                                        OneOps));
6097
6098       // If the desired elements are smaller or larger than the source
6099       // elements we can use a matching integer vector type and then
6100       // truncate/sign extend
6101       EVT MatchingElementType =
6102         EVT::getIntegerVT(*DAG.getContext(),
6103                           N0VT.getScalarType().getSizeInBits());
6104       EVT MatchingVectorType =
6105         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
6106                          N0VT.getVectorNumElements());
6107       SDValue VsetCC =
6108         DAG.getSetCC(DL, MatchingVectorType, N0.getOperand(0),
6109                       N0.getOperand(1),
6110                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
6111       return DAG.getNode(ISD::AND, DL, VT,
6112                          DAG.getSExtOrTrunc(VsetCC, DL, VT),
6113                          DAG.getNode(ISD::BUILD_VECTOR, DL, VT, OneOps));
6114     }
6115
6116     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6117     SDLoc DL(N);
6118     SDValue SCC =
6119       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6120                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6121                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6122     if (SCC.getNode()) return SCC;
6123   }
6124
6125   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
6126   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
6127       isa<ConstantSDNode>(N0.getOperand(1)) &&
6128       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
6129       N0.hasOneUse()) {
6130     SDValue ShAmt = N0.getOperand(1);
6131     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
6132     if (N0.getOpcode() == ISD::SHL) {
6133       SDValue InnerZExt = N0.getOperand(0);
6134       // If the original shl may be shifting out bits, do not perform this
6135       // transformation.
6136       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
6137         InnerZExt.getOperand(0).getValueType().getSizeInBits();
6138       if (ShAmtVal > KnownZeroBits)
6139         return SDValue();
6140     }
6141
6142     SDLoc DL(N);
6143
6144     // Ensure that the shift amount is wide enough for the shifted value.
6145     if (VT.getSizeInBits() >= 256)
6146       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
6147
6148     return DAG.getNode(N0.getOpcode(), DL, VT,
6149                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
6150                        ShAmt);
6151   }
6152
6153   return SDValue();
6154 }
6155
6156 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
6157   SDValue N0 = N->getOperand(0);
6158   EVT VT = N->getValueType(0);
6159
6160   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
6161                                               LegalOperations))
6162     return SDValue(Res, 0);
6163
6164   // fold (aext (aext x)) -> (aext x)
6165   // fold (aext (zext x)) -> (zext x)
6166   // fold (aext (sext x)) -> (sext x)
6167   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
6168       N0.getOpcode() == ISD::ZERO_EXTEND ||
6169       N0.getOpcode() == ISD::SIGN_EXTEND)
6170     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
6171
6172   // fold (aext (truncate (load x))) -> (aext (smaller load x))
6173   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
6174   if (N0.getOpcode() == ISD::TRUNCATE) {
6175     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
6176     if (NarrowLoad.getNode()) {
6177       SDNode* oye = N0.getNode()->getOperand(0).getNode();
6178       if (NarrowLoad.getNode() != N0.getNode()) {
6179         CombineTo(N0.getNode(), NarrowLoad);
6180         // CombineTo deleted the truncate, if needed, but not what's under it.
6181         AddToWorklist(oye);
6182       }
6183       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6184     }
6185   }
6186
6187   // fold (aext (truncate x))
6188   if (N0.getOpcode() == ISD::TRUNCATE) {
6189     SDValue TruncOp = N0.getOperand(0);
6190     if (TruncOp.getValueType() == VT)
6191       return TruncOp; // x iff x size == zext size.
6192     if (TruncOp.getValueType().bitsGT(VT))
6193       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
6194     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
6195   }
6196
6197   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
6198   // if the trunc is not free.
6199   if (N0.getOpcode() == ISD::AND &&
6200       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
6201       N0.getOperand(1).getOpcode() == ISD::Constant &&
6202       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
6203                           N0.getValueType())) {
6204     SDValue X = N0.getOperand(0).getOperand(0);
6205     if (X.getValueType().bitsLT(VT)) {
6206       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
6207     } else if (X.getValueType().bitsGT(VT)) {
6208       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
6209     }
6210     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
6211     Mask = Mask.zext(VT.getSizeInBits());
6212     SDLoc DL(N);
6213     return DAG.getNode(ISD::AND, DL, VT,
6214                        X, DAG.getConstant(Mask, DL, VT));
6215   }
6216
6217   // fold (aext (load x)) -> (aext (truncate (extload x)))
6218   // None of the supported targets knows how to perform load and any_ext
6219   // on vectors in one instruction.  We only perform this transformation on
6220   // scalars.
6221   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
6222       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6223       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
6224     bool DoXform = true;
6225     SmallVector<SDNode*, 4> SetCCs;
6226     if (!N0.hasOneUse())
6227       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
6228     if (DoXform) {
6229       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6230       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6231                                        LN0->getChain(),
6232                                        LN0->getBasePtr(), N0.getValueType(),
6233                                        LN0->getMemOperand());
6234       CombineTo(N, ExtLoad);
6235       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6236                                   N0.getValueType(), ExtLoad);
6237       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
6238       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
6239                       ISD::ANY_EXTEND);
6240       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6241     }
6242   }
6243
6244   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
6245   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
6246   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
6247   if (N0.getOpcode() == ISD::LOAD &&
6248       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6249       N0.hasOneUse()) {
6250     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6251     ISD::LoadExtType ExtType = LN0->getExtensionType();
6252     EVT MemVT = LN0->getMemoryVT();
6253     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
6254       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
6255                                        VT, LN0->getChain(), LN0->getBasePtr(),
6256                                        MemVT, LN0->getMemOperand());
6257       CombineTo(N, ExtLoad);
6258       CombineTo(N0.getNode(),
6259                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
6260                             N0.getValueType(), ExtLoad),
6261                 ExtLoad.getValue(1));
6262       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6263     }
6264   }
6265
6266   if (N0.getOpcode() == ISD::SETCC) {
6267     // For vectors:
6268     // aext(setcc) -> vsetcc
6269     // aext(setcc) -> truncate(vsetcc)
6270     // aext(setcc) -> aext(vsetcc)
6271     // Only do this before legalize for now.
6272     if (VT.isVector() && !LegalOperations) {
6273       EVT N0VT = N0.getOperand(0).getValueType();
6274         // We know that the # elements of the results is the same as the
6275         // # elements of the compare (and the # elements of the compare result
6276         // for that matter).  Check to see that they are the same size.  If so,
6277         // we know that the element size of the sext'd result matches the
6278         // element size of the compare operands.
6279       if (VT.getSizeInBits() == N0VT.getSizeInBits())
6280         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
6281                              N0.getOperand(1),
6282                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
6283       // If the desired elements are smaller or larger than the source
6284       // elements we can use a matching integer vector type and then
6285       // truncate/any extend
6286       else {
6287         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
6288         SDValue VsetCC =
6289           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
6290                         N0.getOperand(1),
6291                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
6292         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
6293       }
6294     }
6295
6296     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
6297     SDLoc DL(N);
6298     SDValue SCC =
6299       SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1),
6300                        DAG.getConstant(1, DL, VT), DAG.getConstant(0, DL, VT),
6301                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
6302     if (SCC.getNode())
6303       return SCC;
6304   }
6305
6306   return SDValue();
6307 }
6308
6309 /// See if the specified operand can be simplified with the knowledge that only
6310 /// the bits specified by Mask are used.  If so, return the simpler operand,
6311 /// otherwise return a null SDValue.
6312 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
6313   switch (V.getOpcode()) {
6314   default: break;
6315   case ISD::Constant: {
6316     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
6317     assert(CV && "Const value should be ConstSDNode.");
6318     const APInt &CVal = CV->getAPIntValue();
6319     APInt NewVal = CVal & Mask;
6320     if (NewVal != CVal)
6321       return DAG.getConstant(NewVal, SDLoc(V), V.getValueType());
6322     break;
6323   }
6324   case ISD::OR:
6325   case ISD::XOR:
6326     // If the LHS or RHS don't contribute bits to the or, drop them.
6327     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
6328       return V.getOperand(1);
6329     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
6330       return V.getOperand(0);
6331     break;
6332   case ISD::SRL:
6333     // Only look at single-use SRLs.
6334     if (!V.getNode()->hasOneUse())
6335       break;
6336     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
6337       // See if we can recursively simplify the LHS.
6338       unsigned Amt = RHSC->getZExtValue();
6339
6340       // Watch out for shift count overflow though.
6341       if (Amt >= Mask.getBitWidth()) break;
6342       APInt NewMask = Mask << Amt;
6343       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
6344       if (SimplifyLHS.getNode())
6345         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
6346                            SimplifyLHS, V.getOperand(1));
6347     }
6348   }
6349   return SDValue();
6350 }
6351
6352 /// If the result of a wider load is shifted to right of N  bits and then
6353 /// truncated to a narrower type and where N is a multiple of number of bits of
6354 /// the narrower type, transform it to a narrower load from address + N / num of
6355 /// bits of new type. If the result is to be extended, also fold the extension
6356 /// to form a extending load.
6357 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
6358   unsigned Opc = N->getOpcode();
6359
6360   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6361   SDValue N0 = N->getOperand(0);
6362   EVT VT = N->getValueType(0);
6363   EVT ExtVT = VT;
6364
6365   // This transformation isn't valid for vector loads.
6366   if (VT.isVector())
6367     return SDValue();
6368
6369   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6370   // extended to VT.
6371   if (Opc == ISD::SIGN_EXTEND_INREG) {
6372     ExtType = ISD::SEXTLOAD;
6373     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6374   } else if (Opc == ISD::SRL) {
6375     // Another special-case: SRL is basically zero-extending a narrower value.
6376     ExtType = ISD::ZEXTLOAD;
6377     N0 = SDValue(N, 0);
6378     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6379     if (!N01) return SDValue();
6380     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6381                               VT.getSizeInBits() - N01->getZExtValue());
6382   }
6383   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6384     return SDValue();
6385
6386   unsigned EVTBits = ExtVT.getSizeInBits();
6387
6388   // Do not generate loads of non-round integer types since these can
6389   // be expensive (and would be wrong if the type is not byte sized).
6390   if (!ExtVT.isRound())
6391     return SDValue();
6392
6393   unsigned ShAmt = 0;
6394   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6395     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6396       ShAmt = N01->getZExtValue();
6397       // Is the shift amount a multiple of size of VT?
6398       if ((ShAmt & (EVTBits-1)) == 0) {
6399         N0 = N0.getOperand(0);
6400         // Is the load width a multiple of size of VT?
6401         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6402           return SDValue();
6403       }
6404
6405       // At this point, we must have a load or else we can't do the transform.
6406       if (!isa<LoadSDNode>(N0)) return SDValue();
6407
6408       // Because a SRL must be assumed to *need* to zero-extend the high bits
6409       // (as opposed to anyext the high bits), we can't combine the zextload
6410       // lowering of SRL and an sextload.
6411       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6412         return SDValue();
6413
6414       // If the shift amount is larger than the input type then we're not
6415       // accessing any of the loaded bytes.  If the load was a zextload/extload
6416       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6417       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6418         return SDValue();
6419     }
6420   }
6421
6422   // If the load is shifted left (and the result isn't shifted back right),
6423   // we can fold the truncate through the shift.
6424   unsigned ShLeftAmt = 0;
6425   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6426       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6427     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6428       ShLeftAmt = N01->getZExtValue();
6429       N0 = N0.getOperand(0);
6430     }
6431   }
6432
6433   // If we haven't found a load, we can't narrow it.  Don't transform one with
6434   // multiple uses, this would require adding a new load.
6435   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6436     return SDValue();
6437
6438   // Don't change the width of a volatile load.
6439   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6440   if (LN0->isVolatile())
6441     return SDValue();
6442
6443   // Verify that we are actually reducing a load width here.
6444   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6445     return SDValue();
6446
6447   // For the transform to be legal, the load must produce only two values
6448   // (the value loaded and the chain).  Don't transform a pre-increment
6449   // load, for example, which produces an extra value.  Otherwise the
6450   // transformation is not equivalent, and the downstream logic to replace
6451   // uses gets things wrong.
6452   if (LN0->getNumValues() > 2)
6453     return SDValue();
6454
6455   // If the load that we're shrinking is an extload and we're not just
6456   // discarding the extension we can't simply shrink the load. Bail.
6457   // TODO: It would be possible to merge the extensions in some cases.
6458   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6459       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6460     return SDValue();
6461
6462   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6463     return SDValue();
6464
6465   EVT PtrType = N0.getOperand(1).getValueType();
6466
6467   if (PtrType == MVT::Untyped || PtrType.isExtended())
6468     // It's not possible to generate a constant of extended or untyped type.
6469     return SDValue();
6470
6471   // For big endian targets, we need to adjust the offset to the pointer to
6472   // load the correct bytes.
6473   if (TLI.isBigEndian()) {
6474     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6475     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6476     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6477   }
6478
6479   uint64_t PtrOff = ShAmt / 8;
6480   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6481   SDLoc DL(LN0);
6482   SDValue NewPtr = DAG.getNode(ISD::ADD, DL,
6483                                PtrType, LN0->getBasePtr(),
6484                                DAG.getConstant(PtrOff, DL, PtrType));
6485   AddToWorklist(NewPtr.getNode());
6486
6487   SDValue Load;
6488   if (ExtType == ISD::NON_EXTLOAD)
6489     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6490                         LN0->getPointerInfo().getWithOffset(PtrOff),
6491                         LN0->isVolatile(), LN0->isNonTemporal(),
6492                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6493   else
6494     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6495                           LN0->getPointerInfo().getWithOffset(PtrOff),
6496                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6497                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6498
6499   // Replace the old load's chain with the new load's chain.
6500   WorklistRemover DeadNodes(*this);
6501   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6502
6503   // Shift the result left, if we've swallowed a left shift.
6504   SDValue Result = Load;
6505   if (ShLeftAmt != 0) {
6506     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6507     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6508       ShImmTy = VT;
6509     // If the shift amount is as large as the result size (but, presumably,
6510     // no larger than the source) then the useful bits of the result are
6511     // zero; we can't simply return the shortened shift, because the result
6512     // of that operation is undefined.
6513     SDLoc DL(N0);
6514     if (ShLeftAmt >= VT.getSizeInBits())
6515       Result = DAG.getConstant(0, DL, VT);
6516     else
6517       Result = DAG.getNode(ISD::SHL, DL, VT,
6518                           Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
6519   }
6520
6521   // Return the new loaded value.
6522   return Result;
6523 }
6524
6525 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6526   SDValue N0 = N->getOperand(0);
6527   SDValue N1 = N->getOperand(1);
6528   EVT VT = N->getValueType(0);
6529   EVT EVT = cast<VTSDNode>(N1)->getVT();
6530   unsigned VTBits = VT.getScalarType().getSizeInBits();
6531   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6532
6533   // fold (sext_in_reg c1) -> c1
6534   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6535     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6536
6537   // If the input is already sign extended, just drop the extension.
6538   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6539     return N0;
6540
6541   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6542   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6543       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6544     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6545                        N0.getOperand(0), N1);
6546
6547   // fold (sext_in_reg (sext x)) -> (sext x)
6548   // fold (sext_in_reg (aext x)) -> (sext x)
6549   // if x is small enough.
6550   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6551     SDValue N00 = N0.getOperand(0);
6552     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6553         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6554       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6555   }
6556
6557   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6558   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6559     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6560
6561   // fold operands of sext_in_reg based on knowledge that the top bits are not
6562   // demanded.
6563   if (SimplifyDemandedBits(SDValue(N, 0)))
6564     return SDValue(N, 0);
6565
6566   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6567   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6568   SDValue NarrowLoad = ReduceLoadWidth(N);
6569   if (NarrowLoad.getNode())
6570     return NarrowLoad;
6571
6572   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6573   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6574   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6575   if (N0.getOpcode() == ISD::SRL) {
6576     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6577       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6578         // We can turn this into an SRA iff the input to the SRL is already sign
6579         // extended enough.
6580         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6581         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6582           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6583                              N0.getOperand(0), N0.getOperand(1));
6584       }
6585   }
6586
6587   // fold (sext_inreg (extload x)) -> (sextload x)
6588   if (ISD::isEXTLoad(N0.getNode()) &&
6589       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6590       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6591       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6592        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6593     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6594     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6595                                      LN0->getChain(),
6596                                      LN0->getBasePtr(), EVT,
6597                                      LN0->getMemOperand());
6598     CombineTo(N, ExtLoad);
6599     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6600     AddToWorklist(ExtLoad.getNode());
6601     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6602   }
6603   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6604   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6605       N0.hasOneUse() &&
6606       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6607       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6608        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6609     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6610     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6611                                      LN0->getChain(),
6612                                      LN0->getBasePtr(), EVT,
6613                                      LN0->getMemOperand());
6614     CombineTo(N, ExtLoad);
6615     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6616     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6617   }
6618
6619   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6620   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6621     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6622                                        N0.getOperand(1), false);
6623     if (BSwap.getNode())
6624       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6625                          BSwap, N1);
6626   }
6627
6628   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6629   // into a build_vector.
6630   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6631     SmallVector<SDValue, 8> Elts;
6632     unsigned NumElts = N0->getNumOperands();
6633     unsigned ShAmt = VTBits - EVTBits;
6634
6635     for (unsigned i = 0; i != NumElts; ++i) {
6636       SDValue Op = N0->getOperand(i);
6637       if (Op->getOpcode() == ISD::UNDEF) {
6638         Elts.push_back(Op);
6639         continue;
6640       }
6641
6642       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6643       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6644       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6645                                      SDLoc(Op), Op.getValueType()));
6646     }
6647
6648     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6649   }
6650
6651   return SDValue();
6652 }
6653
6654 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6655   SDValue N0 = N->getOperand(0);
6656   EVT VT = N->getValueType(0);
6657   bool isLE = TLI.isLittleEndian();
6658
6659   // noop truncate
6660   if (N0.getValueType() == N->getValueType(0))
6661     return N0;
6662   // fold (truncate c1) -> c1
6663   if (isConstantIntBuildVectorOrConstantInt(N0))
6664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6665   // fold (truncate (truncate x)) -> (truncate x)
6666   if (N0.getOpcode() == ISD::TRUNCATE)
6667     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6668   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6669   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6670       N0.getOpcode() == ISD::SIGN_EXTEND ||
6671       N0.getOpcode() == ISD::ANY_EXTEND) {
6672     if (N0.getOperand(0).getValueType().bitsLT(VT))
6673       // if the source is smaller than the dest, we still need an extend
6674       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6675                          N0.getOperand(0));
6676     if (N0.getOperand(0).getValueType().bitsGT(VT))
6677       // if the source is larger than the dest, than we just need the truncate
6678       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6679     // if the source and dest are the same type, we can drop both the extend
6680     // and the truncate.
6681     return N0.getOperand(0);
6682   }
6683
6684   // Fold extract-and-trunc into a narrow extract. For example:
6685   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6686   //   i32 y = TRUNCATE(i64 x)
6687   //        -- becomes --
6688   //   v16i8 b = BITCAST (v2i64 val)
6689   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6690   //
6691   // Note: We only run this optimization after type legalization (which often
6692   // creates this pattern) and before operation legalization after which
6693   // we need to be more careful about the vector instructions that we generate.
6694   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6695       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6696
6697     EVT VecTy = N0.getOperand(0).getValueType();
6698     EVT ExTy = N0.getValueType();
6699     EVT TrTy = N->getValueType(0);
6700
6701     unsigned NumElem = VecTy.getVectorNumElements();
6702     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6703
6704     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6705     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6706
6707     SDValue EltNo = N0->getOperand(1);
6708     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6709       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6710       EVT IndexTy = TLI.getVectorIdxTy();
6711       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6712
6713       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6714                               NVT, N0.getOperand(0));
6715
6716       SDLoc DL(N);
6717       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6718                          DL, TrTy, V,
6719                          DAG.getConstant(Index, DL, IndexTy));
6720     }
6721   }
6722
6723   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6724   if (N0.getOpcode() == ISD::SELECT) {
6725     EVT SrcVT = N0.getValueType();
6726     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6727         TLI.isTruncateFree(SrcVT, VT)) {
6728       SDLoc SL(N0);
6729       SDValue Cond = N0.getOperand(0);
6730       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6731       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6732       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6733     }
6734   }
6735
6736   // Fold a series of buildvector, bitcast, and truncate if possible.
6737   // For example fold
6738   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6739   //   (2xi32 (buildvector x, y)).
6740   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6741       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6742       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6743       N0.getOperand(0).hasOneUse()) {
6744
6745     SDValue BuildVect = N0.getOperand(0);
6746     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6747     EVT TruncVecEltTy = VT.getVectorElementType();
6748
6749     // Check that the element types match.
6750     if (BuildVectEltTy == TruncVecEltTy) {
6751       // Now we only need to compute the offset of the truncated elements.
6752       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6753       unsigned TruncVecNumElts = VT.getVectorNumElements();
6754       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6755
6756       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6757              "Invalid number of elements");
6758
6759       SmallVector<SDValue, 8> Opnds;
6760       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6761         Opnds.push_back(BuildVect.getOperand(i));
6762
6763       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6764     }
6765   }
6766
6767   // See if we can simplify the input to this truncate through knowledge that
6768   // only the low bits are being used.
6769   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6770   // Currently we only perform this optimization on scalars because vectors
6771   // may have different active low bits.
6772   if (!VT.isVector()) {
6773     SDValue Shorter =
6774       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6775                                                VT.getSizeInBits()));
6776     if (Shorter.getNode())
6777       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6778   }
6779   // fold (truncate (load x)) -> (smaller load x)
6780   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6781   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6782     SDValue Reduced = ReduceLoadWidth(N);
6783     if (Reduced.getNode())
6784       return Reduced;
6785     // Handle the case where the load remains an extending load even
6786     // after truncation.
6787     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6788       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6789       if (!LN0->isVolatile() &&
6790           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6791         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6792                                          VT, LN0->getChain(), LN0->getBasePtr(),
6793                                          LN0->getMemoryVT(),
6794                                          LN0->getMemOperand());
6795         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6796         return NewLoad;
6797       }
6798     }
6799   }
6800   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6801   // where ... are all 'undef'.
6802   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6803     SmallVector<EVT, 8> VTs;
6804     SDValue V;
6805     unsigned Idx = 0;
6806     unsigned NumDefs = 0;
6807
6808     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6809       SDValue X = N0.getOperand(i);
6810       if (X.getOpcode() != ISD::UNDEF) {
6811         V = X;
6812         Idx = i;
6813         NumDefs++;
6814       }
6815       // Stop if more than one members are non-undef.
6816       if (NumDefs > 1)
6817         break;
6818       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6819                                      VT.getVectorElementType(),
6820                                      X.getValueType().getVectorNumElements()));
6821     }
6822
6823     if (NumDefs == 0)
6824       return DAG.getUNDEF(VT);
6825
6826     if (NumDefs == 1) {
6827       assert(V.getNode() && "The single defined operand is empty!");
6828       SmallVector<SDValue, 8> Opnds;
6829       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6830         if (i != Idx) {
6831           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6832           continue;
6833         }
6834         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6835         AddToWorklist(NV.getNode());
6836         Opnds.push_back(NV);
6837       }
6838       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6839     }
6840   }
6841
6842   // Simplify the operands using demanded-bits information.
6843   if (!VT.isVector() &&
6844       SimplifyDemandedBits(SDValue(N, 0)))
6845     return SDValue(N, 0);
6846
6847   return SDValue();
6848 }
6849
6850 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6851   SDValue Elt = N->getOperand(i);
6852   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6853     return Elt.getNode();
6854   return Elt.getOperand(Elt.getResNo()).getNode();
6855 }
6856
6857 /// build_pair (load, load) -> load
6858 /// if load locations are consecutive.
6859 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6860   assert(N->getOpcode() == ISD::BUILD_PAIR);
6861
6862   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6863   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6864   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6865       LD1->getAddressSpace() != LD2->getAddressSpace())
6866     return SDValue();
6867   EVT LD1VT = LD1->getValueType(0);
6868
6869   if (ISD::isNON_EXTLoad(LD2) &&
6870       LD2->hasOneUse() &&
6871       // If both are volatile this would reduce the number of volatile loads.
6872       // If one is volatile it might be ok, but play conservative and bail out.
6873       !LD1->isVolatile() &&
6874       !LD2->isVolatile() &&
6875       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6876     unsigned Align = LD1->getAlignment();
6877     unsigned NewAlign = TLI.getDataLayout()->
6878       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6879
6880     if (NewAlign <= Align &&
6881         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6882       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6883                          LD1->getBasePtr(), LD1->getPointerInfo(),
6884                          false, false, false, Align);
6885   }
6886
6887   return SDValue();
6888 }
6889
6890 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6891   SDValue N0 = N->getOperand(0);
6892   EVT VT = N->getValueType(0);
6893
6894   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6895   // Only do this before legalize, since afterward the target may be depending
6896   // on the bitconvert.
6897   // First check to see if this is all constant.
6898   if (!LegalTypes &&
6899       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6900       VT.isVector()) {
6901     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6902
6903     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6904     assert(!DestEltVT.isVector() &&
6905            "Element type of vector ValueType must not be vector!");
6906     if (isSimple)
6907       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6908   }
6909
6910   // If the input is a constant, let getNode fold it.
6911   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6912     // If we can't allow illegal operations, we need to check that this is just
6913     // a fp -> int or int -> conversion and that the resulting operation will
6914     // be legal.
6915     if (!LegalOperations ||
6916         (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
6917          TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
6918         (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
6919          TLI.isOperationLegal(ISD::Constant, VT)))
6920       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6921   }
6922
6923   // (conv (conv x, t1), t2) -> (conv x, t2)
6924   if (N0.getOpcode() == ISD::BITCAST)
6925     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6926                        N0.getOperand(0));
6927
6928   // fold (conv (load x)) -> (load (conv*)x)
6929   // If the resultant load doesn't need a higher alignment than the original!
6930   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6931       // Do not change the width of a volatile load.
6932       !cast<LoadSDNode>(N0)->isVolatile() &&
6933       // Do not remove the cast if the types differ in endian layout.
6934       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6935       TLI.hasBigEndianPartOrdering(VT) &&
6936       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6937       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6938     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6939     unsigned Align = TLI.getDataLayout()->
6940       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6941     unsigned OrigAlign = LN0->getAlignment();
6942
6943     if (Align <= OrigAlign) {
6944       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6945                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6946                                  LN0->isVolatile(), LN0->isNonTemporal(),
6947                                  LN0->isInvariant(), OrigAlign,
6948                                  LN0->getAAInfo());
6949       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6950       return Load;
6951     }
6952   }
6953
6954   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6955   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6956   // This often reduces constant pool loads.
6957   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6958        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6959       N0.getNode()->hasOneUse() && VT.isInteger() &&
6960       !VT.isVector() && !N0.getValueType().isVector()) {
6961     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6962                                   N0.getOperand(0));
6963     AddToWorklist(NewConv.getNode());
6964
6965     SDLoc DL(N);
6966     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6967     if (N0.getOpcode() == ISD::FNEG)
6968       return DAG.getNode(ISD::XOR, DL, VT,
6969                          NewConv, DAG.getConstant(SignBit, DL, VT));
6970     assert(N0.getOpcode() == ISD::FABS);
6971     return DAG.getNode(ISD::AND, DL, VT,
6972                        NewConv, DAG.getConstant(~SignBit, DL, VT));
6973   }
6974
6975   // fold (bitconvert (fcopysign cst, x)) ->
6976   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6977   // Note that we don't handle (copysign x, cst) because this can always be
6978   // folded to an fneg or fabs.
6979   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6980       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6981       VT.isInteger() && !VT.isVector()) {
6982     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6983     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6984     if (isTypeLegal(IntXVT)) {
6985       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6986                               IntXVT, N0.getOperand(1));
6987       AddToWorklist(X.getNode());
6988
6989       // If X has a different width than the result/lhs, sext it or truncate it.
6990       unsigned VTWidth = VT.getSizeInBits();
6991       if (OrigXWidth < VTWidth) {
6992         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6993         AddToWorklist(X.getNode());
6994       } else if (OrigXWidth > VTWidth) {
6995         // To get the sign bit in the right place, we have to shift it right
6996         // before truncating.
6997         SDLoc DL(X);
6998         X = DAG.getNode(ISD::SRL, DL,
6999                         X.getValueType(), X,
7000                         DAG.getConstant(OrigXWidth-VTWidth, DL,
7001                                         X.getValueType()));
7002         AddToWorklist(X.getNode());
7003         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
7004         AddToWorklist(X.getNode());
7005       }
7006
7007       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
7008       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
7009                       X, DAG.getConstant(SignBit, SDLoc(X), VT));
7010       AddToWorklist(X.getNode());
7011
7012       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
7013                                 VT, N0.getOperand(0));
7014       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
7015                         Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
7016       AddToWorklist(Cst.getNode());
7017
7018       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
7019     }
7020   }
7021
7022   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
7023   if (N0.getOpcode() == ISD::BUILD_PAIR) {
7024     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
7025     if (CombineLD.getNode())
7026       return CombineLD;
7027   }
7028
7029   // Remove double bitcasts from shuffles - this is often a legacy of
7030   // XformToShuffleWithZero being used to combine bitmaskings (of
7031   // float vectors bitcast to integer vectors) into shuffles.
7032   // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
7033   if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
7034       N0->getOpcode() == ISD::VECTOR_SHUFFLE &&
7035       VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
7036       !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
7037     ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
7038
7039     // If operands are a bitcast, peek through if it casts the original VT.
7040     // If operands are a UNDEF or constant, just bitcast back to original VT.
7041     auto PeekThroughBitcast = [&](SDValue Op) {
7042       if (Op.getOpcode() == ISD::BITCAST &&
7043           Op.getOperand(0)->getValueType(0) == VT)
7044         return SDValue(Op.getOperand(0));
7045       if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
7046           ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
7047         return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
7048       return SDValue();
7049     };
7050
7051     SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
7052     SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
7053     if (!(SV0 && SV1))
7054       return SDValue();
7055
7056     int MaskScale =
7057         VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
7058     SmallVector<int, 8> NewMask;
7059     for (int M : SVN->getMask())
7060       for (int i = 0; i != MaskScale; ++i)
7061         NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
7062
7063     bool LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7064     if (!LegalMask) {
7065       std::swap(SV0, SV1);
7066       ShuffleVectorSDNode::commuteMask(NewMask);
7067       LegalMask = TLI.isShuffleMaskLegal(NewMask, VT);
7068     }
7069
7070     if (LegalMask)
7071       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask);
7072   }
7073
7074   return SDValue();
7075 }
7076
7077 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
7078   EVT VT = N->getValueType(0);
7079   return CombineConsecutiveLoads(N, VT);
7080 }
7081
7082 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
7083 /// operands. DstEltVT indicates the destination element value type.
7084 SDValue DAGCombiner::
7085 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
7086   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
7087
7088   // If this is already the right type, we're done.
7089   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
7090
7091   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
7092   unsigned DstBitSize = DstEltVT.getSizeInBits();
7093
7094   // If this is a conversion of N elements of one type to N elements of another
7095   // type, convert each element.  This handles FP<->INT cases.
7096   if (SrcBitSize == DstBitSize) {
7097     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7098                               BV->getValueType(0).getVectorNumElements());
7099
7100     // Due to the FP element handling below calling this routine recursively,
7101     // we can end up with a scalar-to-vector node here.
7102     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
7103       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
7104                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
7105                                      DstEltVT, BV->getOperand(0)));
7106
7107     SmallVector<SDValue, 8> Ops;
7108     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7109       SDValue Op = BV->getOperand(i);
7110       // If the vector element type is not legal, the BUILD_VECTOR operands
7111       // are promoted and implicitly truncated.  Make that explicit here.
7112       if (Op.getValueType() != SrcEltVT)
7113         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
7114       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
7115                                 DstEltVT, Op));
7116       AddToWorklist(Ops.back().getNode());
7117     }
7118     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
7119   }
7120
7121   // Otherwise, we're growing or shrinking the elements.  To avoid having to
7122   // handle annoying details of growing/shrinking FP values, we convert them to
7123   // int first.
7124   if (SrcEltVT.isFloatingPoint()) {
7125     // Convert the input float vector to a int vector where the elements are the
7126     // same sizes.
7127     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
7128     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
7129     SrcEltVT = IntVT;
7130   }
7131
7132   // Now we know the input is an integer vector.  If the output is a FP type,
7133   // convert to integer first, then to FP of the right size.
7134   if (DstEltVT.isFloatingPoint()) {
7135     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
7136     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
7137
7138     // Next, convert to FP elements of the same size.
7139     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
7140   }
7141
7142   SDLoc DL(BV);
7143
7144   // Okay, we know the src/dst types are both integers of differing types.
7145   // Handling growing first.
7146   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
7147   if (SrcBitSize < DstBitSize) {
7148     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
7149
7150     SmallVector<SDValue, 8> Ops;
7151     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
7152          i += NumInputsPerOutput) {
7153       bool isLE = TLI.isLittleEndian();
7154       APInt NewBits = APInt(DstBitSize, 0);
7155       bool EltIsUndef = true;
7156       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
7157         // Shift the previously computed bits over.
7158         NewBits <<= SrcBitSize;
7159         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
7160         if (Op.getOpcode() == ISD::UNDEF) continue;
7161         EltIsUndef = false;
7162
7163         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
7164                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
7165       }
7166
7167       if (EltIsUndef)
7168         Ops.push_back(DAG.getUNDEF(DstEltVT));
7169       else
7170         Ops.push_back(DAG.getConstant(NewBits, DL, DstEltVT));
7171     }
7172
7173     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
7174     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7175   }
7176
7177   // Finally, this must be the case where we are shrinking elements: each input
7178   // turns into multiple outputs.
7179   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
7180   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
7181                             NumOutputsPerInput*BV->getNumOperands());
7182   SmallVector<SDValue, 8> Ops;
7183
7184   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
7185     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
7186       Ops.append(NumOutputsPerInput, DAG.getUNDEF(DstEltVT));
7187       continue;
7188     }
7189
7190     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
7191                   getAPIntValue().zextOrTrunc(SrcBitSize);
7192
7193     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
7194       APInt ThisVal = OpVal.trunc(DstBitSize);
7195       Ops.push_back(DAG.getConstant(ThisVal, DL, DstEltVT));
7196       OpVal = OpVal.lshr(DstBitSize);
7197     }
7198
7199     // For big endian targets, swap the order of the pieces of each element.
7200     if (TLI.isBigEndian())
7201       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
7202   }
7203
7204   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Ops);
7205 }
7206
7207 /// Try to perform FMA combining on a given FADD node.
7208 SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
7209   SDValue N0 = N->getOperand(0);
7210   SDValue N1 = N->getOperand(1);
7211   EVT VT = N->getValueType(0);
7212   SDLoc SL(N);
7213
7214   const TargetOptions &Options = DAG.getTarget().Options;
7215   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7216                        Options.UnsafeFPMath);
7217
7218   // Floating-point multiply-add with intermediate rounding.
7219   bool HasFMAD = (LegalOperations &&
7220                   TLI.isOperationLegal(ISD::FMAD, VT));
7221
7222   // Floating-point multiply-add without intermediate rounding.
7223   bool HasFMA = ((!LegalOperations ||
7224                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7225                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7226                  UnsafeFPMath);
7227
7228   // No valid opcode, do not combine.
7229   if (!HasFMAD && !HasFMA)
7230     return SDValue();
7231
7232   // Always prefer FMAD to FMA for precision.
7233   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7234   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7235   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7236
7237   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7238   if (N0.getOpcode() == ISD::FMUL &&
7239       (Aggressive || N0->hasOneUse())) {
7240     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7241                        N0.getOperand(0), N0.getOperand(1), N1);
7242   }
7243
7244   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7245   // Note: Commutes FADD operands.
7246   if (N1.getOpcode() == ISD::FMUL &&
7247       (Aggressive || N1->hasOneUse())) {
7248     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7249                        N1.getOperand(0), N1.getOperand(1), N0);
7250   }
7251
7252   // Look through FP_EXTEND nodes to do more combining.
7253   if (UnsafeFPMath && LookThroughFPExt) {
7254     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7255     if (N0.getOpcode() == ISD::FP_EXTEND) {
7256       SDValue N00 = N0.getOperand(0);
7257       if (N00.getOpcode() == ISD::FMUL)
7258         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7259                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7260                                        N00.getOperand(0)),
7261                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7262                                        N00.getOperand(1)), N1);
7263     }
7264
7265     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7266     // Note: Commutes FADD operands.
7267     if (N1.getOpcode() == ISD::FP_EXTEND) {
7268       SDValue N10 = N1.getOperand(0);
7269       if (N10.getOpcode() == ISD::FMUL)
7270         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7271                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7272                                        N10.getOperand(0)),
7273                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7274                                        N10.getOperand(1)), N0);
7275     }
7276   }
7277
7278   // More folding opportunities when target permits.
7279   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7280     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7281     if (N0.getOpcode() == PreferredFusedOpcode &&
7282         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7283       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7284                          N0.getOperand(0), N0.getOperand(1),
7285                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7286                                      N0.getOperand(2).getOperand(0),
7287                                      N0.getOperand(2).getOperand(1),
7288                                      N1));
7289     }
7290
7291     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7292     if (N1->getOpcode() == PreferredFusedOpcode &&
7293         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7294       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7295                          N1.getOperand(0), N1.getOperand(1),
7296                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7297                                      N1.getOperand(2).getOperand(0),
7298                                      N1.getOperand(2).getOperand(1),
7299                                      N0));
7300     }
7301
7302     if (UnsafeFPMath && LookThroughFPExt) {
7303       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7304       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7305       auto FoldFAddFMAFPExtFMul = [&] (
7306           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7307         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7308                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7309                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7310                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7311                                        Z));
7312       };
7313       if (N0.getOpcode() == PreferredFusedOpcode) {
7314         SDValue N02 = N0.getOperand(2);
7315         if (N02.getOpcode() == ISD::FP_EXTEND) {
7316           SDValue N020 = N02.getOperand(0);
7317           if (N020.getOpcode() == ISD::FMUL)
7318             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7319                                         N020.getOperand(0), N020.getOperand(1),
7320                                         N1);
7321         }
7322       }
7323
7324       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7325       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7326       // FIXME: This turns two single-precision and one double-precision
7327       // operation into two double-precision operations, which might not be
7328       // interesting for all targets, especially GPUs.
7329       auto FoldFAddFPExtFMAFMul = [&] (
7330           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7331         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7332                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7333                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7334                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7335                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7336                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7337                                        Z));
7338       };
7339       if (N0.getOpcode() == ISD::FP_EXTEND) {
7340         SDValue N00 = N0.getOperand(0);
7341         if (N00.getOpcode() == PreferredFusedOpcode) {
7342           SDValue N002 = N00.getOperand(2);
7343           if (N002.getOpcode() == ISD::FMUL)
7344             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7345                                         N002.getOperand(0), N002.getOperand(1),
7346                                         N1);
7347         }
7348       }
7349
7350       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7351       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7352       if (N1.getOpcode() == PreferredFusedOpcode) {
7353         SDValue N12 = N1.getOperand(2);
7354         if (N12.getOpcode() == ISD::FP_EXTEND) {
7355           SDValue N120 = N12.getOperand(0);
7356           if (N120.getOpcode() == ISD::FMUL)
7357             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7358                                         N120.getOperand(0), N120.getOperand(1),
7359                                         N0);
7360         }
7361       }
7362
7363       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7364       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7365       // FIXME: This turns two single-precision and one double-precision
7366       // operation into two double-precision operations, which might not be
7367       // interesting for all targets, especially GPUs.
7368       if (N1.getOpcode() == ISD::FP_EXTEND) {
7369         SDValue N10 = N1.getOperand(0);
7370         if (N10.getOpcode() == PreferredFusedOpcode) {
7371           SDValue N102 = N10.getOperand(2);
7372           if (N102.getOpcode() == ISD::FMUL)
7373             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7374                                         N102.getOperand(0), N102.getOperand(1),
7375                                         N0);
7376         }
7377       }
7378     }
7379   }
7380
7381   return SDValue();
7382 }
7383
7384 /// Try to perform FMA combining on a given FSUB node.
7385 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7386   SDValue N0 = N->getOperand(0);
7387   SDValue N1 = N->getOperand(1);
7388   EVT VT = N->getValueType(0);
7389   SDLoc SL(N);
7390
7391   const TargetOptions &Options = DAG.getTarget().Options;
7392   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7393                        Options.UnsafeFPMath);
7394
7395   // Floating-point multiply-add with intermediate rounding.
7396   bool HasFMAD = (LegalOperations &&
7397                   TLI.isOperationLegal(ISD::FMAD, VT));
7398
7399   // Floating-point multiply-add without intermediate rounding.
7400   bool HasFMA = ((!LegalOperations ||
7401                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7402                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7403                  UnsafeFPMath);
7404
7405   // No valid opcode, do not combine.
7406   if (!HasFMAD && !HasFMA)
7407     return SDValue();
7408
7409   // Always prefer FMAD to FMA for precision.
7410   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7411   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7412   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7413
7414   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7415   if (N0.getOpcode() == ISD::FMUL &&
7416       (Aggressive || N0->hasOneUse())) {
7417     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7418                        N0.getOperand(0), N0.getOperand(1),
7419                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7420   }
7421
7422   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7423   // Note: Commutes FSUB operands.
7424   if (N1.getOpcode() == ISD::FMUL &&
7425       (Aggressive || N1->hasOneUse()))
7426     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7427                        DAG.getNode(ISD::FNEG, SL, VT,
7428                                    N1.getOperand(0)),
7429                        N1.getOperand(1), N0);
7430
7431   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7432   if (N0.getOpcode() == ISD::FNEG &&
7433       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7434       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7435     SDValue N00 = N0.getOperand(0).getOperand(0);
7436     SDValue N01 = N0.getOperand(0).getOperand(1);
7437     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7438                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7439                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7440   }
7441
7442   // Look through FP_EXTEND nodes to do more combining.
7443   if (UnsafeFPMath && LookThroughFPExt) {
7444     // fold (fsub (fpext (fmul x, y)), z)
7445     //   -> (fma (fpext x), (fpext y), (fneg z))
7446     if (N0.getOpcode() == ISD::FP_EXTEND) {
7447       SDValue N00 = N0.getOperand(0);
7448       if (N00.getOpcode() == ISD::FMUL)
7449         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7450                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7451                                        N00.getOperand(0)),
7452                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7453                                        N00.getOperand(1)),
7454                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7455     }
7456
7457     // fold (fsub x, (fpext (fmul y, z)))
7458     //   -> (fma (fneg (fpext y)), (fpext z), x)
7459     // Note: Commutes FSUB operands.
7460     if (N1.getOpcode() == ISD::FP_EXTEND) {
7461       SDValue N10 = N1.getOperand(0);
7462       if (N10.getOpcode() == ISD::FMUL)
7463         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7464                            DAG.getNode(ISD::FNEG, SL, VT,
7465                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7466                                                    N10.getOperand(0))),
7467                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7468                                        N10.getOperand(1)),
7469                            N0);
7470     }
7471
7472     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7473     //   -> (fneg (fma (fpext x), (fpext y), z))
7474     // Note: This could be removed with appropriate canonicalization of the
7475     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7476     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7477     // from implementing the canonicalization in visitFSUB.
7478     if (N0.getOpcode() == ISD::FP_EXTEND) {
7479       SDValue N00 = N0.getOperand(0);
7480       if (N00.getOpcode() == ISD::FNEG) {
7481         SDValue N000 = N00.getOperand(0);
7482         if (N000.getOpcode() == ISD::FMUL) {
7483           return DAG.getNode(ISD::FNEG, SL, VT,
7484                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7485                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7486                                                      N000.getOperand(0)),
7487                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7488                                                      N000.getOperand(1)),
7489                                          N1));
7490         }
7491       }
7492     }
7493
7494     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7495     //   -> (fneg (fma (fpext x)), (fpext y), z)
7496     // Note: This could be removed with appropriate canonicalization of the
7497     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7498     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7499     // from implementing the canonicalization in visitFSUB.
7500     if (N0.getOpcode() == ISD::FNEG) {
7501       SDValue N00 = N0.getOperand(0);
7502       if (N00.getOpcode() == ISD::FP_EXTEND) {
7503         SDValue N000 = N00.getOperand(0);
7504         if (N000.getOpcode() == ISD::FMUL) {
7505           return DAG.getNode(ISD::FNEG, SL, VT,
7506                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7507                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7508                                                      N000.getOperand(0)),
7509                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7510                                                      N000.getOperand(1)),
7511                                          N1));
7512         }
7513       }
7514     }
7515
7516   }
7517
7518   // More folding opportunities when target permits.
7519   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7520     // fold (fsub (fma x, y, (fmul u, v)), z)
7521     //   -> (fma x, y (fma u, v, (fneg z)))
7522     if (N0.getOpcode() == PreferredFusedOpcode &&
7523         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7524       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7525                          N0.getOperand(0), N0.getOperand(1),
7526                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7527                                      N0.getOperand(2).getOperand(0),
7528                                      N0.getOperand(2).getOperand(1),
7529                                      DAG.getNode(ISD::FNEG, SL, VT,
7530                                                  N1)));
7531     }
7532
7533     // fold (fsub x, (fma y, z, (fmul u, v)))
7534     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7535     if (N1.getOpcode() == PreferredFusedOpcode &&
7536         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7537       SDValue N20 = N1.getOperand(2).getOperand(0);
7538       SDValue N21 = N1.getOperand(2).getOperand(1);
7539       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7540                          DAG.getNode(ISD::FNEG, SL, VT,
7541                                      N1.getOperand(0)),
7542                          N1.getOperand(1),
7543                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7544                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7545
7546                                      N21, N0));
7547     }
7548
7549     if (UnsafeFPMath && LookThroughFPExt) {
7550       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7551       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7552       if (N0.getOpcode() == PreferredFusedOpcode) {
7553         SDValue N02 = N0.getOperand(2);
7554         if (N02.getOpcode() == ISD::FP_EXTEND) {
7555           SDValue N020 = N02.getOperand(0);
7556           if (N020.getOpcode() == ISD::FMUL)
7557             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7558                                N0.getOperand(0), N0.getOperand(1),
7559                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7560                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7561                                                        N020.getOperand(0)),
7562                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7563                                                        N020.getOperand(1)),
7564                                            DAG.getNode(ISD::FNEG, SL, VT,
7565                                                        N1)));
7566         }
7567       }
7568
7569       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7570       //   -> (fma (fpext x), (fpext y),
7571       //           (fma (fpext u), (fpext v), (fneg z)))
7572       // FIXME: This turns two single-precision and one double-precision
7573       // operation into two double-precision operations, which might not be
7574       // interesting for all targets, especially GPUs.
7575       if (N0.getOpcode() == ISD::FP_EXTEND) {
7576         SDValue N00 = N0.getOperand(0);
7577         if (N00.getOpcode() == PreferredFusedOpcode) {
7578           SDValue N002 = N00.getOperand(2);
7579           if (N002.getOpcode() == ISD::FMUL)
7580             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7581                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7582                                            N00.getOperand(0)),
7583                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7584                                            N00.getOperand(1)),
7585                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7586                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7587                                                        N002.getOperand(0)),
7588                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7589                                                        N002.getOperand(1)),
7590                                            DAG.getNode(ISD::FNEG, SL, VT,
7591                                                        N1)));
7592         }
7593       }
7594
7595       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7596       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7597       if (N1.getOpcode() == PreferredFusedOpcode &&
7598         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7599         SDValue N120 = N1.getOperand(2).getOperand(0);
7600         if (N120.getOpcode() == ISD::FMUL) {
7601           SDValue N1200 = N120.getOperand(0);
7602           SDValue N1201 = N120.getOperand(1);
7603           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7604                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7605                              N1.getOperand(1),
7606                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7607                                          DAG.getNode(ISD::FNEG, SL, VT,
7608                                              DAG.getNode(ISD::FP_EXTEND, SL,
7609                                                          VT, N1200)),
7610                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7611                                                      N1201),
7612                                          N0));
7613         }
7614       }
7615
7616       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7617       //   -> (fma (fneg (fpext y)), (fpext z),
7618       //           (fma (fneg (fpext u)), (fpext v), x))
7619       // FIXME: This turns two single-precision and one double-precision
7620       // operation into two double-precision operations, which might not be
7621       // interesting for all targets, especially GPUs.
7622       if (N1.getOpcode() == ISD::FP_EXTEND &&
7623         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7624         SDValue N100 = N1.getOperand(0).getOperand(0);
7625         SDValue N101 = N1.getOperand(0).getOperand(1);
7626         SDValue N102 = N1.getOperand(0).getOperand(2);
7627         if (N102.getOpcode() == ISD::FMUL) {
7628           SDValue N1020 = N102.getOperand(0);
7629           SDValue N1021 = N102.getOperand(1);
7630           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7631                              DAG.getNode(ISD::FNEG, SL, VT,
7632                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7633                                                      N100)),
7634                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7635                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7636                                          DAG.getNode(ISD::FNEG, SL, VT,
7637                                              DAG.getNode(ISD::FP_EXTEND, SL,
7638                                                          VT, N1020)),
7639                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7640                                                      N1021),
7641                                          N0));
7642         }
7643       }
7644     }
7645   }
7646
7647   return SDValue();
7648 }
7649
7650 SDValue DAGCombiner::visitFADD(SDNode *N) {
7651   SDValue N0 = N->getOperand(0);
7652   SDValue N1 = N->getOperand(1);
7653   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7654   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7655   EVT VT = N->getValueType(0);
7656   const TargetOptions &Options = DAG.getTarget().Options;
7657
7658   // fold vector ops
7659   if (VT.isVector())
7660     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7661       return FoldedVOp;
7662
7663   // fold (fadd c1, c2) -> c1 + c2
7664   if (N0CFP && N1CFP)
7665     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7666
7667   // canonicalize constant to RHS
7668   if (N0CFP && !N1CFP)
7669     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7670
7671   // fold (fadd A, (fneg B)) -> (fsub A, B)
7672   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7673       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7674     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7675                        GetNegatedExpression(N1, DAG, LegalOperations));
7676
7677   // fold (fadd (fneg A), B) -> (fsub B, A)
7678   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7679       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7680     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7681                        GetNegatedExpression(N0, DAG, LegalOperations));
7682
7683   // If 'unsafe math' is enabled, fold lots of things.
7684   if (Options.UnsafeFPMath) {
7685     // No FP constant should be created after legalization as Instruction
7686     // Selection pass has a hard time dealing with FP constants.
7687     bool AllowNewConst = (Level < AfterLegalizeDAG);
7688
7689     // fold (fadd A, 0) -> A
7690     if (N1CFP && N1CFP->getValueAPF().isZero())
7691       return N0;
7692
7693     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7694     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7695         isa<ConstantFPSDNode>(N0.getOperand(1)))
7696       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7697                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7698                                      N0.getOperand(1), N1));
7699
7700     // If allowed, fold (fadd (fneg x), x) -> 0.0
7701     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7702       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7703
7704     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7705     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7706       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7707
7708     // We can fold chains of FADD's of the same value into multiplications.
7709     // This transform is not safe in general because we are reducing the number
7710     // of rounding steps.
7711     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7712       if (N0.getOpcode() == ISD::FMUL) {
7713         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7714         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7715
7716         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7717         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7718           SDLoc DL(N);
7719           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7720                                        SDValue(CFP01, 0),
7721                                        DAG.getConstantFP(1.0, DL, VT));
7722           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7723         }
7724
7725         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7726         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7727             N1.getOperand(0) == N1.getOperand(1) &&
7728             N0.getOperand(0) == N1.getOperand(0)) {
7729           SDLoc DL(N);
7730           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7731                                        SDValue(CFP01, 0),
7732                                        DAG.getConstantFP(2.0, DL, VT));
7733           return DAG.getNode(ISD::FMUL, DL, VT,
7734                              N0.getOperand(0), NewCFP);
7735         }
7736       }
7737
7738       if (N1.getOpcode() == ISD::FMUL) {
7739         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7740         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7741
7742         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7743         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7744           SDLoc DL(N);
7745           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7746                                        SDValue(CFP11, 0),
7747                                        DAG.getConstantFP(1.0, DL, VT));
7748           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7749         }
7750
7751         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7752         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7753             N0.getOperand(0) == N0.getOperand(1) &&
7754             N1.getOperand(0) == N0.getOperand(0)) {
7755           SDLoc DL(N);
7756           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7757                                        SDValue(CFP11, 0),
7758                                        DAG.getConstantFP(2.0, DL, VT));
7759           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7760         }
7761       }
7762
7763       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7764         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7765         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7766         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7767             (N0.getOperand(0) == N1)) {
7768           SDLoc DL(N);
7769           return DAG.getNode(ISD::FMUL, DL, VT,
7770                              N1, DAG.getConstantFP(3.0, DL, VT));
7771         }
7772       }
7773
7774       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7775         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7776         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7777         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7778             N1.getOperand(0) == N0) {
7779           SDLoc DL(N);
7780           return DAG.getNode(ISD::FMUL, DL, VT,
7781                              N0, DAG.getConstantFP(3.0, DL, VT));
7782         }
7783       }
7784
7785       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7786       if (AllowNewConst &&
7787           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7788           N0.getOperand(0) == N0.getOperand(1) &&
7789           N1.getOperand(0) == N1.getOperand(1) &&
7790           N0.getOperand(0) == N1.getOperand(0)) {
7791         SDLoc DL(N);
7792         return DAG.getNode(ISD::FMUL, DL, VT,
7793                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7794       }
7795     }
7796
7797     // Canonicalize chains of adds to LHS to simplify the following transform.
7798     if (N0.getOpcode() != ISD::FADD && N1.getOpcode() == ISD::FADD)
7799       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7800     
7801     // Convert a chain of 3 dependent operations into 2 independent operations
7802     // and 1 dependent operation:
7803     //  (fadd N0: (fadd N00: (fadd z, w), N01: y), N1: x) ->
7804     //  (fadd N00: (fadd z, w), (fadd N1: x, N01: y))
7805     if (N0.getOpcode() == ISD::FADD &&  N0.hasOneUse() &&
7806         N1.getOpcode() != ISD::FADD) {
7807       SDValue N00 = N0.getOperand(0);
7808       if (N00.getOpcode() == ISD::FADD) {
7809         SDValue N01 = N0.getOperand(1);
7810         SDValue NewAdd = DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N01);
7811         return DAG.getNode(ISD::FADD, SDLoc(N), VT, N00, NewAdd);
7812       }
7813     }
7814   } // enable-unsafe-fp-math
7815
7816   // FADD -> FMA combines:
7817   SDValue Fused = visitFADDForFMACombine(N);
7818   if (Fused) {
7819     AddToWorklist(Fused.getNode());
7820     return Fused;
7821   }
7822
7823   return SDValue();
7824 }
7825
7826 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7827   SDValue N0 = N->getOperand(0);
7828   SDValue N1 = N->getOperand(1);
7829   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7830   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7831   EVT VT = N->getValueType(0);
7832   SDLoc dl(N);
7833   const TargetOptions &Options = DAG.getTarget().Options;
7834
7835   // fold vector ops
7836   if (VT.isVector())
7837     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7838       return FoldedVOp;
7839
7840   // fold (fsub c1, c2) -> c1-c2
7841   if (N0CFP && N1CFP)
7842     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7843
7844   // fold (fsub A, (fneg B)) -> (fadd A, B)
7845   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7846     return DAG.getNode(ISD::FADD, dl, VT, N0,
7847                        GetNegatedExpression(N1, DAG, LegalOperations));
7848
7849   // If 'unsafe math' is enabled, fold lots of things.
7850   if (Options.UnsafeFPMath) {
7851     // (fsub A, 0) -> A
7852     if (N1CFP && N1CFP->getValueAPF().isZero())
7853       return N0;
7854
7855     // (fsub 0, B) -> -B
7856     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7857       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7858         return GetNegatedExpression(N1, DAG, LegalOperations);
7859       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7860         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7861     }
7862
7863     // (fsub x, x) -> 0.0
7864     if (N0 == N1)
7865       return DAG.getConstantFP(0.0f, dl, VT);
7866
7867     // (fsub x, (fadd x, y)) -> (fneg y)
7868     // (fsub x, (fadd y, x)) -> (fneg y)
7869     if (N1.getOpcode() == ISD::FADD) {
7870       SDValue N10 = N1->getOperand(0);
7871       SDValue N11 = N1->getOperand(1);
7872
7873       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7874         return GetNegatedExpression(N11, DAG, LegalOperations);
7875
7876       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7877         return GetNegatedExpression(N10, DAG, LegalOperations);
7878     }
7879   }
7880
7881   // FSUB -> FMA combines:
7882   SDValue Fused = visitFSUBForFMACombine(N);
7883   if (Fused) {
7884     AddToWorklist(Fused.getNode());
7885     return Fused;
7886   }
7887
7888   return SDValue();
7889 }
7890
7891 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7892   SDValue N0 = N->getOperand(0);
7893   SDValue N1 = N->getOperand(1);
7894   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7895   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7896   EVT VT = N->getValueType(0);
7897   const TargetOptions &Options = DAG.getTarget().Options;
7898
7899   // fold vector ops
7900   if (VT.isVector()) {
7901     // This just handles C1 * C2 for vectors. Other vector folds are below.
7902     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7903       return FoldedVOp;
7904   }
7905
7906   // fold (fmul c1, c2) -> c1*c2
7907   if (N0CFP && N1CFP)
7908     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7909
7910   // canonicalize constant to RHS
7911   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7912      !isConstantFPBuildVectorOrConstantFP(N1))
7913     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7914
7915   // fold (fmul A, 1.0) -> A
7916   if (N1CFP && N1CFP->isExactlyValue(1.0))
7917     return N0;
7918
7919   if (Options.UnsafeFPMath) {
7920     // fold (fmul A, 0) -> 0
7921     if (N1CFP && N1CFP->getValueAPF().isZero())
7922       return N1;
7923
7924     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7925     if (N0.getOpcode() == ISD::FMUL) {
7926       // Fold scalars or any vector constants (not just splats).
7927       // This fold is done in general by InstCombine, but extra fmul insts
7928       // may have been generated during lowering.
7929       SDValue N00 = N0.getOperand(0);
7930       SDValue N01 = N0.getOperand(1);
7931       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7932       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7933       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7934       
7935       // Check 1: Make sure that the first operand of the inner multiply is NOT
7936       // a constant. Otherwise, we may induce infinite looping.
7937       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7938         // Check 2: Make sure that the second operand of the inner multiply and
7939         // the second operand of the outer multiply are constants.
7940         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7941             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7942           SDLoc SL(N);
7943           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7944           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7945         }
7946       }
7947     }
7948
7949     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7950     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7951     // during an early run of DAGCombiner can prevent folding with fmuls
7952     // inserted during lowering.
7953     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7954       SDLoc SL(N);
7955       const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7956       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7957       return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7958     }
7959   }
7960
7961   // fold (fmul X, 2.0) -> (fadd X, X)
7962   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7963     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7964
7965   // fold (fmul X, -1.0) -> (fneg X)
7966   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7967     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7968       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7969
7970   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7971   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7972     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7973       // Both can be negated for free, check to see if at least one is cheaper
7974       // negated.
7975       if (LHSNeg == 2 || RHSNeg == 2)
7976         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7977                            GetNegatedExpression(N0, DAG, LegalOperations),
7978                            GetNegatedExpression(N1, DAG, LegalOperations));
7979     }
7980   }
7981
7982   return SDValue();
7983 }
7984
7985 SDValue DAGCombiner::visitFMA(SDNode *N) {
7986   SDValue N0 = N->getOperand(0);
7987   SDValue N1 = N->getOperand(1);
7988   SDValue N2 = N->getOperand(2);
7989   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7990   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7991   EVT VT = N->getValueType(0);
7992   SDLoc dl(N);
7993   const TargetOptions &Options = DAG.getTarget().Options;
7994
7995   // Constant fold FMA.
7996   if (isa<ConstantFPSDNode>(N0) &&
7997       isa<ConstantFPSDNode>(N1) &&
7998       isa<ConstantFPSDNode>(N2)) {
7999     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
8000   }
8001
8002   if (Options.UnsafeFPMath) {
8003     if (N0CFP && N0CFP->isZero())
8004       return N2;
8005     if (N1CFP && N1CFP->isZero())
8006       return N2;
8007   }
8008   if (N0CFP && N0CFP->isExactlyValue(1.0))
8009     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8010   if (N1CFP && N1CFP->isExactlyValue(1.0))
8011     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8012
8013   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8014   if (N0CFP && !N1CFP)
8015     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8016
8017   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8018   if (Options.UnsafeFPMath && N1CFP &&
8019       N2.getOpcode() == ISD::FMUL &&
8020       N0 == N2.getOperand(0) &&
8021       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8022     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8023                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8024   }
8025
8026
8027   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8028   if (Options.UnsafeFPMath &&
8029       N0.getOpcode() == ISD::FMUL && N1CFP &&
8030       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8031     return DAG.getNode(ISD::FMA, dl, VT,
8032                        N0.getOperand(0),
8033                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8034                        N2);
8035   }
8036
8037   // (fma x, 1, y) -> (fadd x, y)
8038   // (fma x, -1, y) -> (fadd (fneg x), y)
8039   if (N1CFP) {
8040     if (N1CFP->isExactlyValue(1.0))
8041       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8042
8043     if (N1CFP->isExactlyValue(-1.0) &&
8044         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8045       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8046       AddToWorklist(RHSNeg.getNode());
8047       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8048     }
8049   }
8050
8051   // (fma x, c, x) -> (fmul x, (c+1))
8052   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8053     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8054                        DAG.getNode(ISD::FADD, dl, VT,
8055                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8056
8057   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8058   if (Options.UnsafeFPMath && N1CFP &&
8059       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8060     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8061                        DAG.getNode(ISD::FADD, dl, VT,
8062                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8063
8064
8065   return SDValue();
8066 }
8067
8068 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8069   SDValue N0 = N->getOperand(0);
8070   SDValue N1 = N->getOperand(1);
8071   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8072   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8073   EVT VT = N->getValueType(0);
8074   SDLoc DL(N);
8075   const TargetOptions &Options = DAG.getTarget().Options;
8076
8077   // fold vector ops
8078   if (VT.isVector())
8079     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8080       return FoldedVOp;
8081
8082   // fold (fdiv c1, c2) -> c1/c2
8083   if (N0CFP && N1CFP)
8084     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8085
8086   if (Options.UnsafeFPMath) {
8087     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8088     if (N1CFP) {
8089       // Compute the reciprocal 1.0 / c2.
8090       APFloat N1APF = N1CFP->getValueAPF();
8091       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8092       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8093       // Only do the transform if the reciprocal is a legal fp immediate that
8094       // isn't too nasty (eg NaN, denormal, ...).
8095       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8096           (!LegalOperations ||
8097            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8098            // backend)... we should handle this gracefully after Legalize.
8099            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8100            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8101            TLI.isFPImmLegal(Recip, VT)))
8102         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8103                            DAG.getConstantFP(Recip, DL, VT));
8104     }
8105
8106     // If this FDIV is part of a reciprocal square root, it may be folded
8107     // into a target-specific square root estimate instruction.
8108     if (N1.getOpcode() == ISD::FSQRT) {
8109       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8110         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8111       }
8112     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8113                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8114       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8115         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8116         AddToWorklist(RV.getNode());
8117         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8118       }
8119     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8120                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8121       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8122         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8123         AddToWorklist(RV.getNode());
8124         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8125       }
8126     } else if (N1.getOpcode() == ISD::FMUL) {
8127       // Look through an FMUL. Even though this won't remove the FDIV directly,
8128       // it's still worthwhile to get rid of the FSQRT if possible.
8129       SDValue SqrtOp;
8130       SDValue OtherOp;
8131       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8132         SqrtOp = N1.getOperand(0);
8133         OtherOp = N1.getOperand(1);
8134       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8135         SqrtOp = N1.getOperand(1);
8136         OtherOp = N1.getOperand(0);
8137       }
8138       if (SqrtOp.getNode()) {
8139         // We found a FSQRT, so try to make this fold:
8140         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8141         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8142           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8143           AddToWorklist(RV.getNode());
8144           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8145         }
8146       }
8147     }
8148
8149     // Fold into a reciprocal estimate and multiply instead of a real divide.
8150     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8151       AddToWorklist(RV.getNode());
8152       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8153     }
8154   }
8155
8156   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8157   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8158     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8159       // Both can be negated for free, check to see if at least one is cheaper
8160       // negated.
8161       if (LHSNeg == 2 || RHSNeg == 2)
8162         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8163                            GetNegatedExpression(N0, DAG, LegalOperations),
8164                            GetNegatedExpression(N1, DAG, LegalOperations));
8165     }
8166   }
8167
8168   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8169   // reciprocal.
8170   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8171   // Notice that this is not always beneficial. One reason is different target
8172   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8173   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8174   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8175   if (Options.UnsafeFPMath) {
8176     // Skip if current node is a reciprocal.
8177     if (N0CFP && N0CFP->isExactlyValue(1.0))
8178       return SDValue();
8179
8180     SmallVector<SDNode *, 4> Users;
8181     // Find all FDIV users of the same divisor.
8182     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8183                               UE = N1.getNode()->use_end();
8184          UI != UE; ++UI) {
8185       SDNode *User = UI.getUse().getUser();
8186       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8187         Users.push_back(User);
8188     }
8189
8190     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8191       SDLoc DL(N);
8192       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8193       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8194
8195       // Dividend / Divisor -> Dividend * Reciprocal
8196       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8197         if ((*I)->getOperand(0) != FPOne) {
8198           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8199                                         (*I)->getOperand(0), Reciprocal);
8200           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8201         }
8202       }
8203       return SDValue();
8204     }
8205   }
8206
8207   return SDValue();
8208 }
8209
8210 SDValue DAGCombiner::visitFREM(SDNode *N) {
8211   SDValue N0 = N->getOperand(0);
8212   SDValue N1 = N->getOperand(1);
8213   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8214   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8215   EVT VT = N->getValueType(0);
8216
8217   // fold (frem c1, c2) -> fmod(c1,c2)
8218   if (N0CFP && N1CFP)
8219     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8220
8221   return SDValue();
8222 }
8223
8224 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8225   if (DAG.getTarget().Options.UnsafeFPMath &&
8226       !TLI.isFsqrtCheap()) {
8227     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8228     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8229       EVT VT = RV.getValueType();
8230       SDLoc DL(N);
8231       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8232       AddToWorklist(RV.getNode());
8233
8234       // Unfortunately, RV is now NaN if the input was exactly 0.
8235       // Select out this case and force the answer to 0.
8236       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8237       SDValue ZeroCmp =
8238         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8239                      N->getOperand(0), Zero, ISD::SETEQ);
8240       AddToWorklist(ZeroCmp.getNode());
8241       AddToWorklist(RV.getNode());
8242
8243       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8244                        DL, VT, ZeroCmp, Zero, RV);
8245       return RV;
8246     }
8247   }
8248   return SDValue();
8249 }
8250
8251 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8252   SDValue N0 = N->getOperand(0);
8253   SDValue N1 = N->getOperand(1);
8254   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8255   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8256   EVT VT = N->getValueType(0);
8257
8258   if (N0CFP && N1CFP)  // Constant fold
8259     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8260
8261   if (N1CFP) {
8262     const APFloat& V = N1CFP->getValueAPF();
8263     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8264     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8265     if (!V.isNegative()) {
8266       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8267         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8268     } else {
8269       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8270         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8271                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8272     }
8273   }
8274
8275   // copysign(fabs(x), y) -> copysign(x, y)
8276   // copysign(fneg(x), y) -> copysign(x, y)
8277   // copysign(copysign(x,z), y) -> copysign(x, y)
8278   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8279       N0.getOpcode() == ISD::FCOPYSIGN)
8280     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8281                        N0.getOperand(0), N1);
8282
8283   // copysign(x, abs(y)) -> abs(x)
8284   if (N1.getOpcode() == ISD::FABS)
8285     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8286
8287   // copysign(x, copysign(y,z)) -> copysign(x, z)
8288   if (N1.getOpcode() == ISD::FCOPYSIGN)
8289     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8290                        N0, N1.getOperand(1));
8291
8292   // copysign(x, fp_extend(y)) -> copysign(x, y)
8293   // copysign(x, fp_round(y)) -> copysign(x, y)
8294   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8295     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8296                        N0, N1.getOperand(0));
8297
8298   return SDValue();
8299 }
8300
8301 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8302   SDValue N0 = N->getOperand(0);
8303   EVT VT = N->getValueType(0);
8304   EVT OpVT = N0.getValueType();
8305
8306   // fold (sint_to_fp c1) -> c1fp
8307   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8308       // ...but only if the target supports immediate floating-point values
8309       (!LegalOperations ||
8310        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8311     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8312
8313   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8314   // but UINT_TO_FP is legal on this target, try to convert.
8315   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8316       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8317     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8318     if (DAG.SignBitIsZero(N0))
8319       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8320   }
8321
8322   // The next optimizations are desirable only if SELECT_CC can be lowered.
8323   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8324     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8325     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8326         !VT.isVector() &&
8327         (!LegalOperations ||
8328          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8329       SDLoc DL(N);
8330       SDValue Ops[] =
8331         { N0.getOperand(0), N0.getOperand(1),
8332           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8333           N0.getOperand(2) };
8334       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8335     }
8336
8337     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8338     //      (select_cc x, y, 1.0, 0.0,, cc)
8339     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8340         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8341         (!LegalOperations ||
8342          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8343       SDLoc DL(N);
8344       SDValue Ops[] =
8345         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8346           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8347           N0.getOperand(0).getOperand(2) };
8348       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8349     }
8350   }
8351
8352   return SDValue();
8353 }
8354
8355 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8356   SDValue N0 = N->getOperand(0);
8357   EVT VT = N->getValueType(0);
8358   EVT OpVT = N0.getValueType();
8359
8360   // fold (uint_to_fp c1) -> c1fp
8361   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8362       // ...but only if the target supports immediate floating-point values
8363       (!LegalOperations ||
8364        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8365     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8366
8367   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8368   // but SINT_TO_FP is legal on this target, try to convert.
8369   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8370       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8371     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8372     if (DAG.SignBitIsZero(N0))
8373       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8374   }
8375
8376   // The next optimizations are desirable only if SELECT_CC can be lowered.
8377   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8378     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8379
8380     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8381         (!LegalOperations ||
8382          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8383       SDLoc DL(N);
8384       SDValue Ops[] =
8385         { N0.getOperand(0), N0.getOperand(1),
8386           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8387           N0.getOperand(2) };
8388       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8389     }
8390   }
8391
8392   return SDValue();
8393 }
8394
8395 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8396 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8397   SDValue N0 = N->getOperand(0);
8398   EVT VT = N->getValueType(0);
8399
8400   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8401     return SDValue();
8402
8403   SDValue Src = N0.getOperand(0);
8404   EVT SrcVT = Src.getValueType();
8405   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8406   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8407
8408   // We can safely assume the conversion won't overflow the output range,
8409   // because (for example) (uint8_t)18293.f is undefined behavior.
8410
8411   // Since we can assume the conversion won't overflow, our decision as to
8412   // whether the input will fit in the float should depend on the minimum
8413   // of the input range and output range.
8414
8415   // This means this is also safe for a signed input and unsigned output, since
8416   // a negative input would lead to undefined behavior.
8417   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8418   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8419   unsigned ActualSize = std::min(InputSize, OutputSize);
8420   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8421
8422   // We can only fold away the float conversion if the input range can be
8423   // represented exactly in the float range.
8424   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8425     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8426       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8427                                                        : ISD::ZERO_EXTEND;
8428       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8429     }
8430     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8431       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8432     if (SrcVT == VT)
8433       return Src;
8434     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8435   }
8436   return SDValue();
8437 }
8438
8439 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8440   SDValue N0 = N->getOperand(0);
8441   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8442   EVT VT = N->getValueType(0);
8443
8444   // fold (fp_to_sint c1fp) -> c1
8445   if (N0CFP)
8446     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8447
8448   return FoldIntToFPToInt(N, DAG);
8449 }
8450
8451 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8452   SDValue N0 = N->getOperand(0);
8453   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8454   EVT VT = N->getValueType(0);
8455
8456   // fold (fp_to_uint c1fp) -> c1
8457   if (N0CFP)
8458     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8459
8460   return FoldIntToFPToInt(N, DAG);
8461 }
8462
8463 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8464   SDValue N0 = N->getOperand(0);
8465   SDValue N1 = N->getOperand(1);
8466   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8467   EVT VT = N->getValueType(0);
8468
8469   // fold (fp_round c1fp) -> c1fp
8470   if (N0CFP)
8471     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8472
8473   // fold (fp_round (fp_extend x)) -> x
8474   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8475     return N0.getOperand(0);
8476
8477   // fold (fp_round (fp_round x)) -> (fp_round x)
8478   if (N0.getOpcode() == ISD::FP_ROUND) {
8479     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8480     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8481     // If the first fp_round isn't a value preserving truncation, it might
8482     // introduce a tie in the second fp_round, that wouldn't occur in the
8483     // single-step fp_round we want to fold to.
8484     // In other words, double rounding isn't the same as rounding.
8485     // Also, this is a value preserving truncation iff both fp_round's are.
8486     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8487       SDLoc DL(N);
8488       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8489                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8490     }
8491   }
8492
8493   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8494   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8495     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8496                               N0.getOperand(0), N1);
8497     AddToWorklist(Tmp.getNode());
8498     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8499                        Tmp, N0.getOperand(1));
8500   }
8501
8502   return SDValue();
8503 }
8504
8505 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8506   SDValue N0 = N->getOperand(0);
8507   EVT VT = N->getValueType(0);
8508   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8509   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8510
8511   // fold (fp_round_inreg c1fp) -> c1fp
8512   if (N0CFP && isTypeLegal(EVT)) {
8513     SDLoc DL(N);
8514     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8515     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8516   }
8517
8518   return SDValue();
8519 }
8520
8521 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8522   SDValue N0 = N->getOperand(0);
8523   EVT VT = N->getValueType(0);
8524
8525   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8526   if (N->hasOneUse() &&
8527       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8528     return SDValue();
8529
8530   // fold (fp_extend c1fp) -> c1fp
8531   if (isConstantFPBuildVectorOrConstantFP(N0))
8532     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8533
8534   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8535   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8536       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8537     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8538
8539   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8540   // value of X.
8541   if (N0.getOpcode() == ISD::FP_ROUND
8542       && N0.getNode()->getConstantOperandVal(1) == 1) {
8543     SDValue In = N0.getOperand(0);
8544     if (In.getValueType() == VT) return In;
8545     if (VT.bitsLT(In.getValueType()))
8546       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8547                          In, N0.getOperand(1));
8548     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8549   }
8550
8551   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8552   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8553        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8554     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8555     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8556                                      LN0->getChain(),
8557                                      LN0->getBasePtr(), N0.getValueType(),
8558                                      LN0->getMemOperand());
8559     CombineTo(N, ExtLoad);
8560     CombineTo(N0.getNode(),
8561               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8562                           N0.getValueType(), ExtLoad,
8563                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8564               ExtLoad.getValue(1));
8565     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8566   }
8567
8568   return SDValue();
8569 }
8570
8571 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8572   SDValue N0 = N->getOperand(0);
8573   EVT VT = N->getValueType(0);
8574
8575   // fold (fceil c1) -> fceil(c1)
8576   if (isConstantFPBuildVectorOrConstantFP(N0))
8577     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8578
8579   return SDValue();
8580 }
8581
8582 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8583   SDValue N0 = N->getOperand(0);
8584   EVT VT = N->getValueType(0);
8585
8586   // fold (ftrunc c1) -> ftrunc(c1)
8587   if (isConstantFPBuildVectorOrConstantFP(N0))
8588     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8589
8590   return SDValue();
8591 }
8592
8593 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8594   SDValue N0 = N->getOperand(0);
8595   EVT VT = N->getValueType(0);
8596
8597   // fold (ffloor c1) -> ffloor(c1)
8598   if (isConstantFPBuildVectorOrConstantFP(N0))
8599     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8600
8601   return SDValue();
8602 }
8603
8604 // FIXME: FNEG and FABS have a lot in common; refactor.
8605 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8606   SDValue N0 = N->getOperand(0);
8607   EVT VT = N->getValueType(0);
8608
8609   // Constant fold FNEG.
8610   if (isConstantFPBuildVectorOrConstantFP(N0))
8611     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8612
8613   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8614                          &DAG.getTarget().Options))
8615     return GetNegatedExpression(N0, DAG, LegalOperations);
8616
8617   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8618   // constant pool values.
8619   if (!TLI.isFNegFree(VT) &&
8620       N0.getOpcode() == ISD::BITCAST &&
8621       N0.getNode()->hasOneUse()) {
8622     SDValue Int = N0.getOperand(0);
8623     EVT IntVT = Int.getValueType();
8624     if (IntVT.isInteger() && !IntVT.isVector()) {
8625       APInt SignMask;
8626       if (N0.getValueType().isVector()) {
8627         // For a vector, get a mask such as 0x80... per scalar element
8628         // and splat it.
8629         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8630         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8631       } else {
8632         // For a scalar, just generate 0x80...
8633         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8634       }
8635       SDLoc DL0(N0);
8636       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8637                         DAG.getConstant(SignMask, DL0, IntVT));
8638       AddToWorklist(Int.getNode());
8639       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8640     }
8641   }
8642
8643   // (fneg (fmul c, x)) -> (fmul -c, x)
8644   if (N0.getOpcode() == ISD::FMUL) {
8645     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8646     if (CFP1) {
8647       APFloat CVal = CFP1->getValueAPF();
8648       CVal.changeSign();
8649       if (Level >= AfterLegalizeDAG &&
8650           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8651            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8652         return DAG.getNode(
8653             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8654             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8655     }
8656   }
8657
8658   return SDValue();
8659 }
8660
8661 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8662   SDValue N0 = N->getOperand(0);
8663   SDValue N1 = N->getOperand(1);
8664   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8665   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8666
8667   if (N0CFP && N1CFP) {
8668     const APFloat &C0 = N0CFP->getValueAPF();
8669     const APFloat &C1 = N1CFP->getValueAPF();
8670     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8671   }
8672
8673   if (N0CFP) {
8674     EVT VT = N->getValueType(0);
8675     // Canonicalize to constant on RHS.
8676     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8677   }
8678
8679   return SDValue();
8680 }
8681
8682 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8683   SDValue N0 = N->getOperand(0);
8684   SDValue N1 = N->getOperand(1);
8685   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8686   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8687
8688   if (N0CFP && N1CFP) {
8689     const APFloat &C0 = N0CFP->getValueAPF();
8690     const APFloat &C1 = N1CFP->getValueAPF();
8691     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8692   }
8693
8694   if (N0CFP) {
8695     EVT VT = N->getValueType(0);
8696     // Canonicalize to constant on RHS.
8697     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8698   }
8699
8700   return SDValue();
8701 }
8702
8703 SDValue DAGCombiner::visitFABS(SDNode *N) {
8704   SDValue N0 = N->getOperand(0);
8705   EVT VT = N->getValueType(0);
8706
8707   // fold (fabs c1) -> fabs(c1)
8708   if (isConstantFPBuildVectorOrConstantFP(N0))
8709     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8710
8711   // fold (fabs (fabs x)) -> (fabs x)
8712   if (N0.getOpcode() == ISD::FABS)
8713     return N->getOperand(0);
8714
8715   // fold (fabs (fneg x)) -> (fabs x)
8716   // fold (fabs (fcopysign x, y)) -> (fabs x)
8717   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8718     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8719
8720   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8721   // constant pool values.
8722   if (!TLI.isFAbsFree(VT) &&
8723       N0.getOpcode() == ISD::BITCAST &&
8724       N0.getNode()->hasOneUse()) {
8725     SDValue Int = N0.getOperand(0);
8726     EVT IntVT = Int.getValueType();
8727     if (IntVT.isInteger() && !IntVT.isVector()) {
8728       APInt SignMask;
8729       if (N0.getValueType().isVector()) {
8730         // For a vector, get a mask such as 0x7f... per scalar element
8731         // and splat it.
8732         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8733         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8734       } else {
8735         // For a scalar, just generate 0x7f...
8736         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8737       }
8738       SDLoc DL(N0);
8739       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8740                         DAG.getConstant(SignMask, DL, IntVT));
8741       AddToWorklist(Int.getNode());
8742       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8743     }
8744   }
8745
8746   return SDValue();
8747 }
8748
8749 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8750   SDValue Chain = N->getOperand(0);
8751   SDValue N1 = N->getOperand(1);
8752   SDValue N2 = N->getOperand(2);
8753
8754   // If N is a constant we could fold this into a fallthrough or unconditional
8755   // branch. However that doesn't happen very often in normal code, because
8756   // Instcombine/SimplifyCFG should have handled the available opportunities.
8757   // If we did this folding here, it would be necessary to update the
8758   // MachineBasicBlock CFG, which is awkward.
8759
8760   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8761   // on the target.
8762   if (N1.getOpcode() == ISD::SETCC &&
8763       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8764                                    N1.getOperand(0).getValueType())) {
8765     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8766                        Chain, N1.getOperand(2),
8767                        N1.getOperand(0), N1.getOperand(1), N2);
8768   }
8769
8770   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8771       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8772        (N1.getOperand(0).hasOneUse() &&
8773         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8774     SDNode *Trunc = nullptr;
8775     if (N1.getOpcode() == ISD::TRUNCATE) {
8776       // Look pass the truncate.
8777       Trunc = N1.getNode();
8778       N1 = N1.getOperand(0);
8779     }
8780
8781     // Match this pattern so that we can generate simpler code:
8782     //
8783     //   %a = ...
8784     //   %b = and i32 %a, 2
8785     //   %c = srl i32 %b, 1
8786     //   brcond i32 %c ...
8787     //
8788     // into
8789     //
8790     //   %a = ...
8791     //   %b = and i32 %a, 2
8792     //   %c = setcc eq %b, 0
8793     //   brcond %c ...
8794     //
8795     // This applies only when the AND constant value has one bit set and the
8796     // SRL constant is equal to the log2 of the AND constant. The back-end is
8797     // smart enough to convert the result into a TEST/JMP sequence.
8798     SDValue Op0 = N1.getOperand(0);
8799     SDValue Op1 = N1.getOperand(1);
8800
8801     if (Op0.getOpcode() == ISD::AND &&
8802         Op1.getOpcode() == ISD::Constant) {
8803       SDValue AndOp1 = Op0.getOperand(1);
8804
8805       if (AndOp1.getOpcode() == ISD::Constant) {
8806         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8807
8808         if (AndConst.isPowerOf2() &&
8809             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8810           SDLoc DL(N);
8811           SDValue SetCC =
8812             DAG.getSetCC(DL,
8813                          getSetCCResultType(Op0.getValueType()),
8814                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8815                          ISD::SETNE);
8816
8817           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8818                                           MVT::Other, Chain, SetCC, N2);
8819           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8820           // will convert it back to (X & C1) >> C2.
8821           CombineTo(N, NewBRCond, false);
8822           // Truncate is dead.
8823           if (Trunc)
8824             deleteAndRecombine(Trunc);
8825           // Replace the uses of SRL with SETCC
8826           WorklistRemover DeadNodes(*this);
8827           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8828           deleteAndRecombine(N1.getNode());
8829           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8830         }
8831       }
8832     }
8833
8834     if (Trunc)
8835       // Restore N1 if the above transformation doesn't match.
8836       N1 = N->getOperand(1);
8837   }
8838
8839   // Transform br(xor(x, y)) -> br(x != y)
8840   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8841   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8842     SDNode *TheXor = N1.getNode();
8843     SDValue Op0 = TheXor->getOperand(0);
8844     SDValue Op1 = TheXor->getOperand(1);
8845     if (Op0.getOpcode() == Op1.getOpcode()) {
8846       // Avoid missing important xor optimizations.
8847       SDValue Tmp = visitXOR(TheXor);
8848       if (Tmp.getNode()) {
8849         if (Tmp.getNode() != TheXor) {
8850           DEBUG(dbgs() << "\nReplacing.8 ";
8851                 TheXor->dump(&DAG);
8852                 dbgs() << "\nWith: ";
8853                 Tmp.getNode()->dump(&DAG);
8854                 dbgs() << '\n');
8855           WorklistRemover DeadNodes(*this);
8856           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8857           deleteAndRecombine(TheXor);
8858           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8859                              MVT::Other, Chain, Tmp, N2);
8860         }
8861
8862         // visitXOR has changed XOR's operands or replaced the XOR completely,
8863         // bail out.
8864         return SDValue(N, 0);
8865       }
8866     }
8867
8868     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8869       bool Equal = false;
8870       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8871         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8872             Op0.getOpcode() == ISD::XOR) {
8873           TheXor = Op0.getNode();
8874           Equal = true;
8875         }
8876
8877       EVT SetCCVT = N1.getValueType();
8878       if (LegalTypes)
8879         SetCCVT = getSetCCResultType(SetCCVT);
8880       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8881                                    SetCCVT,
8882                                    Op0, Op1,
8883                                    Equal ? ISD::SETEQ : ISD::SETNE);
8884       // Replace the uses of XOR with SETCC
8885       WorklistRemover DeadNodes(*this);
8886       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8887       deleteAndRecombine(N1.getNode());
8888       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8889                          MVT::Other, Chain, SetCC, N2);
8890     }
8891   }
8892
8893   return SDValue();
8894 }
8895
8896 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8897 //
8898 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8899   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8900   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8901
8902   // If N is a constant we could fold this into a fallthrough or unconditional
8903   // branch. However that doesn't happen very often in normal code, because
8904   // Instcombine/SimplifyCFG should have handled the available opportunities.
8905   // If we did this folding here, it would be necessary to update the
8906   // MachineBasicBlock CFG, which is awkward.
8907
8908   // Use SimplifySetCC to simplify SETCC's.
8909   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8910                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8911                                false);
8912   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8913
8914   // fold to a simpler setcc
8915   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8916     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8917                        N->getOperand(0), Simp.getOperand(2),
8918                        Simp.getOperand(0), Simp.getOperand(1),
8919                        N->getOperand(4));
8920
8921   return SDValue();
8922 }
8923
8924 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8925 /// and that N may be folded in the load / store addressing mode.
8926 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8927                                     SelectionDAG &DAG,
8928                                     const TargetLowering &TLI) {
8929   EVT VT;
8930   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8931     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8932       return false;
8933     VT = LD->getMemoryVT();
8934   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8935     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8936       return false;
8937     VT = ST->getMemoryVT();
8938   } else
8939     return false;
8940
8941   TargetLowering::AddrMode AM;
8942   if (N->getOpcode() == ISD::ADD) {
8943     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8944     if (Offset)
8945       // [reg +/- imm]
8946       AM.BaseOffs = Offset->getSExtValue();
8947     else
8948       // [reg +/- reg]
8949       AM.Scale = 1;
8950   } else if (N->getOpcode() == ISD::SUB) {
8951     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8952     if (Offset)
8953       // [reg +/- imm]
8954       AM.BaseOffs = -Offset->getSExtValue();
8955     else
8956       // [reg +/- reg]
8957       AM.Scale = 1;
8958   } else
8959     return false;
8960
8961   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8962 }
8963
8964 /// Try turning a load/store into a pre-indexed load/store when the base
8965 /// pointer is an add or subtract and it has other uses besides the load/store.
8966 /// After the transformation, the new indexed load/store has effectively folded
8967 /// the add/subtract in and all of its other uses are redirected to the
8968 /// new load/store.
8969 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8970   if (Level < AfterLegalizeDAG)
8971     return false;
8972
8973   bool isLoad = true;
8974   SDValue Ptr;
8975   EVT VT;
8976   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8977     if (LD->isIndexed())
8978       return false;
8979     VT = LD->getMemoryVT();
8980     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8981         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8982       return false;
8983     Ptr = LD->getBasePtr();
8984   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8985     if (ST->isIndexed())
8986       return false;
8987     VT = ST->getMemoryVT();
8988     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8989         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8990       return false;
8991     Ptr = ST->getBasePtr();
8992     isLoad = false;
8993   } else {
8994     return false;
8995   }
8996
8997   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8998   // out.  There is no reason to make this a preinc/predec.
8999   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
9000       Ptr.getNode()->hasOneUse())
9001     return false;
9002
9003   // Ask the target to do addressing mode selection.
9004   SDValue BasePtr;
9005   SDValue Offset;
9006   ISD::MemIndexedMode AM = ISD::UNINDEXED;
9007   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
9008     return false;
9009
9010   // Backends without true r+i pre-indexed forms may need to pass a
9011   // constant base with a variable offset so that constant coercion
9012   // will work with the patterns in canonical form.
9013   bool Swapped = false;
9014   if (isa<ConstantSDNode>(BasePtr)) {
9015     std::swap(BasePtr, Offset);
9016     Swapped = true;
9017   }
9018
9019   // Don't create a indexed load / store with zero offset.
9020   if (isa<ConstantSDNode>(Offset) &&
9021       cast<ConstantSDNode>(Offset)->isNullValue())
9022     return false;
9023
9024   // Try turning it into a pre-indexed load / store except when:
9025   // 1) The new base ptr is a frame index.
9026   // 2) If N is a store and the new base ptr is either the same as or is a
9027   //    predecessor of the value being stored.
9028   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9029   //    that would create a cycle.
9030   // 4) All uses are load / store ops that use it as old base ptr.
9031
9032   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9033   // (plus the implicit offset) to a register to preinc anyway.
9034   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9035     return false;
9036
9037   // Check #2.
9038   if (!isLoad) {
9039     SDValue Val = cast<StoreSDNode>(N)->getValue();
9040     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9041       return false;
9042   }
9043
9044   // If the offset is a constant, there may be other adds of constants that
9045   // can be folded with this one. We should do this to avoid having to keep
9046   // a copy of the original base pointer.
9047   SmallVector<SDNode *, 16> OtherUses;
9048   if (isa<ConstantSDNode>(Offset))
9049     for (SDNode *Use : BasePtr.getNode()->uses()) {
9050       if (Use == Ptr.getNode())
9051         continue;
9052
9053       if (Use->isPredecessorOf(N))
9054         continue;
9055
9056       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9057         OtherUses.clear();
9058         break;
9059       }
9060
9061       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9062       if (Op1.getNode() == BasePtr.getNode())
9063         std::swap(Op0, Op1);
9064       assert(Op0.getNode() == BasePtr.getNode() &&
9065              "Use of ADD/SUB but not an operand");
9066
9067       if (!isa<ConstantSDNode>(Op1)) {
9068         OtherUses.clear();
9069         break;
9070       }
9071
9072       // FIXME: In some cases, we can be smarter about this.
9073       if (Op1.getValueType() != Offset.getValueType()) {
9074         OtherUses.clear();
9075         break;
9076       }
9077
9078       OtherUses.push_back(Use);
9079     }
9080
9081   if (Swapped)
9082     std::swap(BasePtr, Offset);
9083
9084   // Now check for #3 and #4.
9085   bool RealUse = false;
9086
9087   // Caches for hasPredecessorHelper
9088   SmallPtrSet<const SDNode *, 32> Visited;
9089   SmallVector<const SDNode *, 16> Worklist;
9090
9091   for (SDNode *Use : Ptr.getNode()->uses()) {
9092     if (Use == N)
9093       continue;
9094     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9095       return false;
9096
9097     // If Ptr may be folded in addressing mode of other use, then it's
9098     // not profitable to do this transformation.
9099     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9100       RealUse = true;
9101   }
9102
9103   if (!RealUse)
9104     return false;
9105
9106   SDValue Result;
9107   if (isLoad)
9108     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9109                                 BasePtr, Offset, AM);
9110   else
9111     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9112                                  BasePtr, Offset, AM);
9113   ++PreIndexedNodes;
9114   ++NodesCombined;
9115   DEBUG(dbgs() << "\nReplacing.4 ";
9116         N->dump(&DAG);
9117         dbgs() << "\nWith: ";
9118         Result.getNode()->dump(&DAG);
9119         dbgs() << '\n');
9120   WorklistRemover DeadNodes(*this);
9121   if (isLoad) {
9122     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9123     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9124   } else {
9125     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9126   }
9127
9128   // Finally, since the node is now dead, remove it from the graph.
9129   deleteAndRecombine(N);
9130
9131   if (Swapped)
9132     std::swap(BasePtr, Offset);
9133
9134   // Replace other uses of BasePtr that can be updated to use Ptr
9135   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9136     unsigned OffsetIdx = 1;
9137     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9138       OffsetIdx = 0;
9139     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9140            BasePtr.getNode() && "Expected BasePtr operand");
9141
9142     // We need to replace ptr0 in the following expression:
9143     //   x0 * offset0 + y0 * ptr0 = t0
9144     // knowing that
9145     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9146     //
9147     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9148     // indexed load/store and the expresion that needs to be re-written.
9149     //
9150     // Therefore, we have:
9151     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9152
9153     ConstantSDNode *CN =
9154       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9155     int X0, X1, Y0, Y1;
9156     APInt Offset0 = CN->getAPIntValue();
9157     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9158
9159     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9160     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9161     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9162     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9163
9164     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9165
9166     APInt CNV = Offset0;
9167     if (X0 < 0) CNV = -CNV;
9168     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9169     else CNV = CNV - Offset1;
9170
9171     SDLoc DL(OtherUses[i]);
9172
9173     // We can now generate the new expression.
9174     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9175     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9176
9177     SDValue NewUse = DAG.getNode(Opcode,
9178                                  DL,
9179                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9180     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9181     deleteAndRecombine(OtherUses[i]);
9182   }
9183
9184   // Replace the uses of Ptr with uses of the updated base value.
9185   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9186   deleteAndRecombine(Ptr.getNode());
9187
9188   return true;
9189 }
9190
9191 /// Try to combine a load/store with a add/sub of the base pointer node into a
9192 /// post-indexed load/store. The transformation folded the add/subtract into the
9193 /// new indexed load/store effectively and all of its uses are redirected to the
9194 /// new load/store.
9195 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9196   if (Level < AfterLegalizeDAG)
9197     return false;
9198
9199   bool isLoad = true;
9200   SDValue Ptr;
9201   EVT VT;
9202   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9203     if (LD->isIndexed())
9204       return false;
9205     VT = LD->getMemoryVT();
9206     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9207         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9208       return false;
9209     Ptr = LD->getBasePtr();
9210   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9211     if (ST->isIndexed())
9212       return false;
9213     VT = ST->getMemoryVT();
9214     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9215         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9216       return false;
9217     Ptr = ST->getBasePtr();
9218     isLoad = false;
9219   } else {
9220     return false;
9221   }
9222
9223   if (Ptr.getNode()->hasOneUse())
9224     return false;
9225
9226   for (SDNode *Op : Ptr.getNode()->uses()) {
9227     if (Op == N ||
9228         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9229       continue;
9230
9231     SDValue BasePtr;
9232     SDValue Offset;
9233     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9234     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9235       // Don't create a indexed load / store with zero offset.
9236       if (isa<ConstantSDNode>(Offset) &&
9237           cast<ConstantSDNode>(Offset)->isNullValue())
9238         continue;
9239
9240       // Try turning it into a post-indexed load / store except when
9241       // 1) All uses are load / store ops that use it as base ptr (and
9242       //    it may be folded as addressing mmode).
9243       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9244       //    nor a successor of N. Otherwise, if Op is folded that would
9245       //    create a cycle.
9246
9247       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9248         continue;
9249
9250       // Check for #1.
9251       bool TryNext = false;
9252       for (SDNode *Use : BasePtr.getNode()->uses()) {
9253         if (Use == Ptr.getNode())
9254           continue;
9255
9256         // If all the uses are load / store addresses, then don't do the
9257         // transformation.
9258         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9259           bool RealUse = false;
9260           for (SDNode *UseUse : Use->uses()) {
9261             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9262               RealUse = true;
9263           }
9264
9265           if (!RealUse) {
9266             TryNext = true;
9267             break;
9268           }
9269         }
9270       }
9271
9272       if (TryNext)
9273         continue;
9274
9275       // Check for #2
9276       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9277         SDValue Result = isLoad
9278           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9279                                BasePtr, Offset, AM)
9280           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9281                                 BasePtr, Offset, AM);
9282         ++PostIndexedNodes;
9283         ++NodesCombined;
9284         DEBUG(dbgs() << "\nReplacing.5 ";
9285               N->dump(&DAG);
9286               dbgs() << "\nWith: ";
9287               Result.getNode()->dump(&DAG);
9288               dbgs() << '\n');
9289         WorklistRemover DeadNodes(*this);
9290         if (isLoad) {
9291           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9292           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9293         } else {
9294           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9295         }
9296
9297         // Finally, since the node is now dead, remove it from the graph.
9298         deleteAndRecombine(N);
9299
9300         // Replace the uses of Use with uses of the updated base value.
9301         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9302                                       Result.getValue(isLoad ? 1 : 0));
9303         deleteAndRecombine(Op);
9304         return true;
9305       }
9306     }
9307   }
9308
9309   return false;
9310 }
9311
9312 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9313 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9314   ISD::MemIndexedMode AM = LD->getAddressingMode();
9315   assert(AM != ISD::UNINDEXED);
9316   SDValue BP = LD->getOperand(1);
9317   SDValue Inc = LD->getOperand(2);
9318
9319   // Some backends use TargetConstants for load offsets, but don't expect
9320   // TargetConstants in general ADD nodes. We can convert these constants into
9321   // regular Constants (if the constant is not opaque).
9322   assert((Inc.getOpcode() != ISD::TargetConstant ||
9323           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9324          "Cannot split out indexing using opaque target constants");
9325   if (Inc.getOpcode() == ISD::TargetConstant) {
9326     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9327     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9328                           ConstInc->getValueType(0));
9329   }
9330
9331   unsigned Opc =
9332       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9333   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9334 }
9335
9336 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9337   LoadSDNode *LD  = cast<LoadSDNode>(N);
9338   SDValue Chain = LD->getChain();
9339   SDValue Ptr   = LD->getBasePtr();
9340
9341   // If load is not volatile and there are no uses of the loaded value (and
9342   // the updated indexed value in case of indexed loads), change uses of the
9343   // chain value into uses of the chain input (i.e. delete the dead load).
9344   if (!LD->isVolatile()) {
9345     if (N->getValueType(1) == MVT::Other) {
9346       // Unindexed loads.
9347       if (!N->hasAnyUseOfValue(0)) {
9348         // It's not safe to use the two value CombineTo variant here. e.g.
9349         // v1, chain2 = load chain1, loc
9350         // v2, chain3 = load chain2, loc
9351         // v3         = add v2, c
9352         // Now we replace use of chain2 with chain1.  This makes the second load
9353         // isomorphic to the one we are deleting, and thus makes this load live.
9354         DEBUG(dbgs() << "\nReplacing.6 ";
9355               N->dump(&DAG);
9356               dbgs() << "\nWith chain: ";
9357               Chain.getNode()->dump(&DAG);
9358               dbgs() << "\n");
9359         WorklistRemover DeadNodes(*this);
9360         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9361
9362         if (N->use_empty())
9363           deleteAndRecombine(N);
9364
9365         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9366       }
9367     } else {
9368       // Indexed loads.
9369       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9370
9371       // If this load has an opaque TargetConstant offset, then we cannot split
9372       // the indexing into an add/sub directly (that TargetConstant may not be
9373       // valid for a different type of node, and we cannot convert an opaque
9374       // target constant into a regular constant).
9375       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9376                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9377
9378       if (!N->hasAnyUseOfValue(0) &&
9379           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9380         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9381         SDValue Index;
9382         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9383           Index = SplitIndexingFromLoad(LD);
9384           // Try to fold the base pointer arithmetic into subsequent loads and
9385           // stores.
9386           AddUsersToWorklist(N);
9387         } else
9388           Index = DAG.getUNDEF(N->getValueType(1));
9389         DEBUG(dbgs() << "\nReplacing.7 ";
9390               N->dump(&DAG);
9391               dbgs() << "\nWith: ";
9392               Undef.getNode()->dump(&DAG);
9393               dbgs() << " and 2 other values\n");
9394         WorklistRemover DeadNodes(*this);
9395         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9396         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9397         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9398         deleteAndRecombine(N);
9399         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9400       }
9401     }
9402   }
9403
9404   // If this load is directly stored, replace the load value with the stored
9405   // value.
9406   // TODO: Handle store large -> read small portion.
9407   // TODO: Handle TRUNCSTORE/LOADEXT
9408   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9409     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9410       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9411       if (PrevST->getBasePtr() == Ptr &&
9412           PrevST->getValue().getValueType() == N->getValueType(0))
9413       return CombineTo(N, Chain.getOperand(1), Chain);
9414     }
9415   }
9416
9417   // Try to infer better alignment information than the load already has.
9418   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9419     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9420       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9421         SDValue NewLoad =
9422                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9423                               LD->getValueType(0),
9424                               Chain, Ptr, LD->getPointerInfo(),
9425                               LD->getMemoryVT(),
9426                               LD->isVolatile(), LD->isNonTemporal(),
9427                               LD->isInvariant(), Align, LD->getAAInfo());
9428         if (NewLoad.getNode() != N)
9429           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9430       }
9431     }
9432   }
9433
9434   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9435                                                   : DAG.getSubtarget().useAA();
9436 #ifndef NDEBUG
9437   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9438       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9439     UseAA = false;
9440 #endif
9441   if (UseAA && LD->isUnindexed()) {
9442     // Walk up chain skipping non-aliasing memory nodes.
9443     SDValue BetterChain = FindBetterChain(N, Chain);
9444
9445     // If there is a better chain.
9446     if (Chain != BetterChain) {
9447       SDValue ReplLoad;
9448
9449       // Replace the chain to void dependency.
9450       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9451         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9452                                BetterChain, Ptr, LD->getMemOperand());
9453       } else {
9454         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9455                                   LD->getValueType(0),
9456                                   BetterChain, Ptr, LD->getMemoryVT(),
9457                                   LD->getMemOperand());
9458       }
9459
9460       // Create token factor to keep old chain connected.
9461       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9462                                   MVT::Other, Chain, ReplLoad.getValue(1));
9463
9464       // Make sure the new and old chains are cleaned up.
9465       AddToWorklist(Token.getNode());
9466
9467       // Replace uses with load result and token factor. Don't add users
9468       // to work list.
9469       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9470     }
9471   }
9472
9473   // Try transforming N to an indexed load.
9474   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9475     return SDValue(N, 0);
9476
9477   // Try to slice up N to more direct loads if the slices are mapped to
9478   // different register banks or pairing can take place.
9479   if (SliceUpLoad(N))
9480     return SDValue(N, 0);
9481
9482   return SDValue();
9483 }
9484
9485 namespace {
9486 /// \brief Helper structure used to slice a load in smaller loads.
9487 /// Basically a slice is obtained from the following sequence:
9488 /// Origin = load Ty1, Base
9489 /// Shift = srl Ty1 Origin, CstTy Amount
9490 /// Inst = trunc Shift to Ty2
9491 ///
9492 /// Then, it will be rewriten into:
9493 /// Slice = load SliceTy, Base + SliceOffset
9494 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9495 ///
9496 /// SliceTy is deduced from the number of bits that are actually used to
9497 /// build Inst.
9498 struct LoadedSlice {
9499   /// \brief Helper structure used to compute the cost of a slice.
9500   struct Cost {
9501     /// Are we optimizing for code size.
9502     bool ForCodeSize;
9503     /// Various cost.
9504     unsigned Loads;
9505     unsigned Truncates;
9506     unsigned CrossRegisterBanksCopies;
9507     unsigned ZExts;
9508     unsigned Shift;
9509
9510     Cost(bool ForCodeSize = false)
9511         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9512           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9513
9514     /// \brief Get the cost of one isolated slice.
9515     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9516         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9517           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9518       EVT TruncType = LS.Inst->getValueType(0);
9519       EVT LoadedType = LS.getLoadedType();
9520       if (TruncType != LoadedType &&
9521           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9522         ZExts = 1;
9523     }
9524
9525     /// \brief Account for slicing gain in the current cost.
9526     /// Slicing provide a few gains like removing a shift or a
9527     /// truncate. This method allows to grow the cost of the original
9528     /// load with the gain from this slice.
9529     void addSliceGain(const LoadedSlice &LS) {
9530       // Each slice saves a truncate.
9531       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9532       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9533                               LS.Inst->getOperand(0).getValueType()))
9534         ++Truncates;
9535       // If there is a shift amount, this slice gets rid of it.
9536       if (LS.Shift)
9537         ++Shift;
9538       // If this slice can merge a cross register bank copy, account for it.
9539       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9540         ++CrossRegisterBanksCopies;
9541     }
9542
9543     Cost &operator+=(const Cost &RHS) {
9544       Loads += RHS.Loads;
9545       Truncates += RHS.Truncates;
9546       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9547       ZExts += RHS.ZExts;
9548       Shift += RHS.Shift;
9549       return *this;
9550     }
9551
9552     bool operator==(const Cost &RHS) const {
9553       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9554              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9555              ZExts == RHS.ZExts && Shift == RHS.Shift;
9556     }
9557
9558     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9559
9560     bool operator<(const Cost &RHS) const {
9561       // Assume cross register banks copies are as expensive as loads.
9562       // FIXME: Do we want some more target hooks?
9563       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9564       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9565       // Unless we are optimizing for code size, consider the
9566       // expensive operation first.
9567       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9568         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9569       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9570              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9571     }
9572
9573     bool operator>(const Cost &RHS) const { return RHS < *this; }
9574
9575     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9576
9577     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9578   };
9579   // The last instruction that represent the slice. This should be a
9580   // truncate instruction.
9581   SDNode *Inst;
9582   // The original load instruction.
9583   LoadSDNode *Origin;
9584   // The right shift amount in bits from the original load.
9585   unsigned Shift;
9586   // The DAG from which Origin came from.
9587   // This is used to get some contextual information about legal types, etc.
9588   SelectionDAG *DAG;
9589
9590   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9591               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9592       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9593
9594   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9595   /// \return Result is \p BitWidth and has used bits set to 1 and
9596   ///         not used bits set to 0.
9597   APInt getUsedBits() const {
9598     // Reproduce the trunc(lshr) sequence:
9599     // - Start from the truncated value.
9600     // - Zero extend to the desired bit width.
9601     // - Shift left.
9602     assert(Origin && "No original load to compare against.");
9603     unsigned BitWidth = Origin->getValueSizeInBits(0);
9604     assert(Inst && "This slice is not bound to an instruction");
9605     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9606            "Extracted slice is bigger than the whole type!");
9607     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9608     UsedBits.setAllBits();
9609     UsedBits = UsedBits.zext(BitWidth);
9610     UsedBits <<= Shift;
9611     return UsedBits;
9612   }
9613
9614   /// \brief Get the size of the slice to be loaded in bytes.
9615   unsigned getLoadedSize() const {
9616     unsigned SliceSize = getUsedBits().countPopulation();
9617     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9618     return SliceSize / 8;
9619   }
9620
9621   /// \brief Get the type that will be loaded for this slice.
9622   /// Note: This may not be the final type for the slice.
9623   EVT getLoadedType() const {
9624     assert(DAG && "Missing context");
9625     LLVMContext &Ctxt = *DAG->getContext();
9626     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9627   }
9628
9629   /// \brief Get the alignment of the load used for this slice.
9630   unsigned getAlignment() const {
9631     unsigned Alignment = Origin->getAlignment();
9632     unsigned Offset = getOffsetFromBase();
9633     if (Offset != 0)
9634       Alignment = MinAlign(Alignment, Alignment + Offset);
9635     return Alignment;
9636   }
9637
9638   /// \brief Check if this slice can be rewritten with legal operations.
9639   bool isLegal() const {
9640     // An invalid slice is not legal.
9641     if (!Origin || !Inst || !DAG)
9642       return false;
9643
9644     // Offsets are for indexed load only, we do not handle that.
9645     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9646       return false;
9647
9648     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9649
9650     // Check that the type is legal.
9651     EVT SliceType = getLoadedType();
9652     if (!TLI.isTypeLegal(SliceType))
9653       return false;
9654
9655     // Check that the load is legal for this type.
9656     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9657       return false;
9658
9659     // Check that the offset can be computed.
9660     // 1. Check its type.
9661     EVT PtrType = Origin->getBasePtr().getValueType();
9662     if (PtrType == MVT::Untyped || PtrType.isExtended())
9663       return false;
9664
9665     // 2. Check that it fits in the immediate.
9666     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9667       return false;
9668
9669     // 3. Check that the computation is legal.
9670     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9671       return false;
9672
9673     // Check that the zext is legal if it needs one.
9674     EVT TruncateType = Inst->getValueType(0);
9675     if (TruncateType != SliceType &&
9676         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9677       return false;
9678
9679     return true;
9680   }
9681
9682   /// \brief Get the offset in bytes of this slice in the original chunk of
9683   /// bits.
9684   /// \pre DAG != nullptr.
9685   uint64_t getOffsetFromBase() const {
9686     assert(DAG && "Missing context.");
9687     bool IsBigEndian =
9688         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9689     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9690     uint64_t Offset = Shift / 8;
9691     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9692     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9693            "The size of the original loaded type is not a multiple of a"
9694            " byte.");
9695     // If Offset is bigger than TySizeInBytes, it means we are loading all
9696     // zeros. This should have been optimized before in the process.
9697     assert(TySizeInBytes > Offset &&
9698            "Invalid shift amount for given loaded size");
9699     if (IsBigEndian)
9700       Offset = TySizeInBytes - Offset - getLoadedSize();
9701     return Offset;
9702   }
9703
9704   /// \brief Generate the sequence of instructions to load the slice
9705   /// represented by this object and redirect the uses of this slice to
9706   /// this new sequence of instructions.
9707   /// \pre this->Inst && this->Origin are valid Instructions and this
9708   /// object passed the legal check: LoadedSlice::isLegal returned true.
9709   /// \return The last instruction of the sequence used to load the slice.
9710   SDValue loadSlice() const {
9711     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9712     const SDValue &OldBaseAddr = Origin->getBasePtr();
9713     SDValue BaseAddr = OldBaseAddr;
9714     // Get the offset in that chunk of bytes w.r.t. the endianess.
9715     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9716     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9717     if (Offset) {
9718       // BaseAddr = BaseAddr + Offset.
9719       EVT ArithType = BaseAddr.getValueType();
9720       SDLoc DL(Origin);
9721       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9722                               DAG->getConstant(Offset, DL, ArithType));
9723     }
9724
9725     // Create the type of the loaded slice according to its size.
9726     EVT SliceType = getLoadedType();
9727
9728     // Create the load for the slice.
9729     SDValue LastInst = DAG->getLoad(
9730         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9731         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9732         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9733     // If the final type is not the same as the loaded type, this means that
9734     // we have to pad with zero. Create a zero extend for that.
9735     EVT FinalType = Inst->getValueType(0);
9736     if (SliceType != FinalType)
9737       LastInst =
9738           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9739     return LastInst;
9740   }
9741
9742   /// \brief Check if this slice can be merged with an expensive cross register
9743   /// bank copy. E.g.,
9744   /// i = load i32
9745   /// f = bitcast i32 i to float
9746   bool canMergeExpensiveCrossRegisterBankCopy() const {
9747     if (!Inst || !Inst->hasOneUse())
9748       return false;
9749     SDNode *Use = *Inst->use_begin();
9750     if (Use->getOpcode() != ISD::BITCAST)
9751       return false;
9752     assert(DAG && "Missing context");
9753     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9754     EVT ResVT = Use->getValueType(0);
9755     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9756     const TargetRegisterClass *ArgRC =
9757         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9758     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9759       return false;
9760
9761     // At this point, we know that we perform a cross-register-bank copy.
9762     // Check if it is expensive.
9763     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9764     // Assume bitcasts are cheap, unless both register classes do not
9765     // explicitly share a common sub class.
9766     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9767       return false;
9768
9769     // Check if it will be merged with the load.
9770     // 1. Check the alignment constraint.
9771     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9772         ResVT.getTypeForEVT(*DAG->getContext()));
9773
9774     if (RequiredAlignment > getAlignment())
9775       return false;
9776
9777     // 2. Check that the load is a legal operation for that type.
9778     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9779       return false;
9780
9781     // 3. Check that we do not have a zext in the way.
9782     if (Inst->getValueType(0) != getLoadedType())
9783       return false;
9784
9785     return true;
9786   }
9787 };
9788 }
9789
9790 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9791 /// \p UsedBits looks like 0..0 1..1 0..0.
9792 static bool areUsedBitsDense(const APInt &UsedBits) {
9793   // If all the bits are one, this is dense!
9794   if (UsedBits.isAllOnesValue())
9795     return true;
9796
9797   // Get rid of the unused bits on the right.
9798   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9799   // Get rid of the unused bits on the left.
9800   if (NarrowedUsedBits.countLeadingZeros())
9801     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9802   // Check that the chunk of bits is completely used.
9803   return NarrowedUsedBits.isAllOnesValue();
9804 }
9805
9806 /// \brief Check whether or not \p First and \p Second are next to each other
9807 /// in memory. This means that there is no hole between the bits loaded
9808 /// by \p First and the bits loaded by \p Second.
9809 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9810                                      const LoadedSlice &Second) {
9811   assert(First.Origin == Second.Origin && First.Origin &&
9812          "Unable to match different memory origins.");
9813   APInt UsedBits = First.getUsedBits();
9814   assert((UsedBits & Second.getUsedBits()) == 0 &&
9815          "Slices are not supposed to overlap.");
9816   UsedBits |= Second.getUsedBits();
9817   return areUsedBitsDense(UsedBits);
9818 }
9819
9820 /// \brief Adjust the \p GlobalLSCost according to the target
9821 /// paring capabilities and the layout of the slices.
9822 /// \pre \p GlobalLSCost should account for at least as many loads as
9823 /// there is in the slices in \p LoadedSlices.
9824 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9825                                  LoadedSlice::Cost &GlobalLSCost) {
9826   unsigned NumberOfSlices = LoadedSlices.size();
9827   // If there is less than 2 elements, no pairing is possible.
9828   if (NumberOfSlices < 2)
9829     return;
9830
9831   // Sort the slices so that elements that are likely to be next to each
9832   // other in memory are next to each other in the list.
9833   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9834             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9835     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9836     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9837   });
9838   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9839   // First (resp. Second) is the first (resp. Second) potentially candidate
9840   // to be placed in a paired load.
9841   const LoadedSlice *First = nullptr;
9842   const LoadedSlice *Second = nullptr;
9843   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9844                 // Set the beginning of the pair.
9845                                                            First = Second) {
9846
9847     Second = &LoadedSlices[CurrSlice];
9848
9849     // If First is NULL, it means we start a new pair.
9850     // Get to the next slice.
9851     if (!First)
9852       continue;
9853
9854     EVT LoadedType = First->getLoadedType();
9855
9856     // If the types of the slices are different, we cannot pair them.
9857     if (LoadedType != Second->getLoadedType())
9858       continue;
9859
9860     // Check if the target supplies paired loads for this type.
9861     unsigned RequiredAlignment = 0;
9862     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9863       // move to the next pair, this type is hopeless.
9864       Second = nullptr;
9865       continue;
9866     }
9867     // Check if we meet the alignment requirement.
9868     if (RequiredAlignment > First->getAlignment())
9869       continue;
9870
9871     // Check that both loads are next to each other in memory.
9872     if (!areSlicesNextToEachOther(*First, *Second))
9873       continue;
9874
9875     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9876     --GlobalLSCost.Loads;
9877     // Move to the next pair.
9878     Second = nullptr;
9879   }
9880 }
9881
9882 /// \brief Check the profitability of all involved LoadedSlice.
9883 /// Currently, it is considered profitable if there is exactly two
9884 /// involved slices (1) which are (2) next to each other in memory, and
9885 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9886 ///
9887 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9888 /// the elements themselves.
9889 ///
9890 /// FIXME: When the cost model will be mature enough, we can relax
9891 /// constraints (1) and (2).
9892 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9893                                 const APInt &UsedBits, bool ForCodeSize) {
9894   unsigned NumberOfSlices = LoadedSlices.size();
9895   if (StressLoadSlicing)
9896     return NumberOfSlices > 1;
9897
9898   // Check (1).
9899   if (NumberOfSlices != 2)
9900     return false;
9901
9902   // Check (2).
9903   if (!areUsedBitsDense(UsedBits))
9904     return false;
9905
9906   // Check (3).
9907   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9908   // The original code has one big load.
9909   OrigCost.Loads = 1;
9910   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9911     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9912     // Accumulate the cost of all the slices.
9913     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9914     GlobalSlicingCost += SliceCost;
9915
9916     // Account as cost in the original configuration the gain obtained
9917     // with the current slices.
9918     OrigCost.addSliceGain(LS);
9919   }
9920
9921   // If the target supports paired load, adjust the cost accordingly.
9922   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9923   return OrigCost > GlobalSlicingCost;
9924 }
9925
9926 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9927 /// operations, split it in the various pieces being extracted.
9928 ///
9929 /// This sort of thing is introduced by SROA.
9930 /// This slicing takes care not to insert overlapping loads.
9931 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9932 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9933   if (Level < AfterLegalizeDAG)
9934     return false;
9935
9936   LoadSDNode *LD = cast<LoadSDNode>(N);
9937   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9938       !LD->getValueType(0).isInteger())
9939     return false;
9940
9941   // Keep track of already used bits to detect overlapping values.
9942   // In that case, we will just abort the transformation.
9943   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9944
9945   SmallVector<LoadedSlice, 4> LoadedSlices;
9946
9947   // Check if this load is used as several smaller chunks of bits.
9948   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9949   // of computation for each trunc.
9950   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9951        UI != UIEnd; ++UI) {
9952     // Skip the uses of the chain.
9953     if (UI.getUse().getResNo() != 0)
9954       continue;
9955
9956     SDNode *User = *UI;
9957     unsigned Shift = 0;
9958
9959     // Check if this is a trunc(lshr).
9960     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9961         isa<ConstantSDNode>(User->getOperand(1))) {
9962       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9963       User = *User->use_begin();
9964     }
9965
9966     // At this point, User is a Truncate, iff we encountered, trunc or
9967     // trunc(lshr).
9968     if (User->getOpcode() != ISD::TRUNCATE)
9969       return false;
9970
9971     // The width of the type must be a power of 2 and greater than 8-bits.
9972     // Otherwise the load cannot be represented in LLVM IR.
9973     // Moreover, if we shifted with a non-8-bits multiple, the slice
9974     // will be across several bytes. We do not support that.
9975     unsigned Width = User->getValueSizeInBits(0);
9976     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9977       return 0;
9978
9979     // Build the slice for this chain of computations.
9980     LoadedSlice LS(User, LD, Shift, &DAG);
9981     APInt CurrentUsedBits = LS.getUsedBits();
9982
9983     // Check if this slice overlaps with another.
9984     if ((CurrentUsedBits & UsedBits) != 0)
9985       return false;
9986     // Update the bits used globally.
9987     UsedBits |= CurrentUsedBits;
9988
9989     // Check if the new slice would be legal.
9990     if (!LS.isLegal())
9991       return false;
9992
9993     // Record the slice.
9994     LoadedSlices.push_back(LS);
9995   }
9996
9997   // Abort slicing if it does not seem to be profitable.
9998   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9999     return false;
10000
10001   ++SlicedLoads;
10002
10003   // Rewrite each chain to use an independent load.
10004   // By construction, each chain can be represented by a unique load.
10005
10006   // Prepare the argument for the new token factor for all the slices.
10007   SmallVector<SDValue, 8> ArgChains;
10008   for (SmallVectorImpl<LoadedSlice>::const_iterator
10009            LSIt = LoadedSlices.begin(),
10010            LSItEnd = LoadedSlices.end();
10011        LSIt != LSItEnd; ++LSIt) {
10012     SDValue SliceInst = LSIt->loadSlice();
10013     CombineTo(LSIt->Inst, SliceInst, true);
10014     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10015       SliceInst = SliceInst.getOperand(0);
10016     assert(SliceInst->getOpcode() == ISD::LOAD &&
10017            "It takes more than a zext to get to the loaded slice!!");
10018     ArgChains.push_back(SliceInst.getValue(1));
10019   }
10020
10021   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10022                               ArgChains);
10023   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10024   return true;
10025 }
10026
10027 /// Check to see if V is (and load (ptr), imm), where the load is having
10028 /// specific bytes cleared out.  If so, return the byte size being masked out
10029 /// and the shift amount.
10030 static std::pair<unsigned, unsigned>
10031 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10032   std::pair<unsigned, unsigned> Result(0, 0);
10033
10034   // Check for the structure we're looking for.
10035   if (V->getOpcode() != ISD::AND ||
10036       !isa<ConstantSDNode>(V->getOperand(1)) ||
10037       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10038     return Result;
10039
10040   // Check the chain and pointer.
10041   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10042   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10043
10044   // The store should be chained directly to the load or be an operand of a
10045   // tokenfactor.
10046   if (LD == Chain.getNode())
10047     ; // ok.
10048   else if (Chain->getOpcode() != ISD::TokenFactor)
10049     return Result; // Fail.
10050   else {
10051     bool isOk = false;
10052     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10053       if (Chain->getOperand(i).getNode() == LD) {
10054         isOk = true;
10055         break;
10056       }
10057     if (!isOk) return Result;
10058   }
10059
10060   // This only handles simple types.
10061   if (V.getValueType() != MVT::i16 &&
10062       V.getValueType() != MVT::i32 &&
10063       V.getValueType() != MVT::i64)
10064     return Result;
10065
10066   // Check the constant mask.  Invert it so that the bits being masked out are
10067   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10068   // follow the sign bit for uniformity.
10069   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10070   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10071   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10072   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10073   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10074   if (NotMaskLZ == 64) return Result;  // All zero mask.
10075
10076   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10077   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10078     return Result;
10079
10080   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10081   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10082     NotMaskLZ -= 64-V.getValueSizeInBits();
10083
10084   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10085   switch (MaskedBytes) {
10086   case 1:
10087   case 2:
10088   case 4: break;
10089   default: return Result; // All one mask, or 5-byte mask.
10090   }
10091
10092   // Verify that the first bit starts at a multiple of mask so that the access
10093   // is aligned the same as the access width.
10094   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10095
10096   Result.first = MaskedBytes;
10097   Result.second = NotMaskTZ/8;
10098   return Result;
10099 }
10100
10101
10102 /// Check to see if IVal is something that provides a value as specified by
10103 /// MaskInfo. If so, replace the specified store with a narrower store of
10104 /// truncated IVal.
10105 static SDNode *
10106 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10107                                 SDValue IVal, StoreSDNode *St,
10108                                 DAGCombiner *DC) {
10109   unsigned NumBytes = MaskInfo.first;
10110   unsigned ByteShift = MaskInfo.second;
10111   SelectionDAG &DAG = DC->getDAG();
10112
10113   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10114   // that uses this.  If not, this is not a replacement.
10115   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10116                                   ByteShift*8, (ByteShift+NumBytes)*8);
10117   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10118
10119   // Check that it is legal on the target to do this.  It is legal if the new
10120   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10121   // legalization.
10122   MVT VT = MVT::getIntegerVT(NumBytes*8);
10123   if (!DC->isTypeLegal(VT))
10124     return nullptr;
10125
10126   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10127   // shifted by ByteShift and truncated down to NumBytes.
10128   if (ByteShift) {
10129     SDLoc DL(IVal);
10130     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10131                        DAG.getConstant(ByteShift*8, DL,
10132                                     DC->getShiftAmountTy(IVal.getValueType())));
10133   }
10134
10135   // Figure out the offset for the store and the alignment of the access.
10136   unsigned StOffset;
10137   unsigned NewAlign = St->getAlignment();
10138
10139   if (DAG.getTargetLoweringInfo().isLittleEndian())
10140     StOffset = ByteShift;
10141   else
10142     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10143
10144   SDValue Ptr = St->getBasePtr();
10145   if (StOffset) {
10146     SDLoc DL(IVal);
10147     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10148                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10149     NewAlign = MinAlign(NewAlign, StOffset);
10150   }
10151
10152   // Truncate down to the new size.
10153   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10154
10155   ++OpsNarrowed;
10156   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10157                       St->getPointerInfo().getWithOffset(StOffset),
10158                       false, false, NewAlign).getNode();
10159 }
10160
10161
10162 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10163 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10164 /// narrowing the load and store if it would end up being a win for performance
10165 /// or code size.
10166 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10167   StoreSDNode *ST  = cast<StoreSDNode>(N);
10168   if (ST->isVolatile())
10169     return SDValue();
10170
10171   SDValue Chain = ST->getChain();
10172   SDValue Value = ST->getValue();
10173   SDValue Ptr   = ST->getBasePtr();
10174   EVT VT = Value.getValueType();
10175
10176   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10177     return SDValue();
10178
10179   unsigned Opc = Value.getOpcode();
10180
10181   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10182   // is a byte mask indicating a consecutive number of bytes, check to see if
10183   // Y is known to provide just those bytes.  If so, we try to replace the
10184   // load + replace + store sequence with a single (narrower) store, which makes
10185   // the load dead.
10186   if (Opc == ISD::OR) {
10187     std::pair<unsigned, unsigned> MaskedLoad;
10188     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10189     if (MaskedLoad.first)
10190       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10191                                                   Value.getOperand(1), ST,this))
10192         return SDValue(NewST, 0);
10193
10194     // Or is commutative, so try swapping X and Y.
10195     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10196     if (MaskedLoad.first)
10197       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10198                                                   Value.getOperand(0), ST,this))
10199         return SDValue(NewST, 0);
10200   }
10201
10202   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10203       Value.getOperand(1).getOpcode() != ISD::Constant)
10204     return SDValue();
10205
10206   SDValue N0 = Value.getOperand(0);
10207   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10208       Chain == SDValue(N0.getNode(), 1)) {
10209     LoadSDNode *LD = cast<LoadSDNode>(N0);
10210     if (LD->getBasePtr() != Ptr ||
10211         LD->getPointerInfo().getAddrSpace() !=
10212         ST->getPointerInfo().getAddrSpace())
10213       return SDValue();
10214
10215     // Find the type to narrow it the load / op / store to.
10216     SDValue N1 = Value.getOperand(1);
10217     unsigned BitWidth = N1.getValueSizeInBits();
10218     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10219     if (Opc == ISD::AND)
10220       Imm ^= APInt::getAllOnesValue(BitWidth);
10221     if (Imm == 0 || Imm.isAllOnesValue())
10222       return SDValue();
10223     unsigned ShAmt = Imm.countTrailingZeros();
10224     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10225     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10226     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10227     // The narrowing should be profitable, the load/store operation should be
10228     // legal (or custom) and the store size should be equal to the NewVT width.
10229     while (NewBW < BitWidth &&
10230            (NewVT.getStoreSizeInBits() != NewBW ||
10231             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10232             !TLI.isNarrowingProfitable(VT, NewVT))) {
10233       NewBW = NextPowerOf2(NewBW);
10234       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10235     }
10236     if (NewBW >= BitWidth)
10237       return SDValue();
10238
10239     // If the lsb changed does not start at the type bitwidth boundary,
10240     // start at the previous one.
10241     if (ShAmt % NewBW)
10242       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10243     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10244                                    std::min(BitWidth, ShAmt + NewBW));
10245     if ((Imm & Mask) == Imm) {
10246       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10247       if (Opc == ISD::AND)
10248         NewImm ^= APInt::getAllOnesValue(NewBW);
10249       uint64_t PtrOff = ShAmt / 8;
10250       // For big endian targets, we need to adjust the offset to the pointer to
10251       // load the correct bytes.
10252       if (TLI.isBigEndian())
10253         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10254
10255       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10256       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10257       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10258         return SDValue();
10259
10260       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10261                                    Ptr.getValueType(), Ptr,
10262                                    DAG.getConstant(PtrOff, SDLoc(LD),
10263                                                    Ptr.getValueType()));
10264       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10265                                   LD->getChain(), NewPtr,
10266                                   LD->getPointerInfo().getWithOffset(PtrOff),
10267                                   LD->isVolatile(), LD->isNonTemporal(),
10268                                   LD->isInvariant(), NewAlign,
10269                                   LD->getAAInfo());
10270       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10271                                    DAG.getConstant(NewImm, SDLoc(Value),
10272                                                    NewVT));
10273       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10274                                    NewVal, NewPtr,
10275                                    ST->getPointerInfo().getWithOffset(PtrOff),
10276                                    false, false, NewAlign);
10277
10278       AddToWorklist(NewPtr.getNode());
10279       AddToWorklist(NewLD.getNode());
10280       AddToWorklist(NewVal.getNode());
10281       WorklistRemover DeadNodes(*this);
10282       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10283       ++OpsNarrowed;
10284       return NewST;
10285     }
10286   }
10287
10288   return SDValue();
10289 }
10290
10291 /// For a given floating point load / store pair, if the load value isn't used
10292 /// by any other operations, then consider transforming the pair to integer
10293 /// load / store operations if the target deems the transformation profitable.
10294 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10295   StoreSDNode *ST  = cast<StoreSDNode>(N);
10296   SDValue Chain = ST->getChain();
10297   SDValue Value = ST->getValue();
10298   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10299       Value.hasOneUse() &&
10300       Chain == SDValue(Value.getNode(), 1)) {
10301     LoadSDNode *LD = cast<LoadSDNode>(Value);
10302     EVT VT = LD->getMemoryVT();
10303     if (!VT.isFloatingPoint() ||
10304         VT != ST->getMemoryVT() ||
10305         LD->isNonTemporal() ||
10306         ST->isNonTemporal() ||
10307         LD->getPointerInfo().getAddrSpace() != 0 ||
10308         ST->getPointerInfo().getAddrSpace() != 0)
10309       return SDValue();
10310
10311     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10312     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10313         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10314         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10315         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10316       return SDValue();
10317
10318     unsigned LDAlign = LD->getAlignment();
10319     unsigned STAlign = ST->getAlignment();
10320     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10321     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10322     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10323       return SDValue();
10324
10325     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10326                                 LD->getChain(), LD->getBasePtr(),
10327                                 LD->getPointerInfo(),
10328                                 false, false, false, LDAlign);
10329
10330     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10331                                  NewLD, ST->getBasePtr(),
10332                                  ST->getPointerInfo(),
10333                                  false, false, STAlign);
10334
10335     AddToWorklist(NewLD.getNode());
10336     AddToWorklist(NewST.getNode());
10337     WorklistRemover DeadNodes(*this);
10338     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10339     ++LdStFP2Int;
10340     return NewST;
10341   }
10342
10343   return SDValue();
10344 }
10345
10346 namespace {
10347 /// Helper struct to parse and store a memory address as base + index + offset.
10348 /// We ignore sign extensions when it is safe to do so.
10349 /// The following two expressions are not equivalent. To differentiate we need
10350 /// to store whether there was a sign extension involved in the index
10351 /// computation.
10352 ///  (load (i64 add (i64 copyfromreg %c)
10353 ///                 (i64 signextend (add (i8 load %index)
10354 ///                                      (i8 1))))
10355 /// vs
10356 ///
10357 /// (load (i64 add (i64 copyfromreg %c)
10358 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10359 ///                                         (i32 1)))))
10360 struct BaseIndexOffset {
10361   SDValue Base;
10362   SDValue Index;
10363   int64_t Offset;
10364   bool IsIndexSignExt;
10365
10366   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10367
10368   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10369                   bool IsIndexSignExt) :
10370     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10371
10372   bool equalBaseIndex(const BaseIndexOffset &Other) {
10373     return Other.Base == Base && Other.Index == Index &&
10374       Other.IsIndexSignExt == IsIndexSignExt;
10375   }
10376
10377   /// Parses tree in Ptr for base, index, offset addresses.
10378   static BaseIndexOffset match(SDValue Ptr) {
10379     bool IsIndexSignExt = false;
10380
10381     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10382     // instruction, then it could be just the BASE or everything else we don't
10383     // know how to handle. Just use Ptr as BASE and give up.
10384     if (Ptr->getOpcode() != ISD::ADD)
10385       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10386
10387     // We know that we have at least an ADD instruction. Try to pattern match
10388     // the simple case of BASE + OFFSET.
10389     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10390       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10391       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10392                               IsIndexSignExt);
10393     }
10394
10395     // Inside a loop the current BASE pointer is calculated using an ADD and a
10396     // MUL instruction. In this case Ptr is the actual BASE pointer.
10397     // (i64 add (i64 %array_ptr)
10398     //          (i64 mul (i64 %induction_var)
10399     //                   (i64 %element_size)))
10400     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10401       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10402
10403     // Look at Base + Index + Offset cases.
10404     SDValue Base = Ptr->getOperand(0);
10405     SDValue IndexOffset = Ptr->getOperand(1);
10406
10407     // Skip signextends.
10408     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10409       IndexOffset = IndexOffset->getOperand(0);
10410       IsIndexSignExt = true;
10411     }
10412
10413     // Either the case of Base + Index (no offset) or something else.
10414     if (IndexOffset->getOpcode() != ISD::ADD)
10415       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10416
10417     // Now we have the case of Base + Index + offset.
10418     SDValue Index = IndexOffset->getOperand(0);
10419     SDValue Offset = IndexOffset->getOperand(1);
10420
10421     if (!isa<ConstantSDNode>(Offset))
10422       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10423
10424     // Ignore signextends.
10425     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10426       Index = Index->getOperand(0);
10427       IsIndexSignExt = true;
10428     } else IsIndexSignExt = false;
10429
10430     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10431     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10432   }
10433 };
10434 } // namespace
10435
10436 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10437                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10438                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10439   // Make sure we have something to merge.
10440   if (NumElem < 2)
10441     return false;
10442
10443   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10444   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10445   unsigned LatestNodeUsed = 0;
10446
10447   for (unsigned i=0; i < NumElem; ++i) {
10448     // Find a chain for the new wide-store operand. Notice that some
10449     // of the store nodes that we found may not be selected for inclusion
10450     // in the wide store. The chain we use needs to be the chain of the
10451     // latest store node which is *used* and replaced by the wide store.
10452     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10453       LatestNodeUsed = i;
10454   }
10455
10456   // The latest Node in the DAG.
10457   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10458   SDLoc DL(StoreNodes[0].MemNode);
10459
10460   SDValue StoredVal;
10461   if (UseVector) {
10462     // Find a legal type for the vector store.
10463     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10464     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10465     if (IsConstantSrc) {
10466       // A vector store with a constant source implies that the constant is
10467       // zero; we only handle merging stores of constant zeros because the zero
10468       // can be materialized without a load.
10469       // It may be beneficial to loosen this restriction to allow non-zero
10470       // store merging.
10471       StoredVal = DAG.getConstant(0, DL, Ty);
10472     } else {
10473       SmallVector<SDValue, 8> Ops;
10474       for (unsigned i = 0; i < NumElem ; ++i) {
10475         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10476         SDValue Val = St->getValue();
10477         // All of the operands of a BUILD_VECTOR must have the same type.
10478         if (Val.getValueType() != MemVT)
10479           return false;
10480         Ops.push_back(Val);
10481       }
10482
10483       // Build the extracted vector elements back into a vector.
10484       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10485     }
10486   } else {
10487     // We should always use a vector store when merging extracted vector
10488     // elements, so this path implies a store of constants.
10489     assert(IsConstantSrc && "Merged vector elements should use vector store");
10490
10491     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10492     APInt StoreInt(StoreBW, 0);
10493
10494     // Construct a single integer constant which is made of the smaller
10495     // constant inputs.
10496     bool IsLE = TLI.isLittleEndian();
10497     for (unsigned i = 0; i < NumElem ; ++i) {
10498       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10499       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10500       SDValue Val = St->getValue();
10501       StoreInt <<= ElementSizeBytes*8;
10502       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10503         StoreInt |= C->getAPIntValue().zext(StoreBW);
10504       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10505         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10506       } else {
10507         llvm_unreachable("Invalid constant element type");
10508       }
10509     }
10510
10511     // Create the new Load and Store operations.
10512     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10513     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10514   }
10515
10516   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10517                                   FirstInChain->getBasePtr(),
10518                                   FirstInChain->getPointerInfo(),
10519                                   false, false,
10520                                   FirstInChain->getAlignment());
10521
10522   // Replace the last store with the new store
10523   CombineTo(LatestOp, NewStore);
10524   // Erase all other stores.
10525   for (unsigned i = 0; i < NumElem ; ++i) {
10526     if (StoreNodes[i].MemNode == LatestOp)
10527       continue;
10528     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10529     // ReplaceAllUsesWith will replace all uses that existed when it was
10530     // called, but graph optimizations may cause new ones to appear. For
10531     // example, the case in pr14333 looks like
10532     //
10533     //  St's chain -> St -> another store -> X
10534     //
10535     // And the only difference from St to the other store is the chain.
10536     // When we change it's chain to be St's chain they become identical,
10537     // get CSEed and the net result is that X is now a use of St.
10538     // Since we know that St is redundant, just iterate.
10539     while (!St->use_empty())
10540       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10541     deleteAndRecombine(St);
10542   }
10543
10544   return true;
10545 }
10546
10547 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10548   if (OptLevel == CodeGenOpt::None)
10549     return false;
10550
10551   EVT MemVT = St->getMemoryVT();
10552   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10553   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10554       Attribute::NoImplicitFloat);
10555
10556   // Don't merge vectors into wider inputs.
10557   if (MemVT.isVector() || !MemVT.isSimple())
10558     return false;
10559
10560   // Perform an early exit check. Do not bother looking at stored values that
10561   // are not constants, loads, or extracted vector elements.
10562   SDValue StoredVal = St->getValue();
10563   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10564   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10565                        isa<ConstantFPSDNode>(StoredVal);
10566   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10567
10568   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10569     return false;
10570
10571   // Only look at ends of store sequences.
10572   SDValue Chain = SDValue(St, 0);
10573   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10574     return false;
10575
10576   // This holds the base pointer, index, and the offset in bytes from the base
10577   // pointer.
10578   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10579
10580   // We must have a base and an offset.
10581   if (!BasePtr.Base.getNode())
10582     return false;
10583
10584   // Do not handle stores to undef base pointers.
10585   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10586     return false;
10587
10588   // Save the LoadSDNodes that we find in the chain.
10589   // We need to make sure that these nodes do not interfere with
10590   // any of the store nodes.
10591   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10592
10593   // Save the StoreSDNodes that we find in the chain.
10594   SmallVector<MemOpLink, 8> StoreNodes;
10595
10596   // Walk up the chain and look for nodes with offsets from the same
10597   // base pointer. Stop when reaching an instruction with a different kind
10598   // or instruction which has a different base pointer.
10599   unsigned Seq = 0;
10600   StoreSDNode *Index = St;
10601   while (Index) {
10602     // If the chain has more than one use, then we can't reorder the mem ops.
10603     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10604       break;
10605
10606     // Find the base pointer and offset for this memory node.
10607     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10608
10609     // Check that the base pointer is the same as the original one.
10610     if (!Ptr.equalBaseIndex(BasePtr))
10611       break;
10612
10613     // Check that the alignment is the same.
10614     if (Index->getAlignment() != St->getAlignment())
10615       break;
10616
10617     // The memory operands must not be volatile.
10618     if (Index->isVolatile() || Index->isIndexed())
10619       break;
10620
10621     // No truncation.
10622     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10623       if (St->isTruncatingStore())
10624         break;
10625
10626     // The stored memory type must be the same.
10627     if (Index->getMemoryVT() != MemVT)
10628       break;
10629
10630     // We do not allow unaligned stores because we want to prevent overriding
10631     // stores.
10632     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10633       break;
10634
10635     // We found a potential memory operand to merge.
10636     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10637
10638     // Find the next memory operand in the chain. If the next operand in the
10639     // chain is a store then move up and continue the scan with the next
10640     // memory operand. If the next operand is a load save it and use alias
10641     // information to check if it interferes with anything.
10642     SDNode *NextInChain = Index->getChain().getNode();
10643     while (1) {
10644       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10645         // We found a store node. Use it for the next iteration.
10646         Index = STn;
10647         break;
10648       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10649         if (Ldn->isVolatile()) {
10650           Index = nullptr;
10651           break;
10652         }
10653
10654         // Save the load node for later. Continue the scan.
10655         AliasLoadNodes.push_back(Ldn);
10656         NextInChain = Ldn->getChain().getNode();
10657         continue;
10658       } else {
10659         Index = nullptr;
10660         break;
10661       }
10662     }
10663   }
10664
10665   // Check if there is anything to merge.
10666   if (StoreNodes.size() < 2)
10667     return false;
10668
10669   // Sort the memory operands according to their distance from the base pointer.
10670   std::sort(StoreNodes.begin(), StoreNodes.end(),
10671             [](MemOpLink LHS, MemOpLink RHS) {
10672     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10673            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10674             LHS.SequenceNum > RHS.SequenceNum);
10675   });
10676
10677   // Scan the memory operations on the chain and find the first non-consecutive
10678   // store memory address.
10679   unsigned LastConsecutiveStore = 0;
10680   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10681   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10682
10683     // Check that the addresses are consecutive starting from the second
10684     // element in the list of stores.
10685     if (i > 0) {
10686       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10687       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10688         break;
10689     }
10690
10691     bool Alias = false;
10692     // Check if this store interferes with any of the loads that we found.
10693     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10694       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10695         Alias = true;
10696         break;
10697       }
10698     // We found a load that alias with this store. Stop the sequence.
10699     if (Alias)
10700       break;
10701
10702     // Mark this node as useful.
10703     LastConsecutiveStore = i;
10704   }
10705
10706   // The node with the lowest store address.
10707   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10708
10709   // Store the constants into memory as one consecutive store.
10710   if (IsConstantSrc) {
10711     unsigned LastLegalType = 0;
10712     unsigned LastLegalVectorType = 0;
10713     bool NonZero = false;
10714     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10715       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10716       SDValue StoredVal = St->getValue();
10717
10718       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10719         NonZero |= !C->isNullValue();
10720       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10721         NonZero |= !C->getConstantFPValue()->isNullValue();
10722       } else {
10723         // Non-constant.
10724         break;
10725       }
10726
10727       // Find a legal type for the constant store.
10728       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10729       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10730       if (TLI.isTypeLegal(StoreTy))
10731         LastLegalType = i+1;
10732       // Or check whether a truncstore is legal.
10733       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10734                TargetLowering::TypePromoteInteger) {
10735         EVT LegalizedStoredValueTy =
10736           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10737         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10738           LastLegalType = i+1;
10739       }
10740
10741       // Find a legal type for the vector store.
10742       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10743       if (TLI.isTypeLegal(Ty))
10744         LastLegalVectorType = i + 1;
10745     }
10746
10747     // We only use vectors if the constant is known to be zero and the
10748     // function is not marked with the noimplicitfloat attribute.
10749     if (NonZero || NoVectors)
10750       LastLegalVectorType = 0;
10751
10752     // Check if we found a legal integer type to store.
10753     if (LastLegalType == 0 && LastLegalVectorType == 0)
10754       return false;
10755
10756     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10757     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10758
10759     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10760                                            true, UseVector);
10761   }
10762
10763   // When extracting multiple vector elements, try to store them
10764   // in one vector store rather than a sequence of scalar stores.
10765   if (IsExtractVecEltSrc) {
10766     unsigned NumElem = 0;
10767     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10768       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10769       SDValue StoredVal = St->getValue();
10770       // This restriction could be loosened.
10771       // Bail out if any stored values are not elements extracted from a vector.
10772       // It should be possible to handle mixed sources, but load sources need
10773       // more careful handling (see the block of code below that handles
10774       // consecutive loads).
10775       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10776         return false;
10777
10778       // Find a legal type for the vector store.
10779       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10780       if (TLI.isTypeLegal(Ty))
10781         NumElem = i + 1;
10782     }
10783
10784     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10785                                            false, true);
10786   }
10787
10788   // Below we handle the case of multiple consecutive stores that
10789   // come from multiple consecutive loads. We merge them into a single
10790   // wide load and a single wide store.
10791
10792   // Look for load nodes which are used by the stored values.
10793   SmallVector<MemOpLink, 8> LoadNodes;
10794
10795   // Find acceptable loads. Loads need to have the same chain (token factor),
10796   // must not be zext, volatile, indexed, and they must be consecutive.
10797   BaseIndexOffset LdBasePtr;
10798   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10799     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10800     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10801     if (!Ld) break;
10802
10803     // Loads must only have one use.
10804     if (!Ld->hasNUsesOfValue(1, 0))
10805       break;
10806
10807     // Check that the alignment is the same as the stores.
10808     if (Ld->getAlignment() != St->getAlignment())
10809       break;
10810
10811     // The memory operands must not be volatile.
10812     if (Ld->isVolatile() || Ld->isIndexed())
10813       break;
10814
10815     // We do not accept ext loads.
10816     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10817       break;
10818
10819     // The stored memory type must be the same.
10820     if (Ld->getMemoryVT() != MemVT)
10821       break;
10822
10823     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10824     // If this is not the first ptr that we check.
10825     if (LdBasePtr.Base.getNode()) {
10826       // The base ptr must be the same.
10827       if (!LdPtr.equalBaseIndex(LdBasePtr))
10828         break;
10829     } else {
10830       // Check that all other base pointers are the same as this one.
10831       LdBasePtr = LdPtr;
10832     }
10833
10834     // We found a potential memory operand to merge.
10835     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10836   }
10837
10838   if (LoadNodes.size() < 2)
10839     return false;
10840
10841   // If we have load/store pair instructions and we only have two values,
10842   // don't bother.
10843   unsigned RequiredAlignment;
10844   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10845       St->getAlignment() >= RequiredAlignment)
10846     return false;
10847
10848   // Scan the memory operations on the chain and find the first non-consecutive
10849   // load memory address. These variables hold the index in the store node
10850   // array.
10851   unsigned LastConsecutiveLoad = 0;
10852   // This variable refers to the size and not index in the array.
10853   unsigned LastLegalVectorType = 0;
10854   unsigned LastLegalIntegerType = 0;
10855   StartAddress = LoadNodes[0].OffsetFromBase;
10856   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10857   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10858     // All loads much share the same chain.
10859     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10860       break;
10861
10862     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10863     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10864       break;
10865     LastConsecutiveLoad = i;
10866
10867     // Find a legal type for the vector store.
10868     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10869     if (TLI.isTypeLegal(StoreTy))
10870       LastLegalVectorType = i + 1;
10871
10872     // Find a legal type for the integer store.
10873     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10874     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10875     if (TLI.isTypeLegal(StoreTy))
10876       LastLegalIntegerType = i + 1;
10877     // Or check whether a truncstore and extload is legal.
10878     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10879              TargetLowering::TypePromoteInteger) {
10880       EVT LegalizedStoredValueTy =
10881         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10882       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10883           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10884           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10885           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10886         LastLegalIntegerType = i+1;
10887     }
10888   }
10889
10890   // Only use vector types if the vector type is larger than the integer type.
10891   // If they are the same, use integers.
10892   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10893   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10894
10895   // We add +1 here because the LastXXX variables refer to location while
10896   // the NumElem refers to array/index size.
10897   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10898   NumElem = std::min(LastLegalType, NumElem);
10899
10900   if (NumElem < 2)
10901     return false;
10902
10903   // The latest Node in the DAG.
10904   unsigned LatestNodeUsed = 0;
10905   for (unsigned i=1; i<NumElem; ++i) {
10906     // Find a chain for the new wide-store operand. Notice that some
10907     // of the store nodes that we found may not be selected for inclusion
10908     // in the wide store. The chain we use needs to be the chain of the
10909     // latest store node which is *used* and replaced by the wide store.
10910     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10911       LatestNodeUsed = i;
10912   }
10913
10914   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10915
10916   // Find if it is better to use vectors or integers to load and store
10917   // to memory.
10918   EVT JointMemOpVT;
10919   if (UseVectorTy) {
10920     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10921   } else {
10922     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10923     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10924   }
10925
10926   SDLoc LoadDL(LoadNodes[0].MemNode);
10927   SDLoc StoreDL(StoreNodes[0].MemNode);
10928
10929   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10930   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10931                                 FirstLoad->getChain(),
10932                                 FirstLoad->getBasePtr(),
10933                                 FirstLoad->getPointerInfo(),
10934                                 false, false, false,
10935                                 FirstLoad->getAlignment());
10936
10937   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10938                                   FirstInChain->getBasePtr(),
10939                                   FirstInChain->getPointerInfo(), false, false,
10940                                   FirstInChain->getAlignment());
10941
10942   // Replace one of the loads with the new load.
10943   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10944   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10945                                 SDValue(NewLoad.getNode(), 1));
10946
10947   // Remove the rest of the load chains.
10948   for (unsigned i = 1; i < NumElem ; ++i) {
10949     // Replace all chain users of the old load nodes with the chain of the new
10950     // load node.
10951     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10952     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10953   }
10954
10955   // Replace the last store with the new store.
10956   CombineTo(LatestOp, NewStore);
10957   // Erase all other stores.
10958   for (unsigned i = 0; i < NumElem ; ++i) {
10959     // Remove all Store nodes.
10960     if (StoreNodes[i].MemNode == LatestOp)
10961       continue;
10962     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10963     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10964     deleteAndRecombine(St);
10965   }
10966
10967   return true;
10968 }
10969
10970 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10971   StoreSDNode *ST  = cast<StoreSDNode>(N);
10972   SDValue Chain = ST->getChain();
10973   SDValue Value = ST->getValue();
10974   SDValue Ptr   = ST->getBasePtr();
10975
10976   // If this is a store of a bit convert, store the input value if the
10977   // resultant store does not need a higher alignment than the original.
10978   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10979       ST->isUnindexed()) {
10980     unsigned OrigAlign = ST->getAlignment();
10981     EVT SVT = Value.getOperand(0).getValueType();
10982     unsigned Align = TLI.getDataLayout()->
10983       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10984     if (Align <= OrigAlign &&
10985         ((!LegalOperations && !ST->isVolatile()) ||
10986          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10987       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10988                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10989                           ST->isNonTemporal(), OrigAlign,
10990                           ST->getAAInfo());
10991   }
10992
10993   // Turn 'store undef, Ptr' -> nothing.
10994   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10995     return Chain;
10996
10997   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10998   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10999     // NOTE: If the original store is volatile, this transform must not increase
11000     // the number of stores.  For example, on x86-32 an f64 can be stored in one
11001     // processor operation but an i64 (which is not legal) requires two.  So the
11002     // transform should not be done in this case.
11003     if (Value.getOpcode() != ISD::TargetConstantFP) {
11004       SDValue Tmp;
11005       switch (CFP->getSimpleValueType(0).SimpleTy) {
11006       default: llvm_unreachable("Unknown FP type");
11007       case MVT::f16:    // We don't do this for these yet.
11008       case MVT::f80:
11009       case MVT::f128:
11010       case MVT::ppcf128:
11011         break;
11012       case MVT::f32:
11013         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11014             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11015           ;
11016           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11017                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11018                               MVT::i32);
11019           return DAG.getStore(Chain, SDLoc(N), Tmp,
11020                               Ptr, ST->getMemOperand());
11021         }
11022         break;
11023       case MVT::f64:
11024         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11025              !ST->isVolatile()) ||
11026             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11027           ;
11028           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11029                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11030           return DAG.getStore(Chain, SDLoc(N), Tmp,
11031                               Ptr, ST->getMemOperand());
11032         }
11033
11034         if (!ST->isVolatile() &&
11035             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11036           // Many FP stores are not made apparent until after legalize, e.g. for
11037           // argument passing.  Since this is so common, custom legalize the
11038           // 64-bit integer store into two 32-bit stores.
11039           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11040           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11041           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11042           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11043
11044           unsigned Alignment = ST->getAlignment();
11045           bool isVolatile = ST->isVolatile();
11046           bool isNonTemporal = ST->isNonTemporal();
11047           AAMDNodes AAInfo = ST->getAAInfo();
11048
11049           SDLoc DL(N);
11050
11051           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11052                                      Ptr, ST->getPointerInfo(),
11053                                      isVolatile, isNonTemporal,
11054                                      ST->getAlignment(), AAInfo);
11055           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11056                             DAG.getConstant(4, DL, Ptr.getValueType()));
11057           Alignment = MinAlign(Alignment, 4U);
11058           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11059                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11060                                      isVolatile, isNonTemporal,
11061                                      Alignment, AAInfo);
11062           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11063                              St0, St1);
11064         }
11065
11066         break;
11067       }
11068     }
11069   }
11070
11071   // Try to infer better alignment information than the store already has.
11072   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11073     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11074       if (Align > ST->getAlignment()) {
11075         SDValue NewStore =
11076                DAG.getTruncStore(Chain, SDLoc(N), Value,
11077                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11078                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11079                                  ST->getAAInfo());
11080         if (NewStore.getNode() != N)
11081           return CombineTo(ST, NewStore, true);
11082       }
11083     }
11084   }
11085
11086   // Try transforming a pair floating point load / store ops to integer
11087   // load / store ops.
11088   SDValue NewST = TransformFPLoadStorePair(N);
11089   if (NewST.getNode())
11090     return NewST;
11091
11092   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11093                                                   : DAG.getSubtarget().useAA();
11094 #ifndef NDEBUG
11095   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11096       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11097     UseAA = false;
11098 #endif
11099   if (UseAA && ST->isUnindexed()) {
11100     // Walk up chain skipping non-aliasing memory nodes.
11101     SDValue BetterChain = FindBetterChain(N, Chain);
11102
11103     // If there is a better chain.
11104     if (Chain != BetterChain) {
11105       SDValue ReplStore;
11106
11107       // Replace the chain to avoid dependency.
11108       if (ST->isTruncatingStore()) {
11109         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11110                                       ST->getMemoryVT(), ST->getMemOperand());
11111       } else {
11112         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11113                                  ST->getMemOperand());
11114       }
11115
11116       // Create token to keep both nodes around.
11117       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11118                                   MVT::Other, Chain, ReplStore);
11119
11120       // Make sure the new and old chains are cleaned up.
11121       AddToWorklist(Token.getNode());
11122
11123       // Don't add users to work list.
11124       return CombineTo(N, Token, false);
11125     }
11126   }
11127
11128   // Try transforming N to an indexed store.
11129   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11130     return SDValue(N, 0);
11131
11132   // FIXME: is there such a thing as a truncating indexed store?
11133   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11134       Value.getValueType().isInteger()) {
11135     // See if we can simplify the input to this truncstore with knowledge that
11136     // only the low bits are being used.  For example:
11137     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11138     SDValue Shorter =
11139       GetDemandedBits(Value,
11140                       APInt::getLowBitsSet(
11141                         Value.getValueType().getScalarType().getSizeInBits(),
11142                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11143     AddToWorklist(Value.getNode());
11144     if (Shorter.getNode())
11145       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11146                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11147
11148     // Otherwise, see if we can simplify the operation with
11149     // SimplifyDemandedBits, which only works if the value has a single use.
11150     if (SimplifyDemandedBits(Value,
11151                         APInt::getLowBitsSet(
11152                           Value.getValueType().getScalarType().getSizeInBits(),
11153                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11154       return SDValue(N, 0);
11155   }
11156
11157   // If this is a load followed by a store to the same location, then the store
11158   // is dead/noop.
11159   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11160     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11161         ST->isUnindexed() && !ST->isVolatile() &&
11162         // There can't be any side effects between the load and store, such as
11163         // a call or store.
11164         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11165       // The store is dead, remove it.
11166       return Chain;
11167     }
11168   }
11169
11170   // If this is a store followed by a store with the same value to the same
11171   // location, then the store is dead/noop.
11172   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11173     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11174         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11175         ST1->isUnindexed() && !ST1->isVolatile()) {
11176       // The store is dead, remove it.
11177       return Chain;
11178     }
11179   }
11180
11181   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11182   // truncating store.  We can do this even if this is already a truncstore.
11183   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11184       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11185       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11186                             ST->getMemoryVT())) {
11187     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11188                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11189   }
11190
11191   // Only perform this optimization before the types are legal, because we
11192   // don't want to perform this optimization on every DAGCombine invocation.
11193   if (!LegalTypes) {
11194     bool EverChanged = false;
11195
11196     do {
11197       // There can be multiple store sequences on the same chain.
11198       // Keep trying to merge store sequences until we are unable to do so
11199       // or until we merge the last store on the chain.
11200       bool Changed = MergeConsecutiveStores(ST);
11201       EverChanged |= Changed;
11202       if (!Changed) break;
11203     } while (ST->getOpcode() != ISD::DELETED_NODE);
11204
11205     if (EverChanged)
11206       return SDValue(N, 0);
11207   }
11208
11209   return ReduceLoadOpStoreWidth(N);
11210 }
11211
11212 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11213   SDValue InVec = N->getOperand(0);
11214   SDValue InVal = N->getOperand(1);
11215   SDValue EltNo = N->getOperand(2);
11216   SDLoc dl(N);
11217
11218   // If the inserted element is an UNDEF, just use the input vector.
11219   if (InVal.getOpcode() == ISD::UNDEF)
11220     return InVec;
11221
11222   EVT VT = InVec.getValueType();
11223
11224   // If we can't generate a legal BUILD_VECTOR, exit
11225   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11226     return SDValue();
11227
11228   // Check that we know which element is being inserted
11229   if (!isa<ConstantSDNode>(EltNo))
11230     return SDValue();
11231   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11232
11233   // Canonicalize insert_vector_elt dag nodes.
11234   // Example:
11235   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11236   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11237   //
11238   // Do this only if the child insert_vector node has one use; also
11239   // do this only if indices are both constants and Idx1 < Idx0.
11240   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11241       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11242     unsigned OtherElt =
11243       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11244     if (Elt < OtherElt) {
11245       // Swap nodes.
11246       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11247                                   InVec.getOperand(0), InVal, EltNo);
11248       AddToWorklist(NewOp.getNode());
11249       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11250                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11251     }
11252   }
11253
11254   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11255   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11256   // vector elements.
11257   SmallVector<SDValue, 8> Ops;
11258   // Do not combine these two vectors if the output vector will not replace
11259   // the input vector.
11260   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11261     Ops.append(InVec.getNode()->op_begin(),
11262                InVec.getNode()->op_end());
11263   } else if (InVec.getOpcode() == ISD::UNDEF) {
11264     unsigned NElts = VT.getVectorNumElements();
11265     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11266   } else {
11267     return SDValue();
11268   }
11269
11270   // Insert the element
11271   if (Elt < Ops.size()) {
11272     // All the operands of BUILD_VECTOR must have the same type;
11273     // we enforce that here.
11274     EVT OpVT = Ops[0].getValueType();
11275     if (InVal.getValueType() != OpVT)
11276       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11277                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11278                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11279     Ops[Elt] = InVal;
11280   }
11281
11282   // Return the new vector
11283   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11284 }
11285
11286 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11287     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11288   EVT ResultVT = EVE->getValueType(0);
11289   EVT VecEltVT = InVecVT.getVectorElementType();
11290   unsigned Align = OriginalLoad->getAlignment();
11291   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11292       VecEltVT.getTypeForEVT(*DAG.getContext()));
11293
11294   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11295     return SDValue();
11296
11297   Align = NewAlign;
11298
11299   SDValue NewPtr = OriginalLoad->getBasePtr();
11300   SDValue Offset;
11301   EVT PtrType = NewPtr.getValueType();
11302   MachinePointerInfo MPI;
11303   SDLoc DL(EVE);
11304   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11305     int Elt = ConstEltNo->getZExtValue();
11306     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11307     if (TLI.isBigEndian())
11308       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11309     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11310     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11311   } else {
11312     Offset = DAG.getNode(
11313         ISD::MUL, DL, EltNo.getValueType(), EltNo,
11314         DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11315     if (TLI.isBigEndian())
11316       Offset = DAG.getNode(
11317           ISD::SUB, DL, EltNo.getValueType(),
11318           DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11319           Offset);
11320     MPI = OriginalLoad->getPointerInfo();
11321   }
11322   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11323
11324   // The replacement we need to do here is a little tricky: we need to
11325   // replace an extractelement of a load with a load.
11326   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11327   // Note that this replacement assumes that the extractvalue is the only
11328   // use of the load; that's okay because we don't want to perform this
11329   // transformation in other cases anyway.
11330   SDValue Load;
11331   SDValue Chain;
11332   if (ResultVT.bitsGT(VecEltVT)) {
11333     // If the result type of vextract is wider than the load, then issue an
11334     // extending load instead.
11335     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11336                                                   VecEltVT)
11337                                    ? ISD::ZEXTLOAD
11338                                    : ISD::EXTLOAD;
11339     Load = DAG.getExtLoad(
11340         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11341         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11342         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11343     Chain = Load.getValue(1);
11344   } else {
11345     Load = DAG.getLoad(
11346         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11347         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11348         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11349     Chain = Load.getValue(1);
11350     if (ResultVT.bitsLT(VecEltVT))
11351       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11352     else
11353       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11354   }
11355   WorklistRemover DeadNodes(*this);
11356   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11357   SDValue To[] = { Load, Chain };
11358   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11359   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11360   // worklist explicitly as well.
11361   AddToWorklist(Load.getNode());
11362   AddUsersToWorklist(Load.getNode()); // Add users too
11363   // Make sure to revisit this node to clean it up; it will usually be dead.
11364   AddToWorklist(EVE);
11365   ++OpsNarrowed;
11366   return SDValue(EVE, 0);
11367 }
11368
11369 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11370   // (vextract (scalar_to_vector val, 0) -> val
11371   SDValue InVec = N->getOperand(0);
11372   EVT VT = InVec.getValueType();
11373   EVT NVT = N->getValueType(0);
11374
11375   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11376     // Check if the result type doesn't match the inserted element type. A
11377     // SCALAR_TO_VECTOR may truncate the inserted element and the
11378     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11379     SDValue InOp = InVec.getOperand(0);
11380     if (InOp.getValueType() != NVT) {
11381       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11382       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11383     }
11384     return InOp;
11385   }
11386
11387   SDValue EltNo = N->getOperand(1);
11388   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11389
11390   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11391   // We only perform this optimization before the op legalization phase because
11392   // we may introduce new vector instructions which are not backed by TD
11393   // patterns. For example on AVX, extracting elements from a wide vector
11394   // without using extract_subvector. However, if we can find an underlying
11395   // scalar value, then we can always use that.
11396   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11397       && ConstEltNo) {
11398     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11399     int NumElem = VT.getVectorNumElements();
11400     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11401     // Find the new index to extract from.
11402     int OrigElt = SVOp->getMaskElt(Elt);
11403
11404     // Extracting an undef index is undef.
11405     if (OrigElt == -1)
11406       return DAG.getUNDEF(NVT);
11407
11408     // Select the right vector half to extract from.
11409     SDValue SVInVec;
11410     if (OrigElt < NumElem) {
11411       SVInVec = InVec->getOperand(0);
11412     } else {
11413       SVInVec = InVec->getOperand(1);
11414       OrigElt -= NumElem;
11415     }
11416
11417     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11418       SDValue InOp = SVInVec.getOperand(OrigElt);
11419       if (InOp.getValueType() != NVT) {
11420         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11421         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11422       }
11423
11424       return InOp;
11425     }
11426
11427     // FIXME: We should handle recursing on other vector shuffles and
11428     // scalar_to_vector here as well.
11429
11430     if (!LegalOperations) {
11431       EVT IndexTy = TLI.getVectorIdxTy();
11432       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11433                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11434     }
11435   }
11436
11437   bool BCNumEltsChanged = false;
11438   EVT ExtVT = VT.getVectorElementType();
11439   EVT LVT = ExtVT;
11440
11441   // If the result of load has to be truncated, then it's not necessarily
11442   // profitable.
11443   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11444     return SDValue();
11445
11446   if (InVec.getOpcode() == ISD::BITCAST) {
11447     // Don't duplicate a load with other uses.
11448     if (!InVec.hasOneUse())
11449       return SDValue();
11450
11451     EVT BCVT = InVec.getOperand(0).getValueType();
11452     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11453       return SDValue();
11454     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11455       BCNumEltsChanged = true;
11456     InVec = InVec.getOperand(0);
11457     ExtVT = BCVT.getVectorElementType();
11458   }
11459
11460   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11461   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11462       ISD::isNormalLoad(InVec.getNode()) &&
11463       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11464     SDValue Index = N->getOperand(1);
11465     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11466       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11467                                                            OrigLoad);
11468   }
11469
11470   // Perform only after legalization to ensure build_vector / vector_shuffle
11471   // optimizations have already been done.
11472   if (!LegalOperations) return SDValue();
11473
11474   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11475   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11476   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11477
11478   if (ConstEltNo) {
11479     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11480
11481     LoadSDNode *LN0 = nullptr;
11482     const ShuffleVectorSDNode *SVN = nullptr;
11483     if (ISD::isNormalLoad(InVec.getNode())) {
11484       LN0 = cast<LoadSDNode>(InVec);
11485     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11486                InVec.getOperand(0).getValueType() == ExtVT &&
11487                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11488       // Don't duplicate a load with other uses.
11489       if (!InVec.hasOneUse())
11490         return SDValue();
11491
11492       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11493     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11494       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11495       // =>
11496       // (load $addr+1*size)
11497
11498       // Don't duplicate a load with other uses.
11499       if (!InVec.hasOneUse())
11500         return SDValue();
11501
11502       // If the bit convert changed the number of elements, it is unsafe
11503       // to examine the mask.
11504       if (BCNumEltsChanged)
11505         return SDValue();
11506
11507       // Select the input vector, guarding against out of range extract vector.
11508       unsigned NumElems = VT.getVectorNumElements();
11509       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11510       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11511
11512       if (InVec.getOpcode() == ISD::BITCAST) {
11513         // Don't duplicate a load with other uses.
11514         if (!InVec.hasOneUse())
11515           return SDValue();
11516
11517         InVec = InVec.getOperand(0);
11518       }
11519       if (ISD::isNormalLoad(InVec.getNode())) {
11520         LN0 = cast<LoadSDNode>(InVec);
11521         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11522         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11523       }
11524     }
11525
11526     // Make sure we found a non-volatile load and the extractelement is
11527     // the only use.
11528     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11529       return SDValue();
11530
11531     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11532     if (Elt == -1)
11533       return DAG.getUNDEF(LVT);
11534
11535     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11536   }
11537
11538   return SDValue();
11539 }
11540
11541 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11542 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11543   // We perform this optimization post type-legalization because
11544   // the type-legalizer often scalarizes integer-promoted vectors.
11545   // Performing this optimization before may create bit-casts which
11546   // will be type-legalized to complex code sequences.
11547   // We perform this optimization only before the operation legalizer because we
11548   // may introduce illegal operations.
11549   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11550     return SDValue();
11551
11552   unsigned NumInScalars = N->getNumOperands();
11553   SDLoc dl(N);
11554   EVT VT = N->getValueType(0);
11555
11556   // Check to see if this is a BUILD_VECTOR of a bunch of values
11557   // which come from any_extend or zero_extend nodes. If so, we can create
11558   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11559   // optimizations. We do not handle sign-extend because we can't fill the sign
11560   // using shuffles.
11561   EVT SourceType = MVT::Other;
11562   bool AllAnyExt = true;
11563
11564   for (unsigned i = 0; i != NumInScalars; ++i) {
11565     SDValue In = N->getOperand(i);
11566     // Ignore undef inputs.
11567     if (In.getOpcode() == ISD::UNDEF) continue;
11568
11569     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11570     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11571
11572     // Abort if the element is not an extension.
11573     if (!ZeroExt && !AnyExt) {
11574       SourceType = MVT::Other;
11575       break;
11576     }
11577
11578     // The input is a ZeroExt or AnyExt. Check the original type.
11579     EVT InTy = In.getOperand(0).getValueType();
11580
11581     // Check that all of the widened source types are the same.
11582     if (SourceType == MVT::Other)
11583       // First time.
11584       SourceType = InTy;
11585     else if (InTy != SourceType) {
11586       // Multiple income types. Abort.
11587       SourceType = MVT::Other;
11588       break;
11589     }
11590
11591     // Check if all of the extends are ANY_EXTENDs.
11592     AllAnyExt &= AnyExt;
11593   }
11594
11595   // In order to have valid types, all of the inputs must be extended from the
11596   // same source type and all of the inputs must be any or zero extend.
11597   // Scalar sizes must be a power of two.
11598   EVT OutScalarTy = VT.getScalarType();
11599   bool ValidTypes = SourceType != MVT::Other &&
11600                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11601                  isPowerOf2_32(SourceType.getSizeInBits());
11602
11603   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11604   // turn into a single shuffle instruction.
11605   if (!ValidTypes)
11606     return SDValue();
11607
11608   bool isLE = TLI.isLittleEndian();
11609   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11610   assert(ElemRatio > 1 && "Invalid element size ratio");
11611   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11612                                DAG.getConstant(0, SDLoc(N), SourceType);
11613
11614   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11615   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11616
11617   // Populate the new build_vector
11618   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11619     SDValue Cast = N->getOperand(i);
11620     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11621             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11622             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11623     SDValue In;
11624     if (Cast.getOpcode() == ISD::UNDEF)
11625       In = DAG.getUNDEF(SourceType);
11626     else
11627       In = Cast->getOperand(0);
11628     unsigned Index = isLE ? (i * ElemRatio) :
11629                             (i * ElemRatio + (ElemRatio - 1));
11630
11631     assert(Index < Ops.size() && "Invalid index");
11632     Ops[Index] = In;
11633   }
11634
11635   // The type of the new BUILD_VECTOR node.
11636   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11637   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11638          "Invalid vector size");
11639   // Check if the new vector type is legal.
11640   if (!isTypeLegal(VecVT)) return SDValue();
11641
11642   // Make the new BUILD_VECTOR.
11643   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11644
11645   // The new BUILD_VECTOR node has the potential to be further optimized.
11646   AddToWorklist(BV.getNode());
11647   // Bitcast to the desired type.
11648   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11649 }
11650
11651 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11652   EVT VT = N->getValueType(0);
11653
11654   unsigned NumInScalars = N->getNumOperands();
11655   SDLoc dl(N);
11656
11657   EVT SrcVT = MVT::Other;
11658   unsigned Opcode = ISD::DELETED_NODE;
11659   unsigned NumDefs = 0;
11660
11661   for (unsigned i = 0; i != NumInScalars; ++i) {
11662     SDValue In = N->getOperand(i);
11663     unsigned Opc = In.getOpcode();
11664
11665     if (Opc == ISD::UNDEF)
11666       continue;
11667
11668     // If all scalar values are floats and converted from integers.
11669     if (Opcode == ISD::DELETED_NODE &&
11670         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11671       Opcode = Opc;
11672     }
11673
11674     if (Opc != Opcode)
11675       return SDValue();
11676
11677     EVT InVT = In.getOperand(0).getValueType();
11678
11679     // If all scalar values are typed differently, bail out. It's chosen to
11680     // simplify BUILD_VECTOR of integer types.
11681     if (SrcVT == MVT::Other)
11682       SrcVT = InVT;
11683     if (SrcVT != InVT)
11684       return SDValue();
11685     NumDefs++;
11686   }
11687
11688   // If the vector has just one element defined, it's not worth to fold it into
11689   // a vectorized one.
11690   if (NumDefs < 2)
11691     return SDValue();
11692
11693   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11694          && "Should only handle conversion from integer to float.");
11695   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11696
11697   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11698
11699   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11700     return SDValue();
11701
11702   // Just because the floating-point vector type is legal does not necessarily
11703   // mean that the corresponding integer vector type is.
11704   if (!isTypeLegal(NVT))
11705     return SDValue();
11706
11707   SmallVector<SDValue, 8> Opnds;
11708   for (unsigned i = 0; i != NumInScalars; ++i) {
11709     SDValue In = N->getOperand(i);
11710
11711     if (In.getOpcode() == ISD::UNDEF)
11712       Opnds.push_back(DAG.getUNDEF(SrcVT));
11713     else
11714       Opnds.push_back(In.getOperand(0));
11715   }
11716   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11717   AddToWorklist(BV.getNode());
11718
11719   return DAG.getNode(Opcode, dl, VT, BV);
11720 }
11721
11722 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11723   unsigned NumInScalars = N->getNumOperands();
11724   SDLoc dl(N);
11725   EVT VT = N->getValueType(0);
11726
11727   // A vector built entirely of undefs is undef.
11728   if (ISD::allOperandsUndef(N))
11729     return DAG.getUNDEF(VT);
11730
11731   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11732     return V;
11733
11734   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11735     return V;
11736
11737   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11738   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11739   // at most two distinct vectors, turn this into a shuffle node.
11740
11741   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11742   if (!isTypeLegal(VT))
11743     return SDValue();
11744
11745   // May only combine to shuffle after legalize if shuffle is legal.
11746   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11747     return SDValue();
11748
11749   SDValue VecIn1, VecIn2;
11750   bool UsesZeroVector = false;
11751   for (unsigned i = 0; i != NumInScalars; ++i) {
11752     SDValue Op = N->getOperand(i);
11753     // Ignore undef inputs.
11754     if (Op.getOpcode() == ISD::UNDEF) continue;
11755
11756     // See if we can combine this build_vector into a blend with a zero vector.
11757     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11758         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11759         (Op.getOpcode() == ISD::ConstantFP &&
11760         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11761       UsesZeroVector = true;
11762       continue;
11763     }
11764
11765     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11766     // constant index, bail out.
11767     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11768         !isa<ConstantSDNode>(Op.getOperand(1))) {
11769       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11770       break;
11771     }
11772
11773     // We allow up to two distinct input vectors.
11774     SDValue ExtractedFromVec = Op.getOperand(0);
11775     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11776       continue;
11777
11778     if (!VecIn1.getNode()) {
11779       VecIn1 = ExtractedFromVec;
11780     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11781       VecIn2 = ExtractedFromVec;
11782     } else {
11783       // Too many inputs.
11784       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11785       break;
11786     }
11787   }
11788
11789   // If everything is good, we can make a shuffle operation.
11790   if (VecIn1.getNode()) {
11791     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11792     SmallVector<int, 8> Mask;
11793     for (unsigned i = 0; i != NumInScalars; ++i) {
11794       unsigned Opcode = N->getOperand(i).getOpcode();
11795       if (Opcode == ISD::UNDEF) {
11796         Mask.push_back(-1);
11797         continue;
11798       }
11799
11800       // Operands can also be zero.
11801       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11802         assert(UsesZeroVector &&
11803                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11804                "Unexpected node found!");
11805         Mask.push_back(NumInScalars+i);
11806         continue;
11807       }
11808
11809       // If extracting from the first vector, just use the index directly.
11810       SDValue Extract = N->getOperand(i);
11811       SDValue ExtVal = Extract.getOperand(1);
11812       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11813       if (Extract.getOperand(0) == VecIn1) {
11814         Mask.push_back(ExtIndex);
11815         continue;
11816       }
11817
11818       // Otherwise, use InIdx + InputVecSize
11819       Mask.push_back(InNumElements + ExtIndex);
11820     }
11821
11822     // Avoid introducing illegal shuffles with zero.
11823     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11824       return SDValue();
11825
11826     // We can't generate a shuffle node with mismatched input and output types.
11827     // Attempt to transform a single input vector to the correct type.
11828     if ((VT != VecIn1.getValueType())) {
11829       // If the input vector type has a different base type to the output
11830       // vector type, bail out.
11831       EVT VTElemType = VT.getVectorElementType();
11832       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11833           (VecIn2.getNode() &&
11834            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11835         return SDValue();
11836
11837       // If the input vector is too small, widen it.
11838       // We only support widening of vectors which are half the size of the
11839       // output registers. For example XMM->YMM widening on X86 with AVX.
11840       EVT VecInT = VecIn1.getValueType();
11841       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11842         // If we only have one small input, widen it by adding undef values.
11843         if (!VecIn2.getNode())
11844           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11845                                DAG.getUNDEF(VecIn1.getValueType()));
11846         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11847           // If we have two small inputs of the same type, try to concat them.
11848           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11849           VecIn2 = SDValue(nullptr, 0);
11850         } else
11851           return SDValue();
11852       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11853         // If the input vector is too large, try to split it.
11854         // We don't support having two input vectors that are too large.
11855         // If the zero vector was used, we can not split the vector,
11856         // since we'd need 3 inputs.
11857         if (UsesZeroVector || VecIn2.getNode())
11858           return SDValue();
11859
11860         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11861           return SDValue();
11862
11863         // Try to replace VecIn1 with two extract_subvectors
11864         // No need to update the masks, they should still be correct.
11865         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11866           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11867         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11868           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11869       } else
11870         return SDValue();
11871     }
11872
11873     if (UsesZeroVector)
11874       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11875                                 DAG.getConstantFP(0.0, dl, VT);
11876     else
11877       // If VecIn2 is unused then change it to undef.
11878       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11879
11880     // Check that we were able to transform all incoming values to the same
11881     // type.
11882     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11883         VecIn1.getValueType() != VT)
11884           return SDValue();
11885
11886     // Return the new VECTOR_SHUFFLE node.
11887     SDValue Ops[2];
11888     Ops[0] = VecIn1;
11889     Ops[1] = VecIn2;
11890     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11891   }
11892
11893   return SDValue();
11894 }
11895
11896 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11897   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11898   EVT OpVT = N->getOperand(0).getValueType();
11899
11900   // If the operands are legal vectors, leave them alone.
11901   if (TLI.isTypeLegal(OpVT))
11902     return SDValue();
11903
11904   SDLoc DL(N);
11905   EVT VT = N->getValueType(0);
11906   SmallVector<SDValue, 8> Ops;
11907
11908   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11909   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11910
11911   // Keep track of what we encounter.
11912   bool AnyInteger = false;
11913   bool AnyFP = false;
11914   for (const SDValue &Op : N->ops()) {
11915     if (ISD::BITCAST == Op.getOpcode() &&
11916         !Op.getOperand(0).getValueType().isVector())
11917       Ops.push_back(Op.getOperand(0));
11918     else if (ISD::UNDEF == Op.getOpcode())
11919       Ops.push_back(ScalarUndef);
11920     else
11921       return SDValue();
11922
11923     // Note whether we encounter an integer or floating point scalar.
11924     // If it's neither, bail out, it could be something weird like x86mmx.
11925     EVT LastOpVT = Ops.back().getValueType();
11926     if (LastOpVT.isFloatingPoint())
11927       AnyFP = true;
11928     else if (LastOpVT.isInteger())
11929       AnyInteger = true;
11930     else
11931       return SDValue();
11932   }
11933
11934   // If any of the operands is a floating point scalar bitcast to a vector,
11935   // use floating point types throughout, and bitcast everything.  
11936   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11937   if (AnyFP) {
11938     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11939     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11940     if (AnyInteger) {
11941       for (SDValue &Op : Ops) {
11942         if (Op.getValueType() == SVT)
11943           continue;
11944         if (Op.getOpcode() == ISD::UNDEF)
11945           Op = ScalarUndef;
11946         else
11947           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11948       }
11949     }
11950   }
11951
11952   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11953                                VT.getSizeInBits() / SVT.getSizeInBits());
11954   return DAG.getNode(ISD::BITCAST, DL, VT,
11955                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11956 }
11957
11958 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11959   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11960   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11961   // inputs come from at most two distinct vectors, turn this into a shuffle
11962   // node.
11963
11964   // If we only have one input vector, we don't need to do any concatenation.
11965   if (N->getNumOperands() == 1)
11966     return N->getOperand(0);
11967
11968   // Check if all of the operands are undefs.
11969   EVT VT = N->getValueType(0);
11970   if (ISD::allOperandsUndef(N))
11971     return DAG.getUNDEF(VT);
11972
11973   // Optimize concat_vectors where all but the first of the vectors are undef.
11974   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11975         return Op.getOpcode() == ISD::UNDEF;
11976       })) {
11977     SDValue In = N->getOperand(0);
11978     assert(In.getValueType().isVector() && "Must concat vectors");
11979
11980     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11981     if (In->getOpcode() == ISD::BITCAST &&
11982         !In->getOperand(0)->getValueType(0).isVector()) {
11983       SDValue Scalar = In->getOperand(0);
11984
11985       // If the bitcast type isn't legal, it might be a trunc of a legal type;
11986       // look through the trunc so we can still do the transform:
11987       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11988       if (Scalar->getOpcode() == ISD::TRUNCATE &&
11989           !TLI.isTypeLegal(Scalar.getValueType()) &&
11990           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11991         Scalar = Scalar->getOperand(0);
11992
11993       EVT SclTy = Scalar->getValueType(0);
11994
11995       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11996         return SDValue();
11997
11998       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11999                                  VT.getSizeInBits() / SclTy.getSizeInBits());
12000       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
12001         return SDValue();
12002
12003       SDLoc dl = SDLoc(N);
12004       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
12005       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
12006     }
12007   }
12008
12009   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12010   // We have already tested above for an UNDEF only concatenation.
12011   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12012   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12013   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12014     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12015   };
12016   bool AllBuildVectorsOrUndefs =
12017       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12018   if (AllBuildVectorsOrUndefs) {
12019     SmallVector<SDValue, 8> Opnds;
12020     EVT SVT = VT.getScalarType();
12021
12022     EVT MinVT = SVT;
12023     if (!SVT.isFloatingPoint()) {
12024       // If BUILD_VECTOR are from built from integer, they may have different
12025       // operand types. Get the smallest type and truncate all operands to it.
12026       bool FoundMinVT = false;
12027       for (const SDValue &Op : N->ops())
12028         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12029           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12030           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12031           FoundMinVT = true;
12032         }
12033       assert(FoundMinVT && "Concat vector type mismatch");
12034     }
12035
12036     for (const SDValue &Op : N->ops()) {
12037       EVT OpVT = Op.getValueType();
12038       unsigned NumElts = OpVT.getVectorNumElements();
12039
12040       if (ISD::UNDEF == Op.getOpcode())
12041         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12042
12043       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12044         if (SVT.isFloatingPoint()) {
12045           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12046           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12047         } else {
12048           for (unsigned i = 0; i != NumElts; ++i)
12049             Opnds.push_back(
12050                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12051         }
12052       }
12053     }
12054
12055     assert(VT.getVectorNumElements() == Opnds.size() &&
12056            "Concat vector type mismatch");
12057     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12058   }
12059
12060   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12061   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12062     return V;
12063
12064   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12065   // nodes often generate nop CONCAT_VECTOR nodes.
12066   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12067   // place the incoming vectors at the exact same location.
12068   SDValue SingleSource = SDValue();
12069   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12070
12071   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12072     SDValue Op = N->getOperand(i);
12073
12074     if (Op.getOpcode() == ISD::UNDEF)
12075       continue;
12076
12077     // Check if this is the identity extract:
12078     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12079       return SDValue();
12080
12081     // Find the single incoming vector for the extract_subvector.
12082     if (SingleSource.getNode()) {
12083       if (Op.getOperand(0) != SingleSource)
12084         return SDValue();
12085     } else {
12086       SingleSource = Op.getOperand(0);
12087
12088       // Check the source type is the same as the type of the result.
12089       // If not, this concat may extend the vector, so we can not
12090       // optimize it away.
12091       if (SingleSource.getValueType() != N->getValueType(0))
12092         return SDValue();
12093     }
12094
12095     unsigned IdentityIndex = i * PartNumElem;
12096     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12097     // The extract index must be constant.
12098     if (!CS)
12099       return SDValue();
12100
12101     // Check that we are reading from the identity index.
12102     if (CS->getZExtValue() != IdentityIndex)
12103       return SDValue();
12104   }
12105
12106   if (SingleSource.getNode())
12107     return SingleSource;
12108
12109   return SDValue();
12110 }
12111
12112 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12113   EVT NVT = N->getValueType(0);
12114   SDValue V = N->getOperand(0);
12115
12116   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12117     // Combine:
12118     //    (extract_subvec (concat V1, V2, ...), i)
12119     // Into:
12120     //    Vi if possible
12121     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12122     // type.
12123     if (V->getOperand(0).getValueType() != NVT)
12124       return SDValue();
12125     unsigned Idx = N->getConstantOperandVal(1);
12126     unsigned NumElems = NVT.getVectorNumElements();
12127     assert((Idx % NumElems) == 0 &&
12128            "IDX in concat is not a multiple of the result vector length.");
12129     return V->getOperand(Idx / NumElems);
12130   }
12131
12132   // Skip bitcasting
12133   if (V->getOpcode() == ISD::BITCAST)
12134     V = V.getOperand(0);
12135
12136   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12137     SDLoc dl(N);
12138     // Handle only simple case where vector being inserted and vector
12139     // being extracted are of same type, and are half size of larger vectors.
12140     EVT BigVT = V->getOperand(0).getValueType();
12141     EVT SmallVT = V->getOperand(1).getValueType();
12142     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12143       return SDValue();
12144
12145     // Only handle cases where both indexes are constants with the same type.
12146     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12147     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12148
12149     if (InsIdx && ExtIdx &&
12150         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12151         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12152       // Combine:
12153       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12154       // Into:
12155       //    indices are equal or bit offsets are equal => V1
12156       //    otherwise => (extract_subvec V1, ExtIdx)
12157       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12158           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12159         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12160       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12161                          DAG.getNode(ISD::BITCAST, dl,
12162                                      N->getOperand(0).getValueType(),
12163                                      V->getOperand(0)), N->getOperand(1));
12164     }
12165   }
12166
12167   return SDValue();
12168 }
12169
12170 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12171                                                  SDValue V, SelectionDAG &DAG) {
12172   SDLoc DL(V);
12173   EVT VT = V.getValueType();
12174
12175   switch (V.getOpcode()) {
12176   default:
12177     return V;
12178
12179   case ISD::CONCAT_VECTORS: {
12180     EVT OpVT = V->getOperand(0).getValueType();
12181     int OpSize = OpVT.getVectorNumElements();
12182     SmallBitVector OpUsedElements(OpSize, false);
12183     bool FoundSimplification = false;
12184     SmallVector<SDValue, 4> NewOps;
12185     NewOps.reserve(V->getNumOperands());
12186     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12187       SDValue Op = V->getOperand(i);
12188       bool OpUsed = false;
12189       for (int j = 0; j < OpSize; ++j)
12190         if (UsedElements[i * OpSize + j]) {
12191           OpUsedElements[j] = true;
12192           OpUsed = true;
12193         }
12194       NewOps.push_back(
12195           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12196                  : DAG.getUNDEF(OpVT));
12197       FoundSimplification |= Op == NewOps.back();
12198       OpUsedElements.reset();
12199     }
12200     if (FoundSimplification)
12201       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12202     return V;
12203   }
12204
12205   case ISD::INSERT_SUBVECTOR: {
12206     SDValue BaseV = V->getOperand(0);
12207     SDValue SubV = V->getOperand(1);
12208     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12209     if (!IdxN)
12210       return V;
12211
12212     int SubSize = SubV.getValueType().getVectorNumElements();
12213     int Idx = IdxN->getZExtValue();
12214     bool SubVectorUsed = false;
12215     SmallBitVector SubUsedElements(SubSize, false);
12216     for (int i = 0; i < SubSize; ++i)
12217       if (UsedElements[i + Idx]) {
12218         SubVectorUsed = true;
12219         SubUsedElements[i] = true;
12220         UsedElements[i + Idx] = false;
12221       }
12222
12223     // Now recurse on both the base and sub vectors.
12224     SDValue SimplifiedSubV =
12225         SubVectorUsed
12226             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12227             : DAG.getUNDEF(SubV.getValueType());
12228     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12229     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12230       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12231                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12232     return V;
12233   }
12234   }
12235 }
12236
12237 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12238                                        SDValue N1, SelectionDAG &DAG) {
12239   EVT VT = SVN->getValueType(0);
12240   int NumElts = VT.getVectorNumElements();
12241   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12242   for (int M : SVN->getMask())
12243     if (M >= 0 && M < NumElts)
12244       N0UsedElements[M] = true;
12245     else if (M >= NumElts)
12246       N1UsedElements[M - NumElts] = true;
12247
12248   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12249   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12250   if (S0 == N0 && S1 == N1)
12251     return SDValue();
12252
12253   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12254 }
12255
12256 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12257 // or turn a shuffle of a single concat into simpler shuffle then concat.
12258 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12259   EVT VT = N->getValueType(0);
12260   unsigned NumElts = VT.getVectorNumElements();
12261
12262   SDValue N0 = N->getOperand(0);
12263   SDValue N1 = N->getOperand(1);
12264   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12265
12266   SmallVector<SDValue, 4> Ops;
12267   EVT ConcatVT = N0.getOperand(0).getValueType();
12268   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12269   unsigned NumConcats = NumElts / NumElemsPerConcat;
12270
12271   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12272   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12273   // half vector elements.
12274   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12275       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12276                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12277     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12278                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12279     N1 = DAG.getUNDEF(ConcatVT);
12280     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12281   }
12282
12283   // Look at every vector that's inserted. We're looking for exact
12284   // subvector-sized copies from a concatenated vector
12285   for (unsigned I = 0; I != NumConcats; ++I) {
12286     // Make sure we're dealing with a copy.
12287     unsigned Begin = I * NumElemsPerConcat;
12288     bool AllUndef = true, NoUndef = true;
12289     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12290       if (SVN->getMaskElt(J) >= 0)
12291         AllUndef = false;
12292       else
12293         NoUndef = false;
12294     }
12295
12296     if (NoUndef) {
12297       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12298         return SDValue();
12299
12300       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12301         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12302           return SDValue();
12303
12304       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12305       if (FirstElt < N0.getNumOperands())
12306         Ops.push_back(N0.getOperand(FirstElt));
12307       else
12308         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12309
12310     } else if (AllUndef) {
12311       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12312     } else { // Mixed with general masks and undefs, can't do optimization.
12313       return SDValue();
12314     }
12315   }
12316
12317   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12318 }
12319
12320 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12321   EVT VT = N->getValueType(0);
12322   unsigned NumElts = VT.getVectorNumElements();
12323
12324   SDValue N0 = N->getOperand(0);
12325   SDValue N1 = N->getOperand(1);
12326
12327   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12328
12329   // Canonicalize shuffle undef, undef -> undef
12330   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12331     return DAG.getUNDEF(VT);
12332
12333   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12334
12335   // Canonicalize shuffle v, v -> v, undef
12336   if (N0 == N1) {
12337     SmallVector<int, 8> NewMask;
12338     for (unsigned i = 0; i != NumElts; ++i) {
12339       int Idx = SVN->getMaskElt(i);
12340       if (Idx >= (int)NumElts) Idx -= NumElts;
12341       NewMask.push_back(Idx);
12342     }
12343     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12344                                 &NewMask[0]);
12345   }
12346
12347   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12348   if (N0.getOpcode() == ISD::UNDEF) {
12349     SmallVector<int, 8> NewMask;
12350     for (unsigned i = 0; i != NumElts; ++i) {
12351       int Idx = SVN->getMaskElt(i);
12352       if (Idx >= 0) {
12353         if (Idx >= (int)NumElts)
12354           Idx -= NumElts;
12355         else
12356           Idx = -1; // remove reference to lhs
12357       }
12358       NewMask.push_back(Idx);
12359     }
12360     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12361                                 &NewMask[0]);
12362   }
12363
12364   // Remove references to rhs if it is undef
12365   if (N1.getOpcode() == ISD::UNDEF) {
12366     bool Changed = false;
12367     SmallVector<int, 8> NewMask;
12368     for (unsigned i = 0; i != NumElts; ++i) {
12369       int Idx = SVN->getMaskElt(i);
12370       if (Idx >= (int)NumElts) {
12371         Idx = -1;
12372         Changed = true;
12373       }
12374       NewMask.push_back(Idx);
12375     }
12376     if (Changed)
12377       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12378   }
12379
12380   // If it is a splat, check if the argument vector is another splat or a
12381   // build_vector.
12382   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12383     SDNode *V = N0.getNode();
12384
12385     // If this is a bit convert that changes the element type of the vector but
12386     // not the number of vector elements, look through it.  Be careful not to
12387     // look though conversions that change things like v4f32 to v2f64.
12388     if (V->getOpcode() == ISD::BITCAST) {
12389       SDValue ConvInput = V->getOperand(0);
12390       if (ConvInput.getValueType().isVector() &&
12391           ConvInput.getValueType().getVectorNumElements() == NumElts)
12392         V = ConvInput.getNode();
12393     }
12394
12395     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12396       assert(V->getNumOperands() == NumElts &&
12397              "BUILD_VECTOR has wrong number of operands");
12398       SDValue Base;
12399       bool AllSame = true;
12400       for (unsigned i = 0; i != NumElts; ++i) {
12401         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12402           Base = V->getOperand(i);
12403           break;
12404         }
12405       }
12406       // Splat of <u, u, u, u>, return <u, u, u, u>
12407       if (!Base.getNode())
12408         return N0;
12409       for (unsigned i = 0; i != NumElts; ++i) {
12410         if (V->getOperand(i) != Base) {
12411           AllSame = false;
12412           break;
12413         }
12414       }
12415       // Splat of <x, x, x, x>, return <x, x, x, x>
12416       if (AllSame)
12417         return N0;
12418
12419       // Canonicalize any other splat as a build_vector.
12420       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12421       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12422       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12423                                   V->getValueType(0), Ops);
12424
12425       // We may have jumped through bitcasts, so the type of the
12426       // BUILD_VECTOR may not match the type of the shuffle.
12427       if (V->getValueType(0) != VT)
12428         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12429       return NewBV;
12430     }
12431   }
12432
12433   // There are various patterns used to build up a vector from smaller vectors,
12434   // subvectors, or elements. Scan chains of these and replace unused insertions
12435   // or components with undef.
12436   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12437     return S;
12438
12439   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12440       Level < AfterLegalizeVectorOps &&
12441       (N1.getOpcode() == ISD::UNDEF ||
12442       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12443        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12444     SDValue V = partitionShuffleOfConcats(N, DAG);
12445
12446     if (V.getNode())
12447       return V;
12448   }
12449
12450   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12451   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12452   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12453     SmallVector<SDValue, 8> Ops;
12454     for (int M : SVN->getMask()) {
12455       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12456       if (M >= 0) {
12457         int Idx = M % NumElts;
12458         SDValue &S = (M < (int)NumElts ? N0 : N1);
12459         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12460           Op = S.getOperand(Idx);
12461         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12462           if (Idx == 0)
12463             Op = S.getOperand(0);
12464         } else {
12465           // Operand can't be combined - bail out.
12466           break;
12467         }
12468       }
12469       Ops.push_back(Op);
12470     }
12471     if (Ops.size() == VT.getVectorNumElements()) {
12472       // BUILD_VECTOR requires all inputs to be of the same type, find the
12473       // maximum type and extend them all.
12474       EVT SVT = VT.getScalarType();
12475       if (SVT.isInteger())
12476         for (SDValue &Op : Ops)
12477           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12478       if (SVT != VT.getScalarType())
12479         for (SDValue &Op : Ops)
12480           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12481                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12482                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12483       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12484     }
12485   }
12486
12487   // If this shuffle only has a single input that is a bitcasted shuffle,
12488   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12489   // back to their original types.
12490   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12491       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12492       TLI.isTypeLegal(VT)) {
12493
12494     // Peek through the bitcast only if there is one user.
12495     SDValue BC0 = N0;
12496     while (BC0.getOpcode() == ISD::BITCAST) {
12497       if (!BC0.hasOneUse())
12498         break;
12499       BC0 = BC0.getOperand(0);
12500     }
12501
12502     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12503       if (Scale == 1)
12504         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12505
12506       SmallVector<int, 8> NewMask;
12507       for (int M : Mask)
12508         for (int s = 0; s != Scale; ++s)
12509           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12510       return NewMask;
12511     };
12512
12513     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12514       EVT SVT = VT.getScalarType();
12515       EVT InnerVT = BC0->getValueType(0);
12516       EVT InnerSVT = InnerVT.getScalarType();
12517
12518       // Determine which shuffle works with the smaller scalar type.
12519       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12520       EVT ScaleSVT = ScaleVT.getScalarType();
12521
12522       if (TLI.isTypeLegal(ScaleVT) &&
12523           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12524           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12525
12526         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12527         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12528
12529         // Scale the shuffle masks to the smaller scalar type.
12530         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12531         SmallVector<int, 8> InnerMask =
12532             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12533         SmallVector<int, 8> OuterMask =
12534             ScaleShuffleMask(SVN->getMask(), OuterScale);
12535
12536         // Merge the shuffle masks.
12537         SmallVector<int, 8> NewMask;
12538         for (int M : OuterMask)
12539           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12540
12541         // Test for shuffle mask legality over both commutations.
12542         SDValue SV0 = BC0->getOperand(0);
12543         SDValue SV1 = BC0->getOperand(1);
12544         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12545         if (!LegalMask) {
12546           std::swap(SV0, SV1);
12547           ShuffleVectorSDNode::commuteMask(NewMask);
12548           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12549         }
12550
12551         if (LegalMask) {
12552           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12553           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12554           return DAG.getNode(
12555               ISD::BITCAST, SDLoc(N), VT,
12556               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12557         }
12558       }
12559     }
12560   }
12561
12562   // Canonicalize shuffles according to rules:
12563   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12564   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12565   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12566   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12567       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12568       TLI.isTypeLegal(VT)) {
12569     // The incoming shuffle must be of the same type as the result of the
12570     // current shuffle.
12571     assert(N1->getOperand(0).getValueType() == VT &&
12572            "Shuffle types don't match");
12573
12574     SDValue SV0 = N1->getOperand(0);
12575     SDValue SV1 = N1->getOperand(1);
12576     bool HasSameOp0 = N0 == SV0;
12577     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12578     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12579       // Commute the operands of this shuffle so that next rule
12580       // will trigger.
12581       return DAG.getCommutedVectorShuffle(*SVN);
12582   }
12583
12584   // Try to fold according to rules:
12585   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12586   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12587   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12588   // Don't try to fold shuffles with illegal type.
12589   // Only fold if this shuffle is the only user of the other shuffle.
12590   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12591       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12592     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12593
12594     // The incoming shuffle must be of the same type as the result of the
12595     // current shuffle.
12596     assert(OtherSV->getOperand(0).getValueType() == VT &&
12597            "Shuffle types don't match");
12598
12599     SDValue SV0, SV1;
12600     SmallVector<int, 4> Mask;
12601     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12602     // operand, and SV1 as the second operand.
12603     for (unsigned i = 0; i != NumElts; ++i) {
12604       int Idx = SVN->getMaskElt(i);
12605       if (Idx < 0) {
12606         // Propagate Undef.
12607         Mask.push_back(Idx);
12608         continue;
12609       }
12610
12611       SDValue CurrentVec;
12612       if (Idx < (int)NumElts) {
12613         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12614         // shuffle mask to identify which vector is actually referenced.
12615         Idx = OtherSV->getMaskElt(Idx);
12616         if (Idx < 0) {
12617           // Propagate Undef.
12618           Mask.push_back(Idx);
12619           continue;
12620         }
12621
12622         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12623                                            : OtherSV->getOperand(1);
12624       } else {
12625         // This shuffle index references an element within N1.
12626         CurrentVec = N1;
12627       }
12628
12629       // Simple case where 'CurrentVec' is UNDEF.
12630       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12631         Mask.push_back(-1);
12632         continue;
12633       }
12634
12635       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12636       // will be the first or second operand of the combined shuffle.
12637       Idx = Idx % NumElts;
12638       if (!SV0.getNode() || SV0 == CurrentVec) {
12639         // Ok. CurrentVec is the left hand side.
12640         // Update the mask accordingly.
12641         SV0 = CurrentVec;
12642         Mask.push_back(Idx);
12643         continue;
12644       }
12645
12646       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12647       if (SV1.getNode() && SV1 != CurrentVec)
12648         return SDValue();
12649
12650       // Ok. CurrentVec is the right hand side.
12651       // Update the mask accordingly.
12652       SV1 = CurrentVec;
12653       Mask.push_back(Idx + NumElts);
12654     }
12655
12656     // Check if all indices in Mask are Undef. In case, propagate Undef.
12657     bool isUndefMask = true;
12658     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12659       isUndefMask &= Mask[i] < 0;
12660
12661     if (isUndefMask)
12662       return DAG.getUNDEF(VT);
12663
12664     if (!SV0.getNode())
12665       SV0 = DAG.getUNDEF(VT);
12666     if (!SV1.getNode())
12667       SV1 = DAG.getUNDEF(VT);
12668
12669     // Avoid introducing shuffles with illegal mask.
12670     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12671       ShuffleVectorSDNode::commuteMask(Mask);
12672
12673       if (!TLI.isShuffleMaskLegal(Mask, VT))
12674         return SDValue();
12675
12676       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12677       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12678       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12679       std::swap(SV0, SV1);
12680     }
12681
12682     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12683     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12684     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12685     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12686   }
12687
12688   return SDValue();
12689 }
12690
12691 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12692   SDValue InVal = N->getOperand(0);
12693   EVT VT = N->getValueType(0);
12694
12695   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12696   // with a VECTOR_SHUFFLE.
12697   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12698     SDValue InVec = InVal->getOperand(0);
12699     SDValue EltNo = InVal->getOperand(1);
12700
12701     // FIXME: We could support implicit truncation if the shuffle can be
12702     // scaled to a smaller vector scalar type.
12703     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12704     if (C0 && VT == InVec.getValueType() &&
12705         VT.getScalarType() == InVal.getValueType()) {
12706       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12707       int Elt = C0->getZExtValue();
12708       NewMask[0] = Elt;
12709
12710       if (TLI.isShuffleMaskLegal(NewMask, VT))
12711         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12712                                     NewMask);
12713     }
12714   }
12715
12716   return SDValue();
12717 }
12718
12719 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12720   SDValue N0 = N->getOperand(0);
12721   SDValue N2 = N->getOperand(2);
12722
12723   // If the input vector is a concatenation, and the insert replaces
12724   // one of the halves, we can optimize into a single concat_vectors.
12725   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12726       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12727     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12728     EVT VT = N->getValueType(0);
12729
12730     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12731     // (concat_vectors Z, Y)
12732     if (InsIdx == 0)
12733       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12734                          N->getOperand(1), N0.getOperand(1));
12735
12736     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12737     // (concat_vectors X, Z)
12738     if (InsIdx == VT.getVectorNumElements()/2)
12739       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12740                          N0.getOperand(0), N->getOperand(1));
12741   }
12742
12743   return SDValue();
12744 }
12745
12746 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12747   SDValue N0 = N->getOperand(0);
12748
12749   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12750   if (N0->getOpcode() == ISD::FP16_TO_FP)
12751     return N0->getOperand(0);
12752
12753   return SDValue();
12754 }
12755
12756 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12757 /// with the destination vector and a zero vector.
12758 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12759 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12760 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12761   EVT VT = N->getValueType(0);
12762   SDValue LHS = N->getOperand(0);
12763   SDValue RHS = N->getOperand(1);
12764   SDLoc dl(N);
12765
12766   // Make sure we're not running after operation legalization where it 
12767   // may have custom lowered the vector shuffles.
12768   if (LegalOperations)
12769     return SDValue();
12770
12771   if (N->getOpcode() != ISD::AND)
12772     return SDValue();
12773
12774   if (RHS.getOpcode() == ISD::BITCAST)
12775     RHS = RHS.getOperand(0);
12776
12777   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12778     SmallVector<int, 8> Indices;
12779     unsigned NumElts = RHS.getNumOperands();
12780
12781     for (unsigned i = 0; i != NumElts; ++i) {
12782       SDValue Elt = RHS.getOperand(i);
12783       if (!isa<ConstantSDNode>(Elt))
12784         return SDValue();
12785
12786       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12787         Indices.push_back(i);
12788       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12789         Indices.push_back(NumElts+i);
12790       else
12791         return SDValue();
12792     }
12793
12794     // Let's see if the target supports this vector_shuffle.
12795     EVT RVT = RHS.getValueType();
12796     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12797       return SDValue();
12798
12799     // Return the new VECTOR_SHUFFLE node.
12800     EVT EltVT = RVT.getVectorElementType();
12801     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12802                                    DAG.getConstant(0, dl, EltVT));
12803     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12804     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12805     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12806     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12807   }
12808
12809   return SDValue();
12810 }
12811
12812 /// Visit a binary vector operation, like ADD.
12813 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12814   assert(N->getValueType(0).isVector() &&
12815          "SimplifyVBinOp only works on vectors!");
12816
12817   SDValue LHS = N->getOperand(0);
12818   SDValue RHS = N->getOperand(1);
12819
12820   if (SDValue Shuffle = XformToShuffleWithZero(N))
12821     return Shuffle;
12822
12823   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12824   // this operation.
12825   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12826       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12827     // Check if both vectors are constants. If not bail out.
12828     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12829           cast<BuildVectorSDNode>(RHS)->isConstant()))
12830       return SDValue();
12831
12832     SmallVector<SDValue, 8> Ops;
12833     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12834       SDValue LHSOp = LHS.getOperand(i);
12835       SDValue RHSOp = RHS.getOperand(i);
12836
12837       // Can't fold divide by zero.
12838       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12839           N->getOpcode() == ISD::FDIV) {
12840         if ((RHSOp.getOpcode() == ISD::Constant &&
12841              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12842             (RHSOp.getOpcode() == ISD::ConstantFP &&
12843              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12844           break;
12845       }
12846
12847       EVT VT = LHSOp.getValueType();
12848       EVT RVT = RHSOp.getValueType();
12849       if (RVT != VT) {
12850         // Integer BUILD_VECTOR operands may have types larger than the element
12851         // size (e.g., when the element type is not legal).  Prior to type
12852         // legalization, the types may not match between the two BUILD_VECTORS.
12853         // Truncate one of the operands to make them match.
12854         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12855           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12856         } else {
12857           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12858           VT = RVT;
12859         }
12860       }
12861       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12862                                    LHSOp, RHSOp);
12863       if (FoldOp.getOpcode() != ISD::UNDEF &&
12864           FoldOp.getOpcode() != ISD::Constant &&
12865           FoldOp.getOpcode() != ISD::ConstantFP)
12866         break;
12867       Ops.push_back(FoldOp);
12868       AddToWorklist(FoldOp.getNode());
12869     }
12870
12871     if (Ops.size() == LHS.getNumOperands())
12872       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12873   }
12874
12875   // Type legalization might introduce new shuffles in the DAG.
12876   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12877   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12878   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12879       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12880       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12881       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12882     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12883     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12884
12885     if (SVN0->getMask().equals(SVN1->getMask())) {
12886       EVT VT = N->getValueType(0);
12887       SDValue UndefVector = LHS.getOperand(1);
12888       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12889                                      LHS.getOperand(0), RHS.getOperand(0));
12890       AddUsersToWorklist(N);
12891       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12892                                   &SVN0->getMask()[0]);
12893     }
12894   }
12895
12896   return SDValue();
12897 }
12898
12899 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12900                                     SDValue N1, SDValue N2){
12901   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12902
12903   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12904                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12905
12906   // If we got a simplified select_cc node back from SimplifySelectCC, then
12907   // break it down into a new SETCC node, and a new SELECT node, and then return
12908   // the SELECT node, since we were called with a SELECT node.
12909   if (SCC.getNode()) {
12910     // Check to see if we got a select_cc back (to turn into setcc/select).
12911     // Otherwise, just return whatever node we got back, like fabs.
12912     if (SCC.getOpcode() == ISD::SELECT_CC) {
12913       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12914                                   N0.getValueType(),
12915                                   SCC.getOperand(0), SCC.getOperand(1),
12916                                   SCC.getOperand(4));
12917       AddToWorklist(SETCC.getNode());
12918       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12919                            SCC.getOperand(2), SCC.getOperand(3));
12920     }
12921
12922     return SCC;
12923   }
12924   return SDValue();
12925 }
12926
12927 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12928 /// being selected between, see if we can simplify the select.  Callers of this
12929 /// should assume that TheSelect is deleted if this returns true.  As such, they
12930 /// should return the appropriate thing (e.g. the node) back to the top-level of
12931 /// the DAG combiner loop to avoid it being looked at.
12932 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12933                                     SDValue RHS) {
12934
12935   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12936   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12937   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12938     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12939       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12940       SDValue Sqrt = RHS;
12941       ISD::CondCode CC;
12942       SDValue CmpLHS;
12943       const ConstantFPSDNode *NegZero = nullptr;
12944
12945       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12946         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12947         CmpLHS = TheSelect->getOperand(0);
12948         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12949       } else {
12950         // SELECT or VSELECT
12951         SDValue Cmp = TheSelect->getOperand(0);
12952         if (Cmp.getOpcode() == ISD::SETCC) {
12953           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12954           CmpLHS = Cmp.getOperand(0);
12955           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12956         }
12957       }
12958       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12959           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12960           CC == ISD::SETULT || CC == ISD::SETLT)) {
12961         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12962         CombineTo(TheSelect, Sqrt);
12963         return true;
12964       }
12965     }
12966   }
12967   // Cannot simplify select with vector condition
12968   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12969
12970   // If this is a select from two identical things, try to pull the operation
12971   // through the select.
12972   if (LHS.getOpcode() != RHS.getOpcode() ||
12973       !LHS.hasOneUse() || !RHS.hasOneUse())
12974     return false;
12975
12976   // If this is a load and the token chain is identical, replace the select
12977   // of two loads with a load through a select of the address to load from.
12978   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12979   // constants have been dropped into the constant pool.
12980   if (LHS.getOpcode() == ISD::LOAD) {
12981     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12982     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12983
12984     // Token chains must be identical.
12985     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12986         // Do not let this transformation reduce the number of volatile loads.
12987         LLD->isVolatile() || RLD->isVolatile() ||
12988         // FIXME: If either is a pre/post inc/dec load,
12989         // we'd need to split out the address adjustment.
12990         LLD->isIndexed() || RLD->isIndexed() ||
12991         // If this is an EXTLOAD, the VT's must match.
12992         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12993         // If this is an EXTLOAD, the kind of extension must match.
12994         (LLD->getExtensionType() != RLD->getExtensionType() &&
12995          // The only exception is if one of the extensions is anyext.
12996          LLD->getExtensionType() != ISD::EXTLOAD &&
12997          RLD->getExtensionType() != ISD::EXTLOAD) ||
12998         // FIXME: this discards src value information.  This is
12999         // over-conservative. It would be beneficial to be able to remember
13000         // both potential memory locations.  Since we are discarding
13001         // src value info, don't do the transformation if the memory
13002         // locations are not in the default address space.
13003         LLD->getPointerInfo().getAddrSpace() != 0 ||
13004         RLD->getPointerInfo().getAddrSpace() != 0 ||
13005         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
13006                                       LLD->getBasePtr().getValueType()))
13007       return false;
13008
13009     // Check that the select condition doesn't reach either load.  If so,
13010     // folding this will induce a cycle into the DAG.  If not, this is safe to
13011     // xform, so create a select of the addresses.
13012     SDValue Addr;
13013     if (TheSelect->getOpcode() == ISD::SELECT) {
13014       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13015       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13016           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13017         return false;
13018       // The loads must not depend on one another.
13019       if (LLD->isPredecessorOf(RLD) ||
13020           RLD->isPredecessorOf(LLD))
13021         return false;
13022       Addr = DAG.getSelect(SDLoc(TheSelect),
13023                            LLD->getBasePtr().getValueType(),
13024                            TheSelect->getOperand(0), LLD->getBasePtr(),
13025                            RLD->getBasePtr());
13026     } else {  // Otherwise SELECT_CC
13027       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13028       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13029
13030       if ((LLD->hasAnyUseOfValue(1) &&
13031            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13032           (RLD->hasAnyUseOfValue(1) &&
13033            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13034         return false;
13035
13036       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13037                          LLD->getBasePtr().getValueType(),
13038                          TheSelect->getOperand(0),
13039                          TheSelect->getOperand(1),
13040                          LLD->getBasePtr(), RLD->getBasePtr(),
13041                          TheSelect->getOperand(4));
13042     }
13043
13044     SDValue Load;
13045     // It is safe to replace the two loads if they have different alignments,
13046     // but the new load must be the minimum (most restrictive) alignment of the
13047     // inputs.
13048     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13049     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13050     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13051       Load = DAG.getLoad(TheSelect->getValueType(0),
13052                          SDLoc(TheSelect),
13053                          // FIXME: Discards pointer and AA info.
13054                          LLD->getChain(), Addr, MachinePointerInfo(),
13055                          LLD->isVolatile(), LLD->isNonTemporal(),
13056                          isInvariant, Alignment);
13057     } else {
13058       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13059                             RLD->getExtensionType() : LLD->getExtensionType(),
13060                             SDLoc(TheSelect),
13061                             TheSelect->getValueType(0),
13062                             // FIXME: Discards pointer and AA info.
13063                             LLD->getChain(), Addr, MachinePointerInfo(),
13064                             LLD->getMemoryVT(), LLD->isVolatile(),
13065                             LLD->isNonTemporal(), isInvariant, Alignment);
13066     }
13067
13068     // Users of the select now use the result of the load.
13069     CombineTo(TheSelect, Load);
13070
13071     // Users of the old loads now use the new load's chain.  We know the
13072     // old-load value is dead now.
13073     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13074     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13075     return true;
13076   }
13077
13078   return false;
13079 }
13080
13081 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13082 /// where 'cond' is the comparison specified by CC.
13083 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13084                                       SDValue N2, SDValue N3,
13085                                       ISD::CondCode CC, bool NotExtCompare) {
13086   // (x ? y : y) -> y.
13087   if (N2 == N3) return N2;
13088
13089   EVT VT = N2.getValueType();
13090   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13091   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13092   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13093
13094   // Determine if the condition we're dealing with is constant
13095   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13096                               N0, N1, CC, DL, false);
13097   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13098   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13099
13100   // fold select_cc true, x, y -> x
13101   if (SCCC && !SCCC->isNullValue())
13102     return N2;
13103   // fold select_cc false, x, y -> y
13104   if (SCCC && SCCC->isNullValue())
13105     return N3;
13106
13107   // Check to see if we can simplify the select into an fabs node
13108   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13109     // Allow either -0.0 or 0.0
13110     if (CFP->getValueAPF().isZero()) {
13111       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13112       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13113           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13114           N2 == N3.getOperand(0))
13115         return DAG.getNode(ISD::FABS, DL, VT, N0);
13116
13117       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13118       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13119           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13120           N2.getOperand(0) == N3)
13121         return DAG.getNode(ISD::FABS, DL, VT, N3);
13122     }
13123   }
13124
13125   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13126   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13127   // in it.  This is a win when the constant is not otherwise available because
13128   // it replaces two constant pool loads with one.  We only do this if the FP
13129   // type is known to be legal, because if it isn't, then we are before legalize
13130   // types an we want the other legalization to happen first (e.g. to avoid
13131   // messing with soft float) and if the ConstantFP is not legal, because if
13132   // it is legal, we may not need to store the FP constant in a constant pool.
13133   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13134     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13135       if (TLI.isTypeLegal(N2.getValueType()) &&
13136           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13137                TargetLowering::Legal &&
13138            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13139            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13140           // If both constants have multiple uses, then we won't need to do an
13141           // extra load, they are likely around in registers for other users.
13142           (TV->hasOneUse() || FV->hasOneUse())) {
13143         Constant *Elts[] = {
13144           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13145           const_cast<ConstantFP*>(TV->getConstantFPValue())
13146         };
13147         Type *FPTy = Elts[0]->getType();
13148         const DataLayout &TD = *TLI.getDataLayout();
13149
13150         // Create a ConstantArray of the two constants.
13151         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13152         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13153                                             TD.getPrefTypeAlignment(FPTy));
13154         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13155
13156         // Get the offsets to the 0 and 1 element of the array so that we can
13157         // select between them.
13158         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13159         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13160         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13161
13162         SDValue Cond = DAG.getSetCC(DL,
13163                                     getSetCCResultType(N0.getValueType()),
13164                                     N0, N1, CC);
13165         AddToWorklist(Cond.getNode());
13166         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13167                                           Cond, One, Zero);
13168         AddToWorklist(CstOffset.getNode());
13169         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13170                             CstOffset);
13171         AddToWorklist(CPIdx.getNode());
13172         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13173                            MachinePointerInfo::getConstantPool(), false,
13174                            false, false, Alignment);
13175       }
13176     }
13177
13178   // Check to see if we can perform the "gzip trick", transforming
13179   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13180   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13181       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13182        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13183     EVT XType = N0.getValueType();
13184     EVT AType = N2.getValueType();
13185     if (XType.bitsGE(AType)) {
13186       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13187       // single-bit constant.
13188       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13189         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13190         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13191         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13192                                        getShiftAmountTy(N0.getValueType()));
13193         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13194                                     XType, N0, ShCt);
13195         AddToWorklist(Shift.getNode());
13196
13197         if (XType.bitsGT(AType)) {
13198           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13199           AddToWorklist(Shift.getNode());
13200         }
13201
13202         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13203       }
13204
13205       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13206                                   XType, N0,
13207                                   DAG.getConstant(XType.getSizeInBits() - 1,
13208                                                   SDLoc(N0),
13209                                          getShiftAmountTy(N0.getValueType())));
13210       AddToWorklist(Shift.getNode());
13211
13212       if (XType.bitsGT(AType)) {
13213         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13214         AddToWorklist(Shift.getNode());
13215       }
13216
13217       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13218     }
13219   }
13220
13221   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13222   // where y is has a single bit set.
13223   // A plaintext description would be, we can turn the SELECT_CC into an AND
13224   // when the condition can be materialized as an all-ones register.  Any
13225   // single bit-test can be materialized as an all-ones register with
13226   // shift-left and shift-right-arith.
13227   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13228       N0->getValueType(0) == VT &&
13229       N1C && N1C->isNullValue() &&
13230       N2C && N2C->isNullValue()) {
13231     SDValue AndLHS = N0->getOperand(0);
13232     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13233     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13234       // Shift the tested bit over the sign bit.
13235       APInt AndMask = ConstAndRHS->getAPIntValue();
13236       SDValue ShlAmt =
13237         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13238                         getShiftAmountTy(AndLHS.getValueType()));
13239       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13240
13241       // Now arithmetic right shift it all the way over, so the result is either
13242       // all-ones, or zero.
13243       SDValue ShrAmt =
13244         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13245                         getShiftAmountTy(Shl.getValueType()));
13246       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13247
13248       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13249     }
13250   }
13251
13252   // fold select C, 16, 0 -> shl C, 4
13253   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13254       TLI.getBooleanContents(N0.getValueType()) ==
13255           TargetLowering::ZeroOrOneBooleanContent) {
13256
13257     // If the caller doesn't want us to simplify this into a zext of a compare,
13258     // don't do it.
13259     if (NotExtCompare && N2C->getAPIntValue() == 1)
13260       return SDValue();
13261
13262     // Get a SetCC of the condition
13263     // NOTE: Don't create a SETCC if it's not legal on this target.
13264     if (!LegalOperations ||
13265         TLI.isOperationLegal(ISD::SETCC,
13266           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13267       SDValue Temp, SCC;
13268       // cast from setcc result type to select result type
13269       if (LegalTypes) {
13270         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13271                             N0, N1, CC);
13272         if (N2.getValueType().bitsLT(SCC.getValueType()))
13273           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13274                                         N2.getValueType());
13275         else
13276           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13277                              N2.getValueType(), SCC);
13278       } else {
13279         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13280         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13281                            N2.getValueType(), SCC);
13282       }
13283
13284       AddToWorklist(SCC.getNode());
13285       AddToWorklist(Temp.getNode());
13286
13287       if (N2C->getAPIntValue() == 1)
13288         return Temp;
13289
13290       // shl setcc result by log2 n2c
13291       return DAG.getNode(
13292           ISD::SHL, DL, N2.getValueType(), Temp,
13293           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13294                           getShiftAmountTy(Temp.getValueType())));
13295     }
13296   }
13297
13298   // Check to see if this is the equivalent of setcc
13299   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13300   // otherwise, go ahead with the folds.
13301   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13302     EVT XType = N0.getValueType();
13303     if (!LegalOperations ||
13304         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13305       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13306       if (Res.getValueType() != VT)
13307         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13308       return Res;
13309     }
13310
13311     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13312     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13313         (!LegalOperations ||
13314          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13315       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13316       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13317                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13318                                          SDLoc(Ctlz),
13319                                        getShiftAmountTy(Ctlz.getValueType())));
13320     }
13321     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13322     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13323       SDLoc DL(N0);
13324       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13325                                   XType, DAG.getConstant(0, DL, XType), N0);
13326       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13327       return DAG.getNode(ISD::SRL, DL, XType,
13328                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13329                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13330                                          getShiftAmountTy(XType)));
13331     }
13332     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13333     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13334       SDLoc DL(N0);
13335       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13336                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13337                                          getShiftAmountTy(N0.getValueType())));
13338       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13339                                                                     XType));
13340     }
13341   }
13342
13343   // Check to see if this is an integer abs.
13344   // select_cc setg[te] X,  0,  X, -X ->
13345   // select_cc setgt    X, -1,  X, -X ->
13346   // select_cc setl[te] X,  0, -X,  X ->
13347   // select_cc setlt    X,  1, -X,  X ->
13348   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13349   if (N1C) {
13350     ConstantSDNode *SubC = nullptr;
13351     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13352          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13353         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13354       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13355     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13356               (N1C->isOne() && CC == ISD::SETLT)) &&
13357              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13358       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13359
13360     EVT XType = N0.getValueType();
13361     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13362       SDLoc DL(N0);
13363       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13364                                   N0,
13365                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13366                                          getShiftAmountTy(N0.getValueType())));
13367       SDValue Add = DAG.getNode(ISD::ADD, DL,
13368                                 XType, N0, Shift);
13369       AddToWorklist(Shift.getNode());
13370       AddToWorklist(Add.getNode());
13371       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13372     }
13373   }
13374
13375   return SDValue();
13376 }
13377
13378 /// This is a stub for TargetLowering::SimplifySetCC.
13379 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13380                                    SDValue N1, ISD::CondCode Cond,
13381                                    SDLoc DL, bool foldBooleans) {
13382   TargetLowering::DAGCombinerInfo
13383     DagCombineInfo(DAG, Level, false, this);
13384   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13385 }
13386
13387 /// Given an ISD::SDIV node expressing a divide by constant, return
13388 /// a DAG expression to select that will generate the same value by multiplying
13389 /// by a magic number.
13390 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13391 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13392   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13393   if (!C)
13394     return SDValue();
13395
13396   // Avoid division by zero.
13397   if (!C->getAPIntValue())
13398     return SDValue();
13399
13400   std::vector<SDNode*> Built;
13401   SDValue S =
13402       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13403
13404   for (SDNode *N : Built)
13405     AddToWorklist(N);
13406   return S;
13407 }
13408
13409 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13410 /// DAG expression that will generate the same value by right shifting.
13411 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13412   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13413   if (!C)
13414     return SDValue();
13415
13416   // Avoid division by zero.
13417   if (!C->getAPIntValue())
13418     return SDValue();
13419
13420   std::vector<SDNode *> Built;
13421   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13422
13423   for (SDNode *N : Built)
13424     AddToWorklist(N);
13425   return S;
13426 }
13427
13428 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13429 /// expression that will generate the same value by multiplying by a magic
13430 /// number.
13431 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13432 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13433   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13434   if (!C)
13435     return SDValue();
13436
13437   // Avoid division by zero.
13438   if (!C->getAPIntValue())
13439     return SDValue();
13440
13441   std::vector<SDNode*> Built;
13442   SDValue S =
13443       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13444
13445   for (SDNode *N : Built)
13446     AddToWorklist(N);
13447   return S;
13448 }
13449
13450 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13451   if (Level >= AfterLegalizeDAG)
13452     return SDValue();
13453
13454   // Expose the DAG combiner to the target combiner implementations.
13455   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13456
13457   unsigned Iterations = 0;
13458   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13459     if (Iterations) {
13460       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13461       // For the reciprocal, we need to find the zero of the function:
13462       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13463       //     =>
13464       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13465       //     does not require additional intermediate precision]
13466       EVT VT = Op.getValueType();
13467       SDLoc DL(Op);
13468       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13469
13470       AddToWorklist(Est.getNode());
13471
13472       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13473       for (unsigned i = 0; i < Iterations; ++i) {
13474         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13475         AddToWorklist(NewEst.getNode());
13476
13477         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13478         AddToWorklist(NewEst.getNode());
13479
13480         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13481         AddToWorklist(NewEst.getNode());
13482
13483         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13484         AddToWorklist(Est.getNode());
13485       }
13486     }
13487     return Est;
13488   }
13489
13490   return SDValue();
13491 }
13492
13493 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13494 /// For the reciprocal sqrt, we need to find the zero of the function:
13495 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13496 ///     =>
13497 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13498 /// As a result, we precompute A/2 prior to the iteration loop.
13499 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13500                                           unsigned Iterations) {
13501   EVT VT = Arg.getValueType();
13502   SDLoc DL(Arg);
13503   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13504
13505   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13506   // this entire sequence requires only one FP constant.
13507   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13508   AddToWorklist(HalfArg.getNode());
13509
13510   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13511   AddToWorklist(HalfArg.getNode());
13512
13513   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13514   for (unsigned i = 0; i < Iterations; ++i) {
13515     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13516     AddToWorklist(NewEst.getNode());
13517
13518     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13519     AddToWorklist(NewEst.getNode());
13520
13521     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13522     AddToWorklist(NewEst.getNode());
13523
13524     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13525     AddToWorklist(Est.getNode());
13526   }
13527   return Est;
13528 }
13529
13530 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13531 /// For the reciprocal sqrt, we need to find the zero of the function:
13532 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13533 ///     =>
13534 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13535 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13536                                           unsigned Iterations) {
13537   EVT VT = Arg.getValueType();
13538   SDLoc DL(Arg);
13539   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13540   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13541
13542   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13543   for (unsigned i = 0; i < Iterations; ++i) {
13544     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13545     AddToWorklist(HalfEst.getNode());
13546
13547     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13548     AddToWorklist(Est.getNode());
13549
13550     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13551     AddToWorklist(Est.getNode());
13552
13553     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13554     AddToWorklist(Est.getNode());
13555
13556     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13557     AddToWorklist(Est.getNode());
13558   }
13559   return Est;
13560 }
13561
13562 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13563   if (Level >= AfterLegalizeDAG)
13564     return SDValue();
13565
13566   // Expose the DAG combiner to the target combiner implementations.
13567   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13568   unsigned Iterations = 0;
13569   bool UseOneConstNR = false;
13570   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13571     AddToWorklist(Est.getNode());
13572     if (Iterations) {
13573       Est = UseOneConstNR ?
13574         BuildRsqrtNROneConst(Op, Est, Iterations) :
13575         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13576     }
13577     return Est;
13578   }
13579
13580   return SDValue();
13581 }
13582
13583 /// Return true if base is a frame index, which is known not to alias with
13584 /// anything but itself.  Provides base object and offset as results.
13585 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13586                            const GlobalValue *&GV, const void *&CV) {
13587   // Assume it is a primitive operation.
13588   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13589
13590   // If it's an adding a simple constant then integrate the offset.
13591   if (Base.getOpcode() == ISD::ADD) {
13592     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13593       Base = Base.getOperand(0);
13594       Offset += C->getZExtValue();
13595     }
13596   }
13597
13598   // Return the underlying GlobalValue, and update the Offset.  Return false
13599   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13600   // by multiple nodes with different offsets.
13601   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13602     GV = G->getGlobal();
13603     Offset += G->getOffset();
13604     return false;
13605   }
13606
13607   // Return the underlying Constant value, and update the Offset.  Return false
13608   // for ConstantSDNodes since the same constant pool entry may be represented
13609   // by multiple nodes with different offsets.
13610   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13611     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13612                                          : (const void *)C->getConstVal();
13613     Offset += C->getOffset();
13614     return false;
13615   }
13616   // If it's any of the following then it can't alias with anything but itself.
13617   return isa<FrameIndexSDNode>(Base);
13618 }
13619
13620 /// Return true if there is any possibility that the two addresses overlap.
13621 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13622   // If they are the same then they must be aliases.
13623   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13624
13625   // If they are both volatile then they cannot be reordered.
13626   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13627
13628   // Gather base node and offset information.
13629   SDValue Base1, Base2;
13630   int64_t Offset1, Offset2;
13631   const GlobalValue *GV1, *GV2;
13632   const void *CV1, *CV2;
13633   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13634                                       Base1, Offset1, GV1, CV1);
13635   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13636                                       Base2, Offset2, GV2, CV2);
13637
13638   // If they have a same base address then check to see if they overlap.
13639   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13640     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13641              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13642
13643   // It is possible for different frame indices to alias each other, mostly
13644   // when tail call optimization reuses return address slots for arguments.
13645   // To catch this case, look up the actual index of frame indices to compute
13646   // the real alias relationship.
13647   if (isFrameIndex1 && isFrameIndex2) {
13648     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13649     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13650     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13651     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13652              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13653   }
13654
13655   // Otherwise, if we know what the bases are, and they aren't identical, then
13656   // we know they cannot alias.
13657   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13658     return false;
13659
13660   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13661   // compared to the size and offset of the access, we may be able to prove they
13662   // do not alias.  This check is conservative for now to catch cases created by
13663   // splitting vector types.
13664   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13665       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13666       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13667        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13668       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13669     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13670     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13671
13672     // There is no overlap between these relatively aligned accesses of similar
13673     // size, return no alias.
13674     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13675         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13676       return false;
13677   }
13678
13679   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13680                    ? CombinerGlobalAA
13681                    : DAG.getSubtarget().useAA();
13682 #ifndef NDEBUG
13683   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13684       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13685     UseAA = false;
13686 #endif
13687   if (UseAA &&
13688       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13689     // Use alias analysis information.
13690     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13691                                  Op1->getSrcValueOffset());
13692     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13693         Op0->getSrcValueOffset() - MinOffset;
13694     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13695         Op1->getSrcValueOffset() - MinOffset;
13696     AliasAnalysis::AliasResult AAResult =
13697         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13698                                          Overlap1,
13699                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13700                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13701                                          Overlap2,
13702                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13703     if (AAResult == AliasAnalysis::NoAlias)
13704       return false;
13705   }
13706
13707   // Otherwise we have to assume they alias.
13708   return true;
13709 }
13710
13711 /// Walk up chain skipping non-aliasing memory nodes,
13712 /// looking for aliasing nodes and adding them to the Aliases vector.
13713 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13714                                    SmallVectorImpl<SDValue> &Aliases) {
13715   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13716   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13717
13718   // Get alias information for node.
13719   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13720
13721   // Starting off.
13722   Chains.push_back(OriginalChain);
13723   unsigned Depth = 0;
13724
13725   // Look at each chain and determine if it is an alias.  If so, add it to the
13726   // aliases list.  If not, then continue up the chain looking for the next
13727   // candidate.
13728   while (!Chains.empty()) {
13729     SDValue Chain = Chains.back();
13730     Chains.pop_back();
13731
13732     // For TokenFactor nodes, look at each operand and only continue up the
13733     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13734     // find more and revert to original chain since the xform is unlikely to be
13735     // profitable.
13736     //
13737     // FIXME: The depth check could be made to return the last non-aliasing
13738     // chain we found before we hit a tokenfactor rather than the original
13739     // chain.
13740     if (Depth > 6 || Aliases.size() == 2) {
13741       Aliases.clear();
13742       Aliases.push_back(OriginalChain);
13743       return;
13744     }
13745
13746     // Don't bother if we've been before.
13747     if (!Visited.insert(Chain.getNode()).second)
13748       continue;
13749
13750     switch (Chain.getOpcode()) {
13751     case ISD::EntryToken:
13752       // Entry token is ideal chain operand, but handled in FindBetterChain.
13753       break;
13754
13755     case ISD::LOAD:
13756     case ISD::STORE: {
13757       // Get alias information for Chain.
13758       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13759           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13760
13761       // If chain is alias then stop here.
13762       if (!(IsLoad && IsOpLoad) &&
13763           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13764         Aliases.push_back(Chain);
13765       } else {
13766         // Look further up the chain.
13767         Chains.push_back(Chain.getOperand(0));
13768         ++Depth;
13769       }
13770       break;
13771     }
13772
13773     case ISD::TokenFactor:
13774       // We have to check each of the operands of the token factor for "small"
13775       // token factors, so we queue them up.  Adding the operands to the queue
13776       // (stack) in reverse order maintains the original order and increases the
13777       // likelihood that getNode will find a matching token factor (CSE.)
13778       if (Chain.getNumOperands() > 16) {
13779         Aliases.push_back(Chain);
13780         break;
13781       }
13782       for (unsigned n = Chain.getNumOperands(); n;)
13783         Chains.push_back(Chain.getOperand(--n));
13784       ++Depth;
13785       break;
13786
13787     default:
13788       // For all other instructions we will just have to take what we can get.
13789       Aliases.push_back(Chain);
13790       break;
13791     }
13792   }
13793
13794   // We need to be careful here to also search for aliases through the
13795   // value operand of a store, etc. Consider the following situation:
13796   //   Token1 = ...
13797   //   L1 = load Token1, %52
13798   //   S1 = store Token1, L1, %51
13799   //   L2 = load Token1, %52+8
13800   //   S2 = store Token1, L2, %51+8
13801   //   Token2 = Token(S1, S2)
13802   //   L3 = load Token2, %53
13803   //   S3 = store Token2, L3, %52
13804   //   L4 = load Token2, %53+8
13805   //   S4 = store Token2, L4, %52+8
13806   // If we search for aliases of S3 (which loads address %52), and we look
13807   // only through the chain, then we'll miss the trivial dependence on L1
13808   // (which also loads from %52). We then might change all loads and
13809   // stores to use Token1 as their chain operand, which could result in
13810   // copying %53 into %52 before copying %52 into %51 (which should
13811   // happen first).
13812   //
13813   // The problem is, however, that searching for such data dependencies
13814   // can become expensive, and the cost is not directly related to the
13815   // chain depth. Instead, we'll rule out such configurations here by
13816   // insisting that we've visited all chain users (except for users
13817   // of the original chain, which is not necessary). When doing this,
13818   // we need to look through nodes we don't care about (otherwise, things
13819   // like register copies will interfere with trivial cases).
13820
13821   SmallVector<const SDNode *, 16> Worklist;
13822   for (const SDNode *N : Visited)
13823     if (N != OriginalChain.getNode())
13824       Worklist.push_back(N);
13825
13826   while (!Worklist.empty()) {
13827     const SDNode *M = Worklist.pop_back_val();
13828
13829     // We have already visited M, and want to make sure we've visited any uses
13830     // of M that we care about. For uses that we've not visisted, and don't
13831     // care about, queue them to the worklist.
13832
13833     for (SDNode::use_iterator UI = M->use_begin(),
13834          UIE = M->use_end(); UI != UIE; ++UI)
13835       if (UI.getUse().getValueType() == MVT::Other &&
13836           Visited.insert(*UI).second) {
13837         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13838           // We've not visited this use, and we care about it (it could have an
13839           // ordering dependency with the original node).
13840           Aliases.clear();
13841           Aliases.push_back(OriginalChain);
13842           return;
13843         }
13844
13845         // We've not visited this use, but we don't care about it. Mark it as
13846         // visited and enqueue it to the worklist.
13847         Worklist.push_back(*UI);
13848       }
13849   }
13850 }
13851
13852 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13853 /// (aliasing node.)
13854 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13855   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13856
13857   // Accumulate all the aliases to this node.
13858   GatherAllAliases(N, OldChain, Aliases);
13859
13860   // If no operands then chain to entry token.
13861   if (Aliases.size() == 0)
13862     return DAG.getEntryNode();
13863
13864   // If a single operand then chain to it.  We don't need to revisit it.
13865   if (Aliases.size() == 1)
13866     return Aliases[0];
13867
13868   // Construct a custom tailored token factor.
13869   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13870 }
13871
13872 /// This is the entry point for the file.
13873 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13874                            CodeGenOpt::Level OptLevel) {
13875   /// This is the main entry point to this class.
13876   DAGCombiner(*this, AA, OptLevel).Run(Level);
13877 }