[bpf] fix build
[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
7210
7211
7212
7213   SDValue N0 = N->getOperand(0);
7214   SDValue N1 = N->getOperand(1);
7215   EVT VT = N->getValueType(0);
7216   SDLoc SL(N);
7217
7218   const TargetOptions &Options = DAG.getTarget().Options;
7219   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7220                        Options.UnsafeFPMath);
7221
7222   // Floating-point multiply-add with intermediate rounding.
7223   bool HasFMAD = (LegalOperations &&
7224                   TLI.isOperationLegal(ISD::FMAD, VT));
7225
7226   // Floating-point multiply-add without intermediate rounding.
7227   bool HasFMA = ((!LegalOperations ||
7228                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7229                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7230                  UnsafeFPMath);
7231
7232   // No valid opcode, do not combine.
7233   if (!HasFMAD && !HasFMA)
7234     return SDValue();
7235
7236   // Always prefer FMAD to FMA for precision.
7237   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7238   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7239   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7240
7241   // fold (fadd (fmul x, y), z) -> (fma x, y, z)
7242   if (N0.getOpcode() == ISD::FMUL &&
7243       (Aggressive || N0->hasOneUse())) {
7244     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7245                        N0.getOperand(0), N0.getOperand(1), N1);
7246   }
7247
7248   // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
7249   // Note: Commutes FADD operands.
7250   if (N1.getOpcode() == ISD::FMUL &&
7251       (Aggressive || N1->hasOneUse())) {
7252     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7253                        N1.getOperand(0), N1.getOperand(1), N0);
7254   }
7255
7256   // Look through FP_EXTEND nodes to do more combining.
7257   if (UnsafeFPMath && LookThroughFPExt) {
7258     // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
7259     if (N0.getOpcode() == ISD::FP_EXTEND) {
7260       SDValue N00 = N0.getOperand(0);
7261       if (N00.getOpcode() == ISD::FMUL)
7262         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7263                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7264                                        N00.getOperand(0)),
7265                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7266                                        N00.getOperand(1)), N1);
7267     }
7268
7269     // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
7270     // Note: Commutes FADD operands.
7271     if (N1.getOpcode() == ISD::FP_EXTEND) {
7272       SDValue N10 = N1.getOperand(0);
7273       if (N10.getOpcode() == ISD::FMUL)
7274         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7275                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7276                                        N10.getOperand(0)),
7277                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7278                                        N10.getOperand(1)), N0);
7279     }
7280   }
7281
7282   // More folding opportunities when target permits.
7283   if ((UnsafeFPMath || HasFMAD)  && Aggressive) {
7284     // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
7285     if (N0.getOpcode() == PreferredFusedOpcode &&
7286         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7287       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7288                          N0.getOperand(0), N0.getOperand(1),
7289                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7290                                      N0.getOperand(2).getOperand(0),
7291                                      N0.getOperand(2).getOperand(1),
7292                                      N1));
7293     }
7294
7295     // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
7296     if (N1->getOpcode() == PreferredFusedOpcode &&
7297         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7298       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7299                          N1.getOperand(0), N1.getOperand(1),
7300                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7301                                      N1.getOperand(2).getOperand(0),
7302                                      N1.getOperand(2).getOperand(1),
7303                                      N0));
7304     }
7305
7306     if (UnsafeFPMath && LookThroughFPExt) {
7307       // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
7308       //   -> (fma x, y, (fma (fpext u), (fpext v), z))
7309       auto FoldFAddFMAFPExtFMul = [&] (
7310           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7311         return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
7312                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7313                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7314                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7315                                        Z));
7316       };
7317       if (N0.getOpcode() == PreferredFusedOpcode) {
7318         SDValue N02 = N0.getOperand(2);
7319         if (N02.getOpcode() == ISD::FP_EXTEND) {
7320           SDValue N020 = N02.getOperand(0);
7321           if (N020.getOpcode() == ISD::FMUL)
7322             return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
7323                                         N020.getOperand(0), N020.getOperand(1),
7324                                         N1);
7325         }
7326       }
7327
7328       // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
7329       //   -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
7330       // FIXME: This turns two single-precision and one double-precision
7331       // operation into two double-precision operations, which might not be
7332       // interesting for all targets, especially GPUs.
7333       auto FoldFAddFPExtFMAFMul = [&] (
7334           SDValue X, SDValue Y, SDValue U, SDValue V, SDValue Z) {
7335         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7336                            DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
7337                            DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
7338                            DAG.getNode(PreferredFusedOpcode, SL, VT,
7339                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
7340                                        DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
7341                                        Z));
7342       };
7343       if (N0.getOpcode() == ISD::FP_EXTEND) {
7344         SDValue N00 = N0.getOperand(0);
7345         if (N00.getOpcode() == PreferredFusedOpcode) {
7346           SDValue N002 = N00.getOperand(2);
7347           if (N002.getOpcode() == ISD::FMUL)
7348             return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
7349                                         N002.getOperand(0), N002.getOperand(1),
7350                                         N1);
7351         }
7352       }
7353
7354       // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
7355       //   -> (fma y, z, (fma (fpext u), (fpext v), x))
7356       if (N1.getOpcode() == PreferredFusedOpcode) {
7357         SDValue N12 = N1.getOperand(2);
7358         if (N12.getOpcode() == ISD::FP_EXTEND) {
7359           SDValue N120 = N12.getOperand(0);
7360           if (N120.getOpcode() == ISD::FMUL)
7361             return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
7362                                         N120.getOperand(0), N120.getOperand(1),
7363                                         N0);
7364         }
7365       }
7366
7367       // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
7368       //   -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
7369       // FIXME: This turns two single-precision and one double-precision
7370       // operation into two double-precision operations, which might not be
7371       // interesting for all targets, especially GPUs.
7372       if (N1.getOpcode() == ISD::FP_EXTEND) {
7373         SDValue N10 = N1.getOperand(0);
7374         if (N10.getOpcode() == PreferredFusedOpcode) {
7375           SDValue N102 = N10.getOperand(2);
7376           if (N102.getOpcode() == ISD::FMUL)
7377             return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
7378                                         N102.getOperand(0), N102.getOperand(1),
7379                                         N0);
7380         }
7381       }
7382     }
7383   }
7384
7385   return SDValue();
7386 }
7387
7388 /// Try to perform FMA combining on a given FSUB node.
7389 SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
7390
7391
7392
7393   SDValue N0 = N->getOperand(0);
7394   SDValue N1 = N->getOperand(1);
7395   EVT VT = N->getValueType(0);
7396
7397   SDLoc SL(N);
7398
7399   const TargetOptions &Options = DAG.getTarget().Options;
7400   bool UnsafeFPMath = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
7401                        Options.UnsafeFPMath);
7402
7403   // Floating-point multiply-add with intermediate rounding.
7404   bool HasFMAD = (LegalOperations &&
7405                   TLI.isOperationLegal(ISD::FMAD, VT));
7406
7407   // Floating-point multiply-add without intermediate rounding.
7408   bool HasFMA = ((!LegalOperations ||
7409                   TLI.isOperationLegalOrCustom(ISD::FMA, VT)) &&
7410                  TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7411                  UnsafeFPMath);
7412
7413   // No valid opcode, do not combine.
7414   if (!HasFMAD && !HasFMA)
7415     return SDValue();
7416
7417   // Always prefer FMAD to FMA for precision.
7418   unsigned int PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
7419   bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
7420   bool LookThroughFPExt = TLI.isFPExtFree(VT);
7421
7422   // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7423   if (N0.getOpcode() == ISD::FMUL &&
7424       (Aggressive || N0->hasOneUse())) {
7425     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7426                        N0.getOperand(0), N0.getOperand(1),
7427                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7428   }
7429
7430   // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7431   // Note: Commutes FSUB operands.
7432   if (N1.getOpcode() == ISD::FMUL &&
7433       (Aggressive || N1->hasOneUse()))
7434     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7435                        DAG.getNode(ISD::FNEG, SL, VT,
7436                                    N1.getOperand(0)),
7437                        N1.getOperand(1), N0);
7438
7439   // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7440   if (N0.getOpcode() == ISD::FNEG &&
7441       N0.getOperand(0).getOpcode() == ISD::FMUL &&
7442       (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
7443     SDValue N00 = N0.getOperand(0).getOperand(0);
7444     SDValue N01 = N0.getOperand(0).getOperand(1);
7445     return DAG.getNode(PreferredFusedOpcode, SL, VT,
7446                        DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
7447                        DAG.getNode(ISD::FNEG, SL, VT, N1));
7448   }
7449
7450   // Look through FP_EXTEND nodes to do more combining.
7451   if (UnsafeFPMath && LookThroughFPExt) {
7452     // fold (fsub (fpext (fmul x, y)), z)
7453     //   -> (fma (fpext x), (fpext y), (fneg z))
7454     if (N0.getOpcode() == ISD::FP_EXTEND) {
7455       SDValue N00 = N0.getOperand(0);
7456       if (N00.getOpcode() == ISD::FMUL)
7457         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7458                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7459                                        N00.getOperand(0)),
7460                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7461                                        N00.getOperand(1)),
7462                            DAG.getNode(ISD::FNEG, SL, VT, N1));
7463     }
7464
7465     // fold (fsub x, (fpext (fmul y, z)))
7466     //   -> (fma (fneg (fpext y)), (fpext z), x)
7467     // Note: Commutes FSUB operands.
7468     if (N1.getOpcode() == ISD::FP_EXTEND) {
7469       SDValue N10 = N1.getOperand(0);
7470       if (N10.getOpcode() == ISD::FMUL)
7471         return DAG.getNode(PreferredFusedOpcode, SL, VT,
7472                            DAG.getNode(ISD::FNEG, SL, VT,
7473                                        DAG.getNode(ISD::FP_EXTEND, SL, VT,
7474                                                    N10.getOperand(0))),
7475                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7476                                        N10.getOperand(1)),
7477                            N0);
7478     }
7479
7480     // fold (fsub (fpext (fneg (fmul, x, y))), z)
7481     //   -> (fneg (fma (fpext x), (fpext y), z))
7482     // Note: This could be removed with appropriate canonicalization of the
7483     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7484     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7485     // from implementing the canonicalization in visitFSUB.
7486     if (N0.getOpcode() == ISD::FP_EXTEND) {
7487       SDValue N00 = N0.getOperand(0);
7488       if (N00.getOpcode() == ISD::FNEG) {
7489         SDValue N000 = N00.getOperand(0);
7490         if (N000.getOpcode() == ISD::FMUL) {
7491           return DAG.getNode(ISD::FNEG, SL, VT,
7492                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7493                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7494                                                      N000.getOperand(0)),
7495                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7496                                                      N000.getOperand(1)),
7497                                          N1));
7498         }
7499       }
7500     }
7501
7502     // fold (fsub (fneg (fpext (fmul, x, y))), z)
7503     //   -> (fneg (fma (fpext x)), (fpext y), z)
7504     // Note: This could be removed with appropriate canonicalization of the
7505     // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
7506     // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
7507     // from implementing the canonicalization in visitFSUB.
7508     if (N0.getOpcode() == ISD::FNEG) {
7509       SDValue N00 = N0.getOperand(0);
7510       if (N00.getOpcode() == ISD::FP_EXTEND) {
7511         SDValue N000 = N00.getOperand(0);
7512         if (N000.getOpcode() == ISD::FMUL) {
7513           return DAG.getNode(ISD::FNEG, SL, VT,
7514                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7515                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7516                                                      N000.getOperand(0)),
7517                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7518                                                      N000.getOperand(1)),
7519                                          N1));
7520         }
7521       }
7522     }
7523
7524   }
7525
7526   // More folding opportunities when target permits.
7527   if ((UnsafeFPMath || HasFMAD) && Aggressive) {
7528     // fold (fsub (fma x, y, (fmul u, v)), z)
7529     //   -> (fma x, y (fma u, v, (fneg z)))
7530     if (N0.getOpcode() == PreferredFusedOpcode &&
7531         N0.getOperand(2).getOpcode() == ISD::FMUL) {
7532       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7533                          N0.getOperand(0), N0.getOperand(1),
7534                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7535                                      N0.getOperand(2).getOperand(0),
7536                                      N0.getOperand(2).getOperand(1),
7537                                      DAG.getNode(ISD::FNEG, SL, VT,
7538                                                  N1)));
7539     }
7540
7541     // fold (fsub x, (fma y, z, (fmul u, v)))
7542     //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7543     if (N1.getOpcode() == PreferredFusedOpcode &&
7544         N1.getOperand(2).getOpcode() == ISD::FMUL) {
7545       SDValue N20 = N1.getOperand(2).getOperand(0);
7546       SDValue N21 = N1.getOperand(2).getOperand(1);
7547       return DAG.getNode(PreferredFusedOpcode, SL, VT,
7548                          DAG.getNode(ISD::FNEG, SL, VT,
7549                                      N1.getOperand(0)),
7550                          N1.getOperand(1),
7551                          DAG.getNode(PreferredFusedOpcode, SL, VT,
7552                                      DAG.getNode(ISD::FNEG, SL, VT, N20),
7553
7554                                      N21, N0));
7555     }
7556
7557     if (UnsafeFPMath && LookThroughFPExt) {
7558       // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
7559       //   -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
7560       if (N0.getOpcode() == PreferredFusedOpcode) {
7561         SDValue N02 = N0.getOperand(2);
7562         if (N02.getOpcode() == ISD::FP_EXTEND) {
7563           SDValue N020 = N02.getOperand(0);
7564           if (N020.getOpcode() == ISD::FMUL)
7565             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7566                                N0.getOperand(0), N0.getOperand(1),
7567                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7568                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7569                                                        N020.getOperand(0)),
7570                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7571                                                        N020.getOperand(1)),
7572                                            DAG.getNode(ISD::FNEG, SL, VT,
7573                                                        N1)));
7574         }
7575       }
7576
7577       // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
7578       //   -> (fma (fpext x), (fpext y),
7579       //           (fma (fpext u), (fpext v), (fneg z)))
7580       // FIXME: This turns two single-precision and one double-precision
7581       // operation into two double-precision operations, which might not be
7582       // interesting for all targets, especially GPUs.
7583       if (N0.getOpcode() == ISD::FP_EXTEND) {
7584         SDValue N00 = N0.getOperand(0);
7585         if (N00.getOpcode() == PreferredFusedOpcode) {
7586           SDValue N002 = N00.getOperand(2);
7587           if (N002.getOpcode() == ISD::FMUL)
7588             return DAG.getNode(PreferredFusedOpcode, SL, VT,
7589                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7590                                            N00.getOperand(0)),
7591                                DAG.getNode(ISD::FP_EXTEND, SL, VT,
7592                                            N00.getOperand(1)),
7593                                DAG.getNode(PreferredFusedOpcode, SL, VT,
7594                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7595                                                        N002.getOperand(0)),
7596                                            DAG.getNode(ISD::FP_EXTEND, SL, VT,
7597                                                        N002.getOperand(1)),
7598                                            DAG.getNode(ISD::FNEG, SL, VT,
7599                                                        N1)));
7600         }
7601       }
7602
7603       // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
7604       //   -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
7605       if (N1.getOpcode() == PreferredFusedOpcode &&
7606         N1.getOperand(2).getOpcode() == ISD::FP_EXTEND) {
7607         SDValue N120 = N1.getOperand(2).getOperand(0);
7608         if (N120.getOpcode() == ISD::FMUL) {
7609           SDValue N1200 = N120.getOperand(0);
7610           SDValue N1201 = N120.getOperand(1);
7611           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7612                              DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)),
7613                              N1.getOperand(1),
7614                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7615                                          DAG.getNode(ISD::FNEG, SL, VT,
7616                                              DAG.getNode(ISD::FP_EXTEND, SL,
7617                                                          VT, N1200)),
7618                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7619                                                      N1201),
7620                                          N0));
7621         }
7622       }
7623
7624       // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
7625       //   -> (fma (fneg (fpext y)), (fpext z),
7626       //           (fma (fneg (fpext u)), (fpext v), x))
7627       // FIXME: This turns two single-precision and one double-precision
7628       // operation into two double-precision operations, which might not be
7629       // interesting for all targets, especially GPUs.
7630       if (N1.getOpcode() == ISD::FP_EXTEND &&
7631         N1.getOperand(0).getOpcode() == PreferredFusedOpcode) {
7632         SDValue N100 = N1.getOperand(0).getOperand(0);
7633         SDValue N101 = N1.getOperand(0).getOperand(1);
7634         SDValue N102 = N1.getOperand(0).getOperand(2);
7635         if (N102.getOpcode() == ISD::FMUL) {
7636           SDValue N1020 = N102.getOperand(0);
7637           SDValue N1021 = N102.getOperand(1);
7638           return DAG.getNode(PreferredFusedOpcode, SL, VT,
7639                              DAG.getNode(ISD::FNEG, SL, VT,
7640                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7641                                                      N100)),
7642                              DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
7643                              DAG.getNode(PreferredFusedOpcode, SL, VT,
7644                                          DAG.getNode(ISD::FNEG, SL, VT,
7645                                              DAG.getNode(ISD::FP_EXTEND, SL,
7646                                                          VT, N1020)),
7647                                          DAG.getNode(ISD::FP_EXTEND, SL, VT,
7648                                                      N1021),
7649                                          N0));
7650         }
7651       }
7652     }
7653   }
7654
7655   return SDValue();
7656 }
7657
7658 SDValue DAGCombiner::visitFADD(SDNode *N) {
7659   SDValue N0 = N->getOperand(0);
7660   SDValue N1 = N->getOperand(1);
7661   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7662   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7663   EVT VT = N->getValueType(0);
7664   const TargetOptions &Options = DAG.getTarget().Options;
7665
7666   // fold vector ops
7667   if (VT.isVector())
7668     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7669       return FoldedVOp;
7670
7671   // fold (fadd c1, c2) -> c1 + c2
7672   if (N0CFP && N1CFP)
7673     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
7674
7675   // canonicalize constant to RHS
7676   if (N0CFP && !N1CFP)
7677     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
7678
7679   // fold (fadd A, (fneg B)) -> (fsub A, B)
7680   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7681       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
7682     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
7683                        GetNegatedExpression(N1, DAG, LegalOperations));
7684
7685   // fold (fadd (fneg A), B) -> (fsub B, A)
7686   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
7687       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
7688     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
7689                        GetNegatedExpression(N0, DAG, LegalOperations));
7690
7691   // If 'unsafe math' is enabled, fold lots of things.
7692   if (Options.UnsafeFPMath) {
7693     // No FP constant should be created after legalization as Instruction
7694     // Selection pass has a hard time dealing with FP constants.
7695     bool AllowNewConst = (Level < AfterLegalizeDAG);
7696
7697     // fold (fadd A, 0) -> A
7698     if (N1CFP && N1CFP->getValueAPF().isZero())
7699       return N0;
7700
7701     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
7702     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
7703         isa<ConstantFPSDNode>(N0.getOperand(1)))
7704       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
7705                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
7706                                      N0.getOperand(1), N1));
7707
7708     // If allowed, fold (fadd (fneg x), x) -> 0.0
7709     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
7710       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7711
7712     // If allowed, fold (fadd x, (fneg x)) -> 0.0
7713     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
7714       return DAG.getConstantFP(0.0, SDLoc(N), VT);
7715
7716     // We can fold chains of FADD's of the same value into multiplications.
7717     // This transform is not safe in general because we are reducing the number
7718     // of rounding steps.
7719     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
7720       if (N0.getOpcode() == ISD::FMUL) {
7721         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7722         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7723
7724         // (fadd (fmul x, c), x) -> (fmul x, c+1)
7725         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
7726           SDLoc DL(N);
7727           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7728                                        SDValue(CFP01, 0),
7729                                        DAG.getConstantFP(1.0, DL, VT));
7730           return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
7731         }
7732
7733         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
7734         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
7735             N1.getOperand(0) == N1.getOperand(1) &&
7736             N0.getOperand(0) == N1.getOperand(0)) {
7737           SDLoc DL(N);
7738           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7739                                        SDValue(CFP01, 0),
7740                                        DAG.getConstantFP(2.0, DL, VT));
7741           return DAG.getNode(ISD::FMUL, DL, VT,
7742                              N0.getOperand(0), NewCFP);
7743         }
7744       }
7745
7746       if (N1.getOpcode() == ISD::FMUL) {
7747         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7748         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
7749
7750         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
7751         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
7752           SDLoc DL(N);
7753           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7754                                        SDValue(CFP11, 0),
7755                                        DAG.getConstantFP(1.0, DL, VT));
7756           return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
7757         }
7758
7759         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
7760         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
7761             N0.getOperand(0) == N0.getOperand(1) &&
7762             N1.getOperand(0) == N0.getOperand(0)) {
7763           SDLoc DL(N);
7764           SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT,
7765                                        SDValue(CFP11, 0),
7766                                        DAG.getConstantFP(2.0, DL, VT));
7767           return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
7768         }
7769       }
7770
7771       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
7772         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
7773         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
7774         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
7775             (N0.getOperand(0) == N1)) {
7776           SDLoc DL(N);
7777           return DAG.getNode(ISD::FMUL, DL, VT,
7778                              N1, DAG.getConstantFP(3.0, DL, VT));
7779         }
7780       }
7781
7782       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
7783         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
7784         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
7785         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
7786             N1.getOperand(0) == N0) {
7787           SDLoc DL(N);
7788           return DAG.getNode(ISD::FMUL, DL, VT,
7789                              N0, DAG.getConstantFP(3.0, DL, VT));
7790         }
7791       }
7792
7793       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
7794       if (AllowNewConst &&
7795           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
7796           N0.getOperand(0) == N0.getOperand(1) &&
7797           N1.getOperand(0) == N1.getOperand(1) &&
7798           N0.getOperand(0) == N1.getOperand(0)) {
7799         SDLoc DL(N);
7800         return DAG.getNode(ISD::FMUL, DL, VT,
7801                            N0.getOperand(0), DAG.getConstantFP(4.0, DL, VT));
7802       }
7803     }
7804   } // enable-unsafe-fp-math
7805
7806   // FADD -> FMA combines:
7807   SDValue Fused = visitFADDForFMACombine(N);
7808   if (Fused) {
7809     AddToWorklist(Fused.getNode());
7810     return Fused;
7811   }
7812
7813   return SDValue();
7814 }
7815
7816 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7817   SDValue N0 = N->getOperand(0);
7818   SDValue N1 = N->getOperand(1);
7819   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7820   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7821   EVT VT = N->getValueType(0);
7822   SDLoc dl(N);
7823   const TargetOptions &Options = DAG.getTarget().Options;
7824
7825   // fold vector ops
7826   if (VT.isVector())
7827     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7828       return FoldedVOp;
7829
7830   // fold (fsub c1, c2) -> c1-c2
7831   if (N0CFP && N1CFP)
7832     return DAG.getNode(ISD::FSUB, dl, VT, N0, N1);
7833
7834   // fold (fsub A, (fneg B)) -> (fadd A, B)
7835   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7836     return DAG.getNode(ISD::FADD, dl, VT, N0,
7837                        GetNegatedExpression(N1, DAG, LegalOperations));
7838
7839   // If 'unsafe math' is enabled, fold lots of things.
7840   if (Options.UnsafeFPMath) {
7841     // (fsub A, 0) -> A
7842     if (N1CFP && N1CFP->getValueAPF().isZero())
7843       return N0;
7844
7845     // (fsub 0, B) -> -B
7846     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7847       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7848         return GetNegatedExpression(N1, DAG, LegalOperations);
7849       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7850         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7851     }
7852
7853     // (fsub x, x) -> 0.0
7854     if (N0 == N1)
7855       return DAG.getConstantFP(0.0f, dl, VT);
7856
7857     // (fsub x, (fadd x, y)) -> (fneg y)
7858     // (fsub x, (fadd y, x)) -> (fneg y)
7859     if (N1.getOpcode() == ISD::FADD) {
7860       SDValue N10 = N1->getOperand(0);
7861       SDValue N11 = N1->getOperand(1);
7862
7863       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7864         return GetNegatedExpression(N11, DAG, LegalOperations);
7865
7866       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7867         return GetNegatedExpression(N10, DAG, LegalOperations);
7868     }
7869   }
7870
7871   // FSUB -> FMA combines:
7872   SDValue Fused = visitFSUBForFMACombine(N);
7873   if (Fused) {
7874     AddToWorklist(Fused.getNode());
7875     return Fused;
7876   }
7877
7878   return SDValue();
7879 }
7880
7881 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7882   SDValue N0 = N->getOperand(0);
7883   SDValue N1 = N->getOperand(1);
7884   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7885   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7886   EVT VT = N->getValueType(0);
7887   const TargetOptions &Options = DAG.getTarget().Options;
7888
7889   // fold vector ops
7890   if (VT.isVector()) {
7891     // This just handles C1 * C2 for vectors. Other vector folds are below.
7892     if (SDValue FoldedVOp = SimplifyVBinOp(N))
7893       return FoldedVOp;
7894   }
7895
7896   // fold (fmul c1, c2) -> c1*c2
7897   if (N0CFP && N1CFP)
7898     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7899
7900   // canonicalize constant to RHS
7901   if (isConstantFPBuildVectorOrConstantFP(N0) &&
7902      !isConstantFPBuildVectorOrConstantFP(N1))
7903     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7904
7905   // fold (fmul A, 1.0) -> A
7906   if (N1CFP && N1CFP->isExactlyValue(1.0))
7907     return N0;
7908
7909   if (Options.UnsafeFPMath) {
7910     // fold (fmul A, 0) -> 0
7911     if (N1CFP && N1CFP->getValueAPF().isZero())
7912       return N1;
7913
7914     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7915     if (N0.getOpcode() == ISD::FMUL) {
7916       // Fold scalars or any vector constants (not just splats).
7917       // This fold is done in general by InstCombine, but extra fmul insts
7918       // may have been generated during lowering.
7919       SDValue N00 = N0.getOperand(0);
7920       SDValue N01 = N0.getOperand(1);
7921       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7922       auto *BV00 = dyn_cast<BuildVectorSDNode>(N00);
7923       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7924       
7925       // Check 1: Make sure that the first operand of the inner multiply is NOT
7926       // a constant. Otherwise, we may induce infinite looping.
7927       if (!(isConstOrConstSplatFP(N00) || (BV00 && BV00->isConstant()))) {
7928         // Check 2: Make sure that the second operand of the inner multiply and
7929         // the second operand of the outer multiply are constants.
7930         if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7931             (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7932           SDLoc SL(N);
7933           SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7934           return DAG.getNode(ISD::FMUL, SL, VT, N00, MulConsts);
7935         }
7936       }
7937     }
7938
7939     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7940     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7941     // during an early run of DAGCombiner can prevent folding with fmuls
7942     // inserted during lowering.
7943     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7944       SDLoc SL(N);
7945       const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7946       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7947       return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7948     }
7949   }
7950
7951   // fold (fmul X, 2.0) -> (fadd X, X)
7952   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7953     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7954
7955   // fold (fmul X, -1.0) -> (fneg X)
7956   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7957     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7958       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7959
7960   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7961   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7962     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7963       // Both can be negated for free, check to see if at least one is cheaper
7964       // negated.
7965       if (LHSNeg == 2 || RHSNeg == 2)
7966         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7967                            GetNegatedExpression(N0, DAG, LegalOperations),
7968                            GetNegatedExpression(N1, DAG, LegalOperations));
7969     }
7970   }
7971
7972   return SDValue();
7973 }
7974
7975 SDValue DAGCombiner::visitFMA(SDNode *N) {
7976   SDValue N0 = N->getOperand(0);
7977   SDValue N1 = N->getOperand(1);
7978   SDValue N2 = N->getOperand(2);
7979   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7980   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7981   EVT VT = N->getValueType(0);
7982   SDLoc dl(N);
7983   const TargetOptions &Options = DAG.getTarget().Options;
7984
7985   // Constant fold FMA.
7986   if (isa<ConstantFPSDNode>(N0) &&
7987       isa<ConstantFPSDNode>(N1) &&
7988       isa<ConstantFPSDNode>(N2)) {
7989     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7990   }
7991
7992   if (Options.UnsafeFPMath) {
7993     if (N0CFP && N0CFP->isZero())
7994       return N2;
7995     if (N1CFP && N1CFP->isZero())
7996       return N2;
7997   }
7998   if (N0CFP && N0CFP->isExactlyValue(1.0))
7999     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
8000   if (N1CFP && N1CFP->isExactlyValue(1.0))
8001     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
8002
8003   // Canonicalize (fma c, x, y) -> (fma x, c, y)
8004   if (N0CFP && !N1CFP)
8005     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
8006
8007   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
8008   if (Options.UnsafeFPMath && N1CFP &&
8009       N2.getOpcode() == ISD::FMUL &&
8010       N0 == N2.getOperand(0) &&
8011       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
8012     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8013                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
8014   }
8015
8016
8017   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
8018   if (Options.UnsafeFPMath &&
8019       N0.getOpcode() == ISD::FMUL && N1CFP &&
8020       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
8021     return DAG.getNode(ISD::FMA, dl, VT,
8022                        N0.getOperand(0),
8023                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
8024                        N2);
8025   }
8026
8027   // (fma x, 1, y) -> (fadd x, y)
8028   // (fma x, -1, y) -> (fadd (fneg x), y)
8029   if (N1CFP) {
8030     if (N1CFP->isExactlyValue(1.0))
8031       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
8032
8033     if (N1CFP->isExactlyValue(-1.0) &&
8034         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
8035       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
8036       AddToWorklist(RHSNeg.getNode());
8037       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
8038     }
8039   }
8040
8041   // (fma x, c, x) -> (fmul x, (c+1))
8042   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
8043     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8044                        DAG.getNode(ISD::FADD, dl, VT,
8045                                    N1, DAG.getConstantFP(1.0, dl, VT)));
8046
8047   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
8048   if (Options.UnsafeFPMath && N1CFP &&
8049       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
8050     return DAG.getNode(ISD::FMUL, dl, VT, N0,
8051                        DAG.getNode(ISD::FADD, dl, VT,
8052                                    N1, DAG.getConstantFP(-1.0, dl, VT)));
8053
8054
8055   return SDValue();
8056 }
8057
8058 SDValue DAGCombiner::visitFDIV(SDNode *N) {
8059   SDValue N0 = N->getOperand(0);
8060   SDValue N1 = N->getOperand(1);
8061   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8062   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8063   EVT VT = N->getValueType(0);
8064   SDLoc DL(N);
8065   const TargetOptions &Options = DAG.getTarget().Options;
8066
8067   // fold vector ops
8068   if (VT.isVector())
8069     if (SDValue FoldedVOp = SimplifyVBinOp(N))
8070       return FoldedVOp;
8071
8072   // fold (fdiv c1, c2) -> c1/c2
8073   if (N0CFP && N1CFP)
8074     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
8075
8076   if (Options.UnsafeFPMath) {
8077     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
8078     if (N1CFP) {
8079       // Compute the reciprocal 1.0 / c2.
8080       APFloat N1APF = N1CFP->getValueAPF();
8081       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
8082       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
8083       // Only do the transform if the reciprocal is a legal fp immediate that
8084       // isn't too nasty (eg NaN, denormal, ...).
8085       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
8086           (!LegalOperations ||
8087            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
8088            // backend)... we should handle this gracefully after Legalize.
8089            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
8090            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
8091            TLI.isFPImmLegal(Recip, VT)))
8092         return DAG.getNode(ISD::FMUL, DL, VT, N0,
8093                            DAG.getConstantFP(Recip, DL, VT));
8094     }
8095
8096     // If this FDIV is part of a reciprocal square root, it may be folded
8097     // into a target-specific square root estimate instruction.
8098     if (N1.getOpcode() == ISD::FSQRT) {
8099       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
8100         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8101       }
8102     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
8103                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8104       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8105         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
8106         AddToWorklist(RV.getNode());
8107         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8108       }
8109     } else if (N1.getOpcode() == ISD::FP_ROUND &&
8110                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8111       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
8112         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
8113         AddToWorklist(RV.getNode());
8114         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8115       }
8116     } else if (N1.getOpcode() == ISD::FMUL) {
8117       // Look through an FMUL. Even though this won't remove the FDIV directly,
8118       // it's still worthwhile to get rid of the FSQRT if possible.
8119       SDValue SqrtOp;
8120       SDValue OtherOp;
8121       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
8122         SqrtOp = N1.getOperand(0);
8123         OtherOp = N1.getOperand(1);
8124       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
8125         SqrtOp = N1.getOperand(1);
8126         OtherOp = N1.getOperand(0);
8127       }
8128       if (SqrtOp.getNode()) {
8129         // We found a FSQRT, so try to make this fold:
8130         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
8131         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
8132           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
8133           AddToWorklist(RV.getNode());
8134           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8135         }
8136       }
8137     }
8138
8139     // Fold into a reciprocal estimate and multiply instead of a real divide.
8140     if (SDValue RV = BuildReciprocalEstimate(N1)) {
8141       AddToWorklist(RV.getNode());
8142       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
8143     }
8144   }
8145
8146   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
8147   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
8148     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
8149       // Both can be negated for free, check to see if at least one is cheaper
8150       // negated.
8151       if (LHSNeg == 2 || RHSNeg == 2)
8152         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
8153                            GetNegatedExpression(N0, DAG, LegalOperations),
8154                            GetNegatedExpression(N1, DAG, LegalOperations));
8155     }
8156   }
8157
8158   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
8159   // reciprocal.
8160   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
8161   // Notice that this is not always beneficial. One reason is different target
8162   // may have different costs for FDIV and FMUL, so sometimes the cost of two
8163   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
8164   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
8165   if (Options.UnsafeFPMath) {
8166     // Skip if current node is a reciprocal.
8167     if (N0CFP && N0CFP->isExactlyValue(1.0))
8168       return SDValue();
8169
8170     SmallVector<SDNode *, 4> Users;
8171     // Find all FDIV users of the same divisor.
8172     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
8173                               UE = N1.getNode()->use_end();
8174          UI != UE; ++UI) {
8175       SDNode *User = UI.getUse().getUser();
8176       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
8177         Users.push_back(User);
8178     }
8179
8180     if (TLI.combineRepeatedFPDivisors(Users.size())) {
8181       SDLoc DL(N);
8182       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT); // floating point 1.0
8183       SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1);
8184
8185       // Dividend / Divisor -> Dividend * Reciprocal
8186       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
8187         if ((*I)->getOperand(0) != FPOne) {
8188           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
8189                                         (*I)->getOperand(0), Reciprocal);
8190           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
8191         }
8192       }
8193       return SDValue();
8194     }
8195   }
8196
8197   return SDValue();
8198 }
8199
8200 SDValue DAGCombiner::visitFREM(SDNode *N) {
8201   SDValue N0 = N->getOperand(0);
8202   SDValue N1 = N->getOperand(1);
8203   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8204   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8205   EVT VT = N->getValueType(0);
8206
8207   // fold (frem c1, c2) -> fmod(c1,c2)
8208   if (N0CFP && N1CFP)
8209     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
8210
8211   return SDValue();
8212 }
8213
8214 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
8215   if (DAG.getTarget().Options.UnsafeFPMath &&
8216       !TLI.isFsqrtCheap()) {
8217     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
8218     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
8219       EVT VT = RV.getValueType();
8220       SDLoc DL(N);
8221       RV = DAG.getNode(ISD::FMUL, DL, VT, N->getOperand(0), RV);
8222       AddToWorklist(RV.getNode());
8223
8224       // Unfortunately, RV is now NaN if the input was exactly 0.
8225       // Select out this case and force the answer to 0.
8226       SDValue Zero = DAG.getConstantFP(0.0, DL, VT);
8227       SDValue ZeroCmp =
8228         DAG.getSetCC(DL, TLI.getSetCCResultType(*DAG.getContext(), VT),
8229                      N->getOperand(0), Zero, ISD::SETEQ);
8230       AddToWorklist(ZeroCmp.getNode());
8231       AddToWorklist(RV.getNode());
8232
8233       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
8234                        DL, VT, ZeroCmp, Zero, RV);
8235       return RV;
8236     }
8237   }
8238   return SDValue();
8239 }
8240
8241 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
8242   SDValue N0 = N->getOperand(0);
8243   SDValue N1 = N->getOperand(1);
8244   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8245   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8246   EVT VT = N->getValueType(0);
8247
8248   if (N0CFP && N1CFP)  // Constant fold
8249     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
8250
8251   if (N1CFP) {
8252     const APFloat& V = N1CFP->getValueAPF();
8253     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
8254     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
8255     if (!V.isNegative()) {
8256       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
8257         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8258     } else {
8259       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
8260         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
8261                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
8262     }
8263   }
8264
8265   // copysign(fabs(x), y) -> copysign(x, y)
8266   // copysign(fneg(x), y) -> copysign(x, y)
8267   // copysign(copysign(x,z), y) -> copysign(x, y)
8268   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
8269       N0.getOpcode() == ISD::FCOPYSIGN)
8270     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8271                        N0.getOperand(0), N1);
8272
8273   // copysign(x, abs(y)) -> abs(x)
8274   if (N1.getOpcode() == ISD::FABS)
8275     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8276
8277   // copysign(x, copysign(y,z)) -> copysign(x, z)
8278   if (N1.getOpcode() == ISD::FCOPYSIGN)
8279     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8280                        N0, N1.getOperand(1));
8281
8282   // copysign(x, fp_extend(y)) -> copysign(x, y)
8283   // copysign(x, fp_round(y)) -> copysign(x, y)
8284   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
8285     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8286                        N0, N1.getOperand(0));
8287
8288   return SDValue();
8289 }
8290
8291 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
8292   SDValue N0 = N->getOperand(0);
8293   EVT VT = N->getValueType(0);
8294   EVT OpVT = N0.getValueType();
8295
8296   // fold (sint_to_fp c1) -> c1fp
8297   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8298       // ...but only if the target supports immediate floating-point values
8299       (!LegalOperations ||
8300        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8301     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8302
8303   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
8304   // but UINT_TO_FP is legal on this target, try to convert.
8305   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
8306       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
8307     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
8308     if (DAG.SignBitIsZero(N0))
8309       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8310   }
8311
8312   // The next optimizations are desirable only if SELECT_CC can be lowered.
8313   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8314     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8315     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
8316         !VT.isVector() &&
8317         (!LegalOperations ||
8318          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8319       SDLoc DL(N);
8320       SDValue Ops[] =
8321         { N0.getOperand(0), N0.getOperand(1),
8322           DAG.getConstantFP(-1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8323           N0.getOperand(2) };
8324       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8325     }
8326
8327     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
8328     //      (select_cc x, y, 1.0, 0.0,, cc)
8329     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
8330         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
8331         (!LegalOperations ||
8332          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8333       SDLoc DL(N);
8334       SDValue Ops[] =
8335         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
8336           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8337           N0.getOperand(0).getOperand(2) };
8338       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8339     }
8340   }
8341
8342   return SDValue();
8343 }
8344
8345 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
8346   SDValue N0 = N->getOperand(0);
8347   EVT VT = N->getValueType(0);
8348   EVT OpVT = N0.getValueType();
8349
8350   // fold (uint_to_fp c1) -> c1fp
8351   if (isConstantIntBuildVectorOrConstantInt(N0) &&
8352       // ...but only if the target supports immediate floating-point values
8353       (!LegalOperations ||
8354        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
8355     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
8356
8357   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
8358   // but SINT_TO_FP is legal on this target, try to convert.
8359   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
8360       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
8361     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
8362     if (DAG.SignBitIsZero(N0))
8363       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
8364   }
8365
8366   // The next optimizations are desirable only if SELECT_CC can be lowered.
8367   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
8368     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
8369
8370     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
8371         (!LegalOperations ||
8372          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
8373       SDLoc DL(N);
8374       SDValue Ops[] =
8375         { N0.getOperand(0), N0.getOperand(1),
8376           DAG.getConstantFP(1.0, DL, VT), DAG.getConstantFP(0.0, DL, VT),
8377           N0.getOperand(2) };
8378       return DAG.getNode(ISD::SELECT_CC, DL, VT, Ops);
8379     }
8380   }
8381
8382   return SDValue();
8383 }
8384
8385 // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
8386 static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
8387   SDValue N0 = N->getOperand(0);
8388   EVT VT = N->getValueType(0);
8389
8390   if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
8391     return SDValue();
8392
8393   SDValue Src = N0.getOperand(0);
8394   EVT SrcVT = Src.getValueType();
8395   bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
8396   bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
8397
8398   // We can safely assume the conversion won't overflow the output range,
8399   // because (for example) (uint8_t)18293.f is undefined behavior.
8400
8401   // Since we can assume the conversion won't overflow, our decision as to
8402   // whether the input will fit in the float should depend on the minimum
8403   // of the input range and output range.
8404
8405   // This means this is also safe for a signed input and unsigned output, since
8406   // a negative input would lead to undefined behavior.
8407   unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
8408   unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
8409   unsigned ActualSize = std::min(InputSize, OutputSize);
8410   const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
8411
8412   // We can only fold away the float conversion if the input range can be
8413   // represented exactly in the float range.
8414   if (APFloat::semanticsPrecision(sem) >= ActualSize) {
8415     if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
8416       unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
8417                                                        : ISD::ZERO_EXTEND;
8418       return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
8419     }
8420     if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
8421       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
8422     if (SrcVT == VT)
8423       return Src;
8424     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Src);
8425   }
8426   return SDValue();
8427 }
8428
8429 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
8430   SDValue N0 = N->getOperand(0);
8431   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8432   EVT VT = N->getValueType(0);
8433
8434   // fold (fp_to_sint c1fp) -> c1
8435   if (N0CFP)
8436     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
8437
8438   return FoldIntToFPToInt(N, DAG);
8439 }
8440
8441 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
8442   SDValue N0 = N->getOperand(0);
8443   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8444   EVT VT = N->getValueType(0);
8445
8446   // fold (fp_to_uint c1fp) -> c1
8447   if (N0CFP)
8448     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
8449
8450   return FoldIntToFPToInt(N, DAG);
8451 }
8452
8453 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
8454   SDValue N0 = N->getOperand(0);
8455   SDValue N1 = N->getOperand(1);
8456   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8457   EVT VT = N->getValueType(0);
8458
8459   // fold (fp_round c1fp) -> c1fp
8460   if (N0CFP)
8461     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
8462
8463   // fold (fp_round (fp_extend x)) -> x
8464   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
8465     return N0.getOperand(0);
8466
8467   // fold (fp_round (fp_round x)) -> (fp_round x)
8468   if (N0.getOpcode() == ISD::FP_ROUND) {
8469     const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
8470     const bool N0IsTrunc = N0.getNode()->getConstantOperandVal(1) == 1;
8471     // If the first fp_round isn't a value preserving truncation, it might
8472     // introduce a tie in the second fp_round, that wouldn't occur in the
8473     // single-step fp_round we want to fold to.
8474     // In other words, double rounding isn't the same as rounding.
8475     // Also, this is a value preserving truncation iff both fp_round's are.
8476     if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
8477       SDLoc DL(N);
8478       return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
8479                          DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
8480     }
8481   }
8482
8483   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
8484   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
8485     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
8486                               N0.getOperand(0), N1);
8487     AddToWorklist(Tmp.getNode());
8488     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
8489                        Tmp, N0.getOperand(1));
8490   }
8491
8492   return SDValue();
8493 }
8494
8495 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
8496   SDValue N0 = N->getOperand(0);
8497   EVT VT = N->getValueType(0);
8498   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
8499   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8500
8501   // fold (fp_round_inreg c1fp) -> c1fp
8502   if (N0CFP && isTypeLegal(EVT)) {
8503     SDLoc DL(N);
8504     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), DL, EVT);
8505     return DAG.getNode(ISD::FP_EXTEND, DL, VT, Round);
8506   }
8507
8508   return SDValue();
8509 }
8510
8511 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
8512   SDValue N0 = N->getOperand(0);
8513   EVT VT = N->getValueType(0);
8514
8515   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
8516   if (N->hasOneUse() &&
8517       N->use_begin()->getOpcode() == ISD::FP_ROUND)
8518     return SDValue();
8519
8520   // fold (fp_extend c1fp) -> c1fp
8521   if (isConstantFPBuildVectorOrConstantFP(N0))
8522     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
8523
8524   // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
8525   if (N0.getOpcode() == ISD::FP16_TO_FP &&
8526       TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
8527     return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
8528
8529   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
8530   // value of X.
8531   if (N0.getOpcode() == ISD::FP_ROUND
8532       && N0.getNode()->getConstantOperandVal(1) == 1) {
8533     SDValue In = N0.getOperand(0);
8534     if (In.getValueType() == VT) return In;
8535     if (VT.bitsLT(In.getValueType()))
8536       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
8537                          In, N0.getOperand(1));
8538     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
8539   }
8540
8541   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
8542   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8543        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
8544     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
8545     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
8546                                      LN0->getChain(),
8547                                      LN0->getBasePtr(), N0.getValueType(),
8548                                      LN0->getMemOperand());
8549     CombineTo(N, ExtLoad);
8550     CombineTo(N0.getNode(),
8551               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
8552                           N0.getValueType(), ExtLoad,
8553                           DAG.getIntPtrConstant(1, SDLoc(N0))),
8554               ExtLoad.getValue(1));
8555     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8556   }
8557
8558   return SDValue();
8559 }
8560
8561 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
8562   SDValue N0 = N->getOperand(0);
8563   EVT VT = N->getValueType(0);
8564
8565   // fold (fceil c1) -> fceil(c1)
8566   if (isConstantFPBuildVectorOrConstantFP(N0))
8567     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
8568
8569   return SDValue();
8570 }
8571
8572 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
8573   SDValue N0 = N->getOperand(0);
8574   EVT VT = N->getValueType(0);
8575
8576   // fold (ftrunc c1) -> ftrunc(c1)
8577   if (isConstantFPBuildVectorOrConstantFP(N0))
8578     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
8579
8580   return SDValue();
8581 }
8582
8583 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
8584   SDValue N0 = N->getOperand(0);
8585   EVT VT = N->getValueType(0);
8586
8587   // fold (ffloor c1) -> ffloor(c1)
8588   if (isConstantFPBuildVectorOrConstantFP(N0))
8589     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
8590
8591   return SDValue();
8592 }
8593
8594 // FIXME: FNEG and FABS have a lot in common; refactor.
8595 SDValue DAGCombiner::visitFNEG(SDNode *N) {
8596   SDValue N0 = N->getOperand(0);
8597   EVT VT = N->getValueType(0);
8598
8599   // Constant fold FNEG.
8600   if (isConstantFPBuildVectorOrConstantFP(N0))
8601     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
8602
8603   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
8604                          &DAG.getTarget().Options))
8605     return GetNegatedExpression(N0, DAG, LegalOperations);
8606
8607   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
8608   // constant pool values.
8609   if (!TLI.isFNegFree(VT) &&
8610       N0.getOpcode() == ISD::BITCAST &&
8611       N0.getNode()->hasOneUse()) {
8612     SDValue Int = N0.getOperand(0);
8613     EVT IntVT = Int.getValueType();
8614     if (IntVT.isInteger() && !IntVT.isVector()) {
8615       APInt SignMask;
8616       if (N0.getValueType().isVector()) {
8617         // For a vector, get a mask such as 0x80... per scalar element
8618         // and splat it.
8619         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8620         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8621       } else {
8622         // For a scalar, just generate 0x80...
8623         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
8624       }
8625       SDLoc DL0(N0);
8626       Int = DAG.getNode(ISD::XOR, DL0, IntVT, Int,
8627                         DAG.getConstant(SignMask, DL0, IntVT));
8628       AddToWorklist(Int.getNode());
8629       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
8630     }
8631   }
8632
8633   // (fneg (fmul c, x)) -> (fmul -c, x)
8634   if (N0.getOpcode() == ISD::FMUL) {
8635     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8636     if (CFP1) {
8637       APFloat CVal = CFP1->getValueAPF();
8638       CVal.changeSign();
8639       if (Level >= AfterLegalizeDAG &&
8640           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
8641            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
8642         return DAG.getNode(
8643             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
8644             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
8645     }
8646   }
8647
8648   return SDValue();
8649 }
8650
8651 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
8652   SDValue N0 = N->getOperand(0);
8653   SDValue N1 = N->getOperand(1);
8654   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8655   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8656
8657   if (N0CFP && N1CFP) {
8658     const APFloat &C0 = N0CFP->getValueAPF();
8659     const APFloat &C1 = N1CFP->getValueAPF();
8660     return DAG.getConstantFP(minnum(C0, C1), SDLoc(N), N->getValueType(0));
8661   }
8662
8663   if (N0CFP) {
8664     EVT VT = N->getValueType(0);
8665     // Canonicalize to constant on RHS.
8666     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
8667   }
8668
8669   return SDValue();
8670 }
8671
8672 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
8673   SDValue N0 = N->getOperand(0);
8674   SDValue N1 = N->getOperand(1);
8675   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
8676   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
8677
8678   if (N0CFP && N1CFP) {
8679     const APFloat &C0 = N0CFP->getValueAPF();
8680     const APFloat &C1 = N1CFP->getValueAPF();
8681     return DAG.getConstantFP(maxnum(C0, C1), SDLoc(N), N->getValueType(0));
8682   }
8683
8684   if (N0CFP) {
8685     EVT VT = N->getValueType(0);
8686     // Canonicalize to constant on RHS.
8687     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
8688   }
8689
8690   return SDValue();
8691 }
8692
8693 SDValue DAGCombiner::visitFABS(SDNode *N) {
8694   SDValue N0 = N->getOperand(0);
8695   EVT VT = N->getValueType(0);
8696
8697   // fold (fabs c1) -> fabs(c1)
8698   if (isConstantFPBuildVectorOrConstantFP(N0))
8699     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
8700
8701   // fold (fabs (fabs x)) -> (fabs x)
8702   if (N0.getOpcode() == ISD::FABS)
8703     return N->getOperand(0);
8704
8705   // fold (fabs (fneg x)) -> (fabs x)
8706   // fold (fabs (fcopysign x, y)) -> (fabs x)
8707   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
8708     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
8709
8710   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
8711   // constant pool values.
8712   if (!TLI.isFAbsFree(VT) &&
8713       N0.getOpcode() == ISD::BITCAST &&
8714       N0.getNode()->hasOneUse()) {
8715     SDValue Int = N0.getOperand(0);
8716     EVT IntVT = Int.getValueType();
8717     if (IntVT.isInteger() && !IntVT.isVector()) {
8718       APInt SignMask;
8719       if (N0.getValueType().isVector()) {
8720         // For a vector, get a mask such as 0x7f... per scalar element
8721         // and splat it.
8722         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
8723         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
8724       } else {
8725         // For a scalar, just generate 0x7f...
8726         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
8727       }
8728       SDLoc DL(N0);
8729       Int = DAG.getNode(ISD::AND, DL, IntVT, Int,
8730                         DAG.getConstant(SignMask, DL, IntVT));
8731       AddToWorklist(Int.getNode());
8732       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8733     }
8734   }
8735
8736   return SDValue();
8737 }
8738
8739 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8740   SDValue Chain = N->getOperand(0);
8741   SDValue N1 = N->getOperand(1);
8742   SDValue N2 = N->getOperand(2);
8743
8744   // If N is a constant we could fold this into a fallthrough or unconditional
8745   // branch. However that doesn't happen very often in normal code, because
8746   // Instcombine/SimplifyCFG should have handled the available opportunities.
8747   // If we did this folding here, it would be necessary to update the
8748   // MachineBasicBlock CFG, which is awkward.
8749
8750   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8751   // on the target.
8752   if (N1.getOpcode() == ISD::SETCC &&
8753       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8754                                    N1.getOperand(0).getValueType())) {
8755     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8756                        Chain, N1.getOperand(2),
8757                        N1.getOperand(0), N1.getOperand(1), N2);
8758   }
8759
8760   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8761       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8762        (N1.getOperand(0).hasOneUse() &&
8763         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8764     SDNode *Trunc = nullptr;
8765     if (N1.getOpcode() == ISD::TRUNCATE) {
8766       // Look pass the truncate.
8767       Trunc = N1.getNode();
8768       N1 = N1.getOperand(0);
8769     }
8770
8771     // Match this pattern so that we can generate simpler code:
8772     //
8773     //   %a = ...
8774     //   %b = and i32 %a, 2
8775     //   %c = srl i32 %b, 1
8776     //   brcond i32 %c ...
8777     //
8778     // into
8779     //
8780     //   %a = ...
8781     //   %b = and i32 %a, 2
8782     //   %c = setcc eq %b, 0
8783     //   brcond %c ...
8784     //
8785     // This applies only when the AND constant value has one bit set and the
8786     // SRL constant is equal to the log2 of the AND constant. The back-end is
8787     // smart enough to convert the result into a TEST/JMP sequence.
8788     SDValue Op0 = N1.getOperand(0);
8789     SDValue Op1 = N1.getOperand(1);
8790
8791     if (Op0.getOpcode() == ISD::AND &&
8792         Op1.getOpcode() == ISD::Constant) {
8793       SDValue AndOp1 = Op0.getOperand(1);
8794
8795       if (AndOp1.getOpcode() == ISD::Constant) {
8796         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8797
8798         if (AndConst.isPowerOf2() &&
8799             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8800           SDLoc DL(N);
8801           SDValue SetCC =
8802             DAG.getSetCC(DL,
8803                          getSetCCResultType(Op0.getValueType()),
8804                          Op0, DAG.getConstant(0, DL, Op0.getValueType()),
8805                          ISD::SETNE);
8806
8807           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, DL,
8808                                           MVT::Other, Chain, SetCC, N2);
8809           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8810           // will convert it back to (X & C1) >> C2.
8811           CombineTo(N, NewBRCond, false);
8812           // Truncate is dead.
8813           if (Trunc)
8814             deleteAndRecombine(Trunc);
8815           // Replace the uses of SRL with SETCC
8816           WorklistRemover DeadNodes(*this);
8817           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8818           deleteAndRecombine(N1.getNode());
8819           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8820         }
8821       }
8822     }
8823
8824     if (Trunc)
8825       // Restore N1 if the above transformation doesn't match.
8826       N1 = N->getOperand(1);
8827   }
8828
8829   // Transform br(xor(x, y)) -> br(x != y)
8830   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8831   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8832     SDNode *TheXor = N1.getNode();
8833     SDValue Op0 = TheXor->getOperand(0);
8834     SDValue Op1 = TheXor->getOperand(1);
8835     if (Op0.getOpcode() == Op1.getOpcode()) {
8836       // Avoid missing important xor optimizations.
8837       SDValue Tmp = visitXOR(TheXor);
8838       if (Tmp.getNode()) {
8839         if (Tmp.getNode() != TheXor) {
8840           DEBUG(dbgs() << "\nReplacing.8 ";
8841                 TheXor->dump(&DAG);
8842                 dbgs() << "\nWith: ";
8843                 Tmp.getNode()->dump(&DAG);
8844                 dbgs() << '\n');
8845           WorklistRemover DeadNodes(*this);
8846           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8847           deleteAndRecombine(TheXor);
8848           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8849                              MVT::Other, Chain, Tmp, N2);
8850         }
8851
8852         // visitXOR has changed XOR's operands or replaced the XOR completely,
8853         // bail out.
8854         return SDValue(N, 0);
8855       }
8856     }
8857
8858     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8859       bool Equal = false;
8860       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8861         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8862             Op0.getOpcode() == ISD::XOR) {
8863           TheXor = Op0.getNode();
8864           Equal = true;
8865         }
8866
8867       EVT SetCCVT = N1.getValueType();
8868       if (LegalTypes)
8869         SetCCVT = getSetCCResultType(SetCCVT);
8870       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8871                                    SetCCVT,
8872                                    Op0, Op1,
8873                                    Equal ? ISD::SETEQ : ISD::SETNE);
8874       // Replace the uses of XOR with SETCC
8875       WorklistRemover DeadNodes(*this);
8876       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8877       deleteAndRecombine(N1.getNode());
8878       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8879                          MVT::Other, Chain, SetCC, N2);
8880     }
8881   }
8882
8883   return SDValue();
8884 }
8885
8886 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8887 //
8888 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8889   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8890   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8891
8892   // If N is a constant we could fold this into a fallthrough or unconditional
8893   // branch. However that doesn't happen very often in normal code, because
8894   // Instcombine/SimplifyCFG should have handled the available opportunities.
8895   // If we did this folding here, it would be necessary to update the
8896   // MachineBasicBlock CFG, which is awkward.
8897
8898   // Use SimplifySetCC to simplify SETCC's.
8899   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8900                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8901                                false);
8902   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8903
8904   // fold to a simpler setcc
8905   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8906     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8907                        N->getOperand(0), Simp.getOperand(2),
8908                        Simp.getOperand(0), Simp.getOperand(1),
8909                        N->getOperand(4));
8910
8911   return SDValue();
8912 }
8913
8914 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8915 /// and that N may be folded in the load / store addressing mode.
8916 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8917                                     SelectionDAG &DAG,
8918                                     const TargetLowering &TLI) {
8919   EVT VT;
8920   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8921     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8922       return false;
8923     VT = LD->getMemoryVT();
8924   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8925     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8926       return false;
8927     VT = ST->getMemoryVT();
8928   } else
8929     return false;
8930
8931   TargetLowering::AddrMode AM;
8932   if (N->getOpcode() == ISD::ADD) {
8933     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8934     if (Offset)
8935       // [reg +/- imm]
8936       AM.BaseOffs = Offset->getSExtValue();
8937     else
8938       // [reg +/- reg]
8939       AM.Scale = 1;
8940   } else if (N->getOpcode() == ISD::SUB) {
8941     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8942     if (Offset)
8943       // [reg +/- imm]
8944       AM.BaseOffs = -Offset->getSExtValue();
8945     else
8946       // [reg +/- reg]
8947       AM.Scale = 1;
8948   } else
8949     return false;
8950
8951   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8952 }
8953
8954 /// Try turning a load/store into a pre-indexed load/store when the base
8955 /// pointer is an add or subtract and it has other uses besides the load/store.
8956 /// After the transformation, the new indexed load/store has effectively folded
8957 /// the add/subtract in and all of its other uses are redirected to the
8958 /// new load/store.
8959 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8960   if (Level < AfterLegalizeDAG)
8961     return false;
8962
8963   bool isLoad = true;
8964   SDValue Ptr;
8965   EVT VT;
8966   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8967     if (LD->isIndexed())
8968       return false;
8969     VT = LD->getMemoryVT();
8970     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8971         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8972       return false;
8973     Ptr = LD->getBasePtr();
8974   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8975     if (ST->isIndexed())
8976       return false;
8977     VT = ST->getMemoryVT();
8978     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8979         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8980       return false;
8981     Ptr = ST->getBasePtr();
8982     isLoad = false;
8983   } else {
8984     return false;
8985   }
8986
8987   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8988   // out.  There is no reason to make this a preinc/predec.
8989   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8990       Ptr.getNode()->hasOneUse())
8991     return false;
8992
8993   // Ask the target to do addressing mode selection.
8994   SDValue BasePtr;
8995   SDValue Offset;
8996   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8997   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8998     return false;
8999
9000   // Backends without true r+i pre-indexed forms may need to pass a
9001   // constant base with a variable offset so that constant coercion
9002   // will work with the patterns in canonical form.
9003   bool Swapped = false;
9004   if (isa<ConstantSDNode>(BasePtr)) {
9005     std::swap(BasePtr, Offset);
9006     Swapped = true;
9007   }
9008
9009   // Don't create a indexed load / store with zero offset.
9010   if (isa<ConstantSDNode>(Offset) &&
9011       cast<ConstantSDNode>(Offset)->isNullValue())
9012     return false;
9013
9014   // Try turning it into a pre-indexed load / store except when:
9015   // 1) The new base ptr is a frame index.
9016   // 2) If N is a store and the new base ptr is either the same as or is a
9017   //    predecessor of the value being stored.
9018   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
9019   //    that would create a cycle.
9020   // 4) All uses are load / store ops that use it as old base ptr.
9021
9022   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
9023   // (plus the implicit offset) to a register to preinc anyway.
9024   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9025     return false;
9026
9027   // Check #2.
9028   if (!isLoad) {
9029     SDValue Val = cast<StoreSDNode>(N)->getValue();
9030     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
9031       return false;
9032   }
9033
9034   // If the offset is a constant, there may be other adds of constants that
9035   // can be folded with this one. We should do this to avoid having to keep
9036   // a copy of the original base pointer.
9037   SmallVector<SDNode *, 16> OtherUses;
9038   if (isa<ConstantSDNode>(Offset))
9039     for (SDNode *Use : BasePtr.getNode()->uses()) {
9040       if (Use == Ptr.getNode())
9041         continue;
9042
9043       if (Use->isPredecessorOf(N))
9044         continue;
9045
9046       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
9047         OtherUses.clear();
9048         break;
9049       }
9050
9051       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
9052       if (Op1.getNode() == BasePtr.getNode())
9053         std::swap(Op0, Op1);
9054       assert(Op0.getNode() == BasePtr.getNode() &&
9055              "Use of ADD/SUB but not an operand");
9056
9057       if (!isa<ConstantSDNode>(Op1)) {
9058         OtherUses.clear();
9059         break;
9060       }
9061
9062       // FIXME: In some cases, we can be smarter about this.
9063       if (Op1.getValueType() != Offset.getValueType()) {
9064         OtherUses.clear();
9065         break;
9066       }
9067
9068       OtherUses.push_back(Use);
9069     }
9070
9071   if (Swapped)
9072     std::swap(BasePtr, Offset);
9073
9074   // Now check for #3 and #4.
9075   bool RealUse = false;
9076
9077   // Caches for hasPredecessorHelper
9078   SmallPtrSet<const SDNode *, 32> Visited;
9079   SmallVector<const SDNode *, 16> Worklist;
9080
9081   for (SDNode *Use : Ptr.getNode()->uses()) {
9082     if (Use == N)
9083       continue;
9084     if (N->hasPredecessorHelper(Use, Visited, Worklist))
9085       return false;
9086
9087     // If Ptr may be folded in addressing mode of other use, then it's
9088     // not profitable to do this transformation.
9089     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
9090       RealUse = true;
9091   }
9092
9093   if (!RealUse)
9094     return false;
9095
9096   SDValue Result;
9097   if (isLoad)
9098     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9099                                 BasePtr, Offset, AM);
9100   else
9101     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9102                                  BasePtr, Offset, AM);
9103   ++PreIndexedNodes;
9104   ++NodesCombined;
9105   DEBUG(dbgs() << "\nReplacing.4 ";
9106         N->dump(&DAG);
9107         dbgs() << "\nWith: ";
9108         Result.getNode()->dump(&DAG);
9109         dbgs() << '\n');
9110   WorklistRemover DeadNodes(*this);
9111   if (isLoad) {
9112     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9113     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9114   } else {
9115     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9116   }
9117
9118   // Finally, since the node is now dead, remove it from the graph.
9119   deleteAndRecombine(N);
9120
9121   if (Swapped)
9122     std::swap(BasePtr, Offset);
9123
9124   // Replace other uses of BasePtr that can be updated to use Ptr
9125   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
9126     unsigned OffsetIdx = 1;
9127     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
9128       OffsetIdx = 0;
9129     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
9130            BasePtr.getNode() && "Expected BasePtr operand");
9131
9132     // We need to replace ptr0 in the following expression:
9133     //   x0 * offset0 + y0 * ptr0 = t0
9134     // knowing that
9135     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
9136     //
9137     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
9138     // indexed load/store and the expresion that needs to be re-written.
9139     //
9140     // Therefore, we have:
9141     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
9142
9143     ConstantSDNode *CN =
9144       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
9145     int X0, X1, Y0, Y1;
9146     APInt Offset0 = CN->getAPIntValue();
9147     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
9148
9149     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
9150     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
9151     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
9152     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
9153
9154     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
9155
9156     APInt CNV = Offset0;
9157     if (X0 < 0) CNV = -CNV;
9158     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
9159     else CNV = CNV - Offset1;
9160
9161     SDLoc DL(OtherUses[i]);
9162
9163     // We can now generate the new expression.
9164     SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
9165     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
9166
9167     SDValue NewUse = DAG.getNode(Opcode,
9168                                  DL,
9169                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
9170     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
9171     deleteAndRecombine(OtherUses[i]);
9172   }
9173
9174   // Replace the uses of Ptr with uses of the updated base value.
9175   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
9176   deleteAndRecombine(Ptr.getNode());
9177
9178   return true;
9179 }
9180
9181 /// Try to combine a load/store with a add/sub of the base pointer node into a
9182 /// post-indexed load/store. The transformation folded the add/subtract into the
9183 /// new indexed load/store effectively and all of its uses are redirected to the
9184 /// new load/store.
9185 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
9186   if (Level < AfterLegalizeDAG)
9187     return false;
9188
9189   bool isLoad = true;
9190   SDValue Ptr;
9191   EVT VT;
9192   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
9193     if (LD->isIndexed())
9194       return false;
9195     VT = LD->getMemoryVT();
9196     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
9197         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
9198       return false;
9199     Ptr = LD->getBasePtr();
9200   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
9201     if (ST->isIndexed())
9202       return false;
9203     VT = ST->getMemoryVT();
9204     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
9205         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
9206       return false;
9207     Ptr = ST->getBasePtr();
9208     isLoad = false;
9209   } else {
9210     return false;
9211   }
9212
9213   if (Ptr.getNode()->hasOneUse())
9214     return false;
9215
9216   for (SDNode *Op : Ptr.getNode()->uses()) {
9217     if (Op == N ||
9218         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
9219       continue;
9220
9221     SDValue BasePtr;
9222     SDValue Offset;
9223     ISD::MemIndexedMode AM = ISD::UNINDEXED;
9224     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
9225       // Don't create a indexed load / store with zero offset.
9226       if (isa<ConstantSDNode>(Offset) &&
9227           cast<ConstantSDNode>(Offset)->isNullValue())
9228         continue;
9229
9230       // Try turning it into a post-indexed load / store except when
9231       // 1) All uses are load / store ops that use it as base ptr (and
9232       //    it may be folded as addressing mmode).
9233       // 2) Op must be independent of N, i.e. Op is neither a predecessor
9234       //    nor a successor of N. Otherwise, if Op is folded that would
9235       //    create a cycle.
9236
9237       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
9238         continue;
9239
9240       // Check for #1.
9241       bool TryNext = false;
9242       for (SDNode *Use : BasePtr.getNode()->uses()) {
9243         if (Use == Ptr.getNode())
9244           continue;
9245
9246         // If all the uses are load / store addresses, then don't do the
9247         // transformation.
9248         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
9249           bool RealUse = false;
9250           for (SDNode *UseUse : Use->uses()) {
9251             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
9252               RealUse = true;
9253           }
9254
9255           if (!RealUse) {
9256             TryNext = true;
9257             break;
9258           }
9259         }
9260       }
9261
9262       if (TryNext)
9263         continue;
9264
9265       // Check for #2
9266       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
9267         SDValue Result = isLoad
9268           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
9269                                BasePtr, Offset, AM)
9270           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
9271                                 BasePtr, Offset, AM);
9272         ++PostIndexedNodes;
9273         ++NodesCombined;
9274         DEBUG(dbgs() << "\nReplacing.5 ";
9275               N->dump(&DAG);
9276               dbgs() << "\nWith: ";
9277               Result.getNode()->dump(&DAG);
9278               dbgs() << '\n');
9279         WorklistRemover DeadNodes(*this);
9280         if (isLoad) {
9281           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
9282           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
9283         } else {
9284           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
9285         }
9286
9287         // Finally, since the node is now dead, remove it from the graph.
9288         deleteAndRecombine(N);
9289
9290         // Replace the uses of Use with uses of the updated base value.
9291         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
9292                                       Result.getValue(isLoad ? 1 : 0));
9293         deleteAndRecombine(Op);
9294         return true;
9295       }
9296     }
9297   }
9298
9299   return false;
9300 }
9301
9302 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
9303 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
9304   ISD::MemIndexedMode AM = LD->getAddressingMode();
9305   assert(AM != ISD::UNINDEXED);
9306   SDValue BP = LD->getOperand(1);
9307   SDValue Inc = LD->getOperand(2);
9308
9309   // Some backends use TargetConstants for load offsets, but don't expect
9310   // TargetConstants in general ADD nodes. We can convert these constants into
9311   // regular Constants (if the constant is not opaque).
9312   assert((Inc.getOpcode() != ISD::TargetConstant ||
9313           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
9314          "Cannot split out indexing using opaque target constants");
9315   if (Inc.getOpcode() == ISD::TargetConstant) {
9316     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
9317     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
9318                           ConstInc->getValueType(0));
9319   }
9320
9321   unsigned Opc =
9322       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
9323   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
9324 }
9325
9326 SDValue DAGCombiner::visitLOAD(SDNode *N) {
9327   LoadSDNode *LD  = cast<LoadSDNode>(N);
9328   SDValue Chain = LD->getChain();
9329   SDValue Ptr   = LD->getBasePtr();
9330
9331   // If load is not volatile and there are no uses of the loaded value (and
9332   // the updated indexed value in case of indexed loads), change uses of the
9333   // chain value into uses of the chain input (i.e. delete the dead load).
9334   if (!LD->isVolatile()) {
9335     if (N->getValueType(1) == MVT::Other) {
9336       // Unindexed loads.
9337       if (!N->hasAnyUseOfValue(0)) {
9338         // It's not safe to use the two value CombineTo variant here. e.g.
9339         // v1, chain2 = load chain1, loc
9340         // v2, chain3 = load chain2, loc
9341         // v3         = add v2, c
9342         // Now we replace use of chain2 with chain1.  This makes the second load
9343         // isomorphic to the one we are deleting, and thus makes this load live.
9344         DEBUG(dbgs() << "\nReplacing.6 ";
9345               N->dump(&DAG);
9346               dbgs() << "\nWith chain: ";
9347               Chain.getNode()->dump(&DAG);
9348               dbgs() << "\n");
9349         WorklistRemover DeadNodes(*this);
9350         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9351
9352         if (N->use_empty())
9353           deleteAndRecombine(N);
9354
9355         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9356       }
9357     } else {
9358       // Indexed loads.
9359       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
9360
9361       // If this load has an opaque TargetConstant offset, then we cannot split
9362       // the indexing into an add/sub directly (that TargetConstant may not be
9363       // valid for a different type of node, and we cannot convert an opaque
9364       // target constant into a regular constant).
9365       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
9366                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
9367
9368       if (!N->hasAnyUseOfValue(0) &&
9369           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
9370         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
9371         SDValue Index;
9372         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
9373           Index = SplitIndexingFromLoad(LD);
9374           // Try to fold the base pointer arithmetic into subsequent loads and
9375           // stores.
9376           AddUsersToWorklist(N);
9377         } else
9378           Index = DAG.getUNDEF(N->getValueType(1));
9379         DEBUG(dbgs() << "\nReplacing.7 ";
9380               N->dump(&DAG);
9381               dbgs() << "\nWith: ";
9382               Undef.getNode()->dump(&DAG);
9383               dbgs() << " and 2 other values\n");
9384         WorklistRemover DeadNodes(*this);
9385         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
9386         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
9387         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
9388         deleteAndRecombine(N);
9389         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
9390       }
9391     }
9392   }
9393
9394   // If this load is directly stored, replace the load value with the stored
9395   // value.
9396   // TODO: Handle store large -> read small portion.
9397   // TODO: Handle TRUNCSTORE/LOADEXT
9398   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
9399     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
9400       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
9401       if (PrevST->getBasePtr() == Ptr &&
9402           PrevST->getValue().getValueType() == N->getValueType(0))
9403       return CombineTo(N, Chain.getOperand(1), Chain);
9404     }
9405   }
9406
9407   // Try to infer better alignment information than the load already has.
9408   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
9409     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9410       if (Align > LD->getMemOperand()->getBaseAlignment()) {
9411         SDValue NewLoad =
9412                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
9413                               LD->getValueType(0),
9414                               Chain, Ptr, LD->getPointerInfo(),
9415                               LD->getMemoryVT(),
9416                               LD->isVolatile(), LD->isNonTemporal(),
9417                               LD->isInvariant(), Align, LD->getAAInfo());
9418         if (NewLoad.getNode() != N)
9419           return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
9420       }
9421     }
9422   }
9423
9424   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9425                                                   : DAG.getSubtarget().useAA();
9426 #ifndef NDEBUG
9427   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9428       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9429     UseAA = false;
9430 #endif
9431   if (UseAA && LD->isUnindexed()) {
9432     // Walk up chain skipping non-aliasing memory nodes.
9433     SDValue BetterChain = FindBetterChain(N, Chain);
9434
9435     // If there is a better chain.
9436     if (Chain != BetterChain) {
9437       SDValue ReplLoad;
9438
9439       // Replace the chain to void dependency.
9440       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
9441         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
9442                                BetterChain, Ptr, LD->getMemOperand());
9443       } else {
9444         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
9445                                   LD->getValueType(0),
9446                                   BetterChain, Ptr, LD->getMemoryVT(),
9447                                   LD->getMemOperand());
9448       }
9449
9450       // Create token factor to keep old chain connected.
9451       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9452                                   MVT::Other, Chain, ReplLoad.getValue(1));
9453
9454       // Make sure the new and old chains are cleaned up.
9455       AddToWorklist(Token.getNode());
9456
9457       // Replace uses with load result and token factor. Don't add users
9458       // to work list.
9459       return CombineTo(N, ReplLoad.getValue(0), Token, false);
9460     }
9461   }
9462
9463   // Try transforming N to an indexed load.
9464   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9465     return SDValue(N, 0);
9466
9467   // Try to slice up N to more direct loads if the slices are mapped to
9468   // different register banks or pairing can take place.
9469   if (SliceUpLoad(N))
9470     return SDValue(N, 0);
9471
9472   return SDValue();
9473 }
9474
9475 namespace {
9476 /// \brief Helper structure used to slice a load in smaller loads.
9477 /// Basically a slice is obtained from the following sequence:
9478 /// Origin = load Ty1, Base
9479 /// Shift = srl Ty1 Origin, CstTy Amount
9480 /// Inst = trunc Shift to Ty2
9481 ///
9482 /// Then, it will be rewriten into:
9483 /// Slice = load SliceTy, Base + SliceOffset
9484 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
9485 ///
9486 /// SliceTy is deduced from the number of bits that are actually used to
9487 /// build Inst.
9488 struct LoadedSlice {
9489   /// \brief Helper structure used to compute the cost of a slice.
9490   struct Cost {
9491     /// Are we optimizing for code size.
9492     bool ForCodeSize;
9493     /// Various cost.
9494     unsigned Loads;
9495     unsigned Truncates;
9496     unsigned CrossRegisterBanksCopies;
9497     unsigned ZExts;
9498     unsigned Shift;
9499
9500     Cost(bool ForCodeSize = false)
9501         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
9502           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
9503
9504     /// \brief Get the cost of one isolated slice.
9505     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
9506         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
9507           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
9508       EVT TruncType = LS.Inst->getValueType(0);
9509       EVT LoadedType = LS.getLoadedType();
9510       if (TruncType != LoadedType &&
9511           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
9512         ZExts = 1;
9513     }
9514
9515     /// \brief Account for slicing gain in the current cost.
9516     /// Slicing provide a few gains like removing a shift or a
9517     /// truncate. This method allows to grow the cost of the original
9518     /// load with the gain from this slice.
9519     void addSliceGain(const LoadedSlice &LS) {
9520       // Each slice saves a truncate.
9521       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
9522       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
9523                               LS.Inst->getOperand(0).getValueType()))
9524         ++Truncates;
9525       // If there is a shift amount, this slice gets rid of it.
9526       if (LS.Shift)
9527         ++Shift;
9528       // If this slice can merge a cross register bank copy, account for it.
9529       if (LS.canMergeExpensiveCrossRegisterBankCopy())
9530         ++CrossRegisterBanksCopies;
9531     }
9532
9533     Cost &operator+=(const Cost &RHS) {
9534       Loads += RHS.Loads;
9535       Truncates += RHS.Truncates;
9536       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
9537       ZExts += RHS.ZExts;
9538       Shift += RHS.Shift;
9539       return *this;
9540     }
9541
9542     bool operator==(const Cost &RHS) const {
9543       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
9544              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
9545              ZExts == RHS.ZExts && Shift == RHS.Shift;
9546     }
9547
9548     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
9549
9550     bool operator<(const Cost &RHS) const {
9551       // Assume cross register banks copies are as expensive as loads.
9552       // FIXME: Do we want some more target hooks?
9553       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
9554       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
9555       // Unless we are optimizing for code size, consider the
9556       // expensive operation first.
9557       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
9558         return ExpensiveOpsLHS < ExpensiveOpsRHS;
9559       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
9560              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
9561     }
9562
9563     bool operator>(const Cost &RHS) const { return RHS < *this; }
9564
9565     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
9566
9567     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
9568   };
9569   // The last instruction that represent the slice. This should be a
9570   // truncate instruction.
9571   SDNode *Inst;
9572   // The original load instruction.
9573   LoadSDNode *Origin;
9574   // The right shift amount in bits from the original load.
9575   unsigned Shift;
9576   // The DAG from which Origin came from.
9577   // This is used to get some contextual information about legal types, etc.
9578   SelectionDAG *DAG;
9579
9580   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
9581               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
9582       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
9583
9584   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
9585   /// \return Result is \p BitWidth and has used bits set to 1 and
9586   ///         not used bits set to 0.
9587   APInt getUsedBits() const {
9588     // Reproduce the trunc(lshr) sequence:
9589     // - Start from the truncated value.
9590     // - Zero extend to the desired bit width.
9591     // - Shift left.
9592     assert(Origin && "No original load to compare against.");
9593     unsigned BitWidth = Origin->getValueSizeInBits(0);
9594     assert(Inst && "This slice is not bound to an instruction");
9595     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
9596            "Extracted slice is bigger than the whole type!");
9597     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
9598     UsedBits.setAllBits();
9599     UsedBits = UsedBits.zext(BitWidth);
9600     UsedBits <<= Shift;
9601     return UsedBits;
9602   }
9603
9604   /// \brief Get the size of the slice to be loaded in bytes.
9605   unsigned getLoadedSize() const {
9606     unsigned SliceSize = getUsedBits().countPopulation();
9607     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
9608     return SliceSize / 8;
9609   }
9610
9611   /// \brief Get the type that will be loaded for this slice.
9612   /// Note: This may not be the final type for the slice.
9613   EVT getLoadedType() const {
9614     assert(DAG && "Missing context");
9615     LLVMContext &Ctxt = *DAG->getContext();
9616     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
9617   }
9618
9619   /// \brief Get the alignment of the load used for this slice.
9620   unsigned getAlignment() const {
9621     unsigned Alignment = Origin->getAlignment();
9622     unsigned Offset = getOffsetFromBase();
9623     if (Offset != 0)
9624       Alignment = MinAlign(Alignment, Alignment + Offset);
9625     return Alignment;
9626   }
9627
9628   /// \brief Check if this slice can be rewritten with legal operations.
9629   bool isLegal() const {
9630     // An invalid slice is not legal.
9631     if (!Origin || !Inst || !DAG)
9632       return false;
9633
9634     // Offsets are for indexed load only, we do not handle that.
9635     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
9636       return false;
9637
9638     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9639
9640     // Check that the type is legal.
9641     EVT SliceType = getLoadedType();
9642     if (!TLI.isTypeLegal(SliceType))
9643       return false;
9644
9645     // Check that the load is legal for this type.
9646     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
9647       return false;
9648
9649     // Check that the offset can be computed.
9650     // 1. Check its type.
9651     EVT PtrType = Origin->getBasePtr().getValueType();
9652     if (PtrType == MVT::Untyped || PtrType.isExtended())
9653       return false;
9654
9655     // 2. Check that it fits in the immediate.
9656     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
9657       return false;
9658
9659     // 3. Check that the computation is legal.
9660     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
9661       return false;
9662
9663     // Check that the zext is legal if it needs one.
9664     EVT TruncateType = Inst->getValueType(0);
9665     if (TruncateType != SliceType &&
9666         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
9667       return false;
9668
9669     return true;
9670   }
9671
9672   /// \brief Get the offset in bytes of this slice in the original chunk of
9673   /// bits.
9674   /// \pre DAG != nullptr.
9675   uint64_t getOffsetFromBase() const {
9676     assert(DAG && "Missing context.");
9677     bool IsBigEndian =
9678         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
9679     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
9680     uint64_t Offset = Shift / 8;
9681     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
9682     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
9683            "The size of the original loaded type is not a multiple of a"
9684            " byte.");
9685     // If Offset is bigger than TySizeInBytes, it means we are loading all
9686     // zeros. This should have been optimized before in the process.
9687     assert(TySizeInBytes > Offset &&
9688            "Invalid shift amount for given loaded size");
9689     if (IsBigEndian)
9690       Offset = TySizeInBytes - Offset - getLoadedSize();
9691     return Offset;
9692   }
9693
9694   /// \brief Generate the sequence of instructions to load the slice
9695   /// represented by this object and redirect the uses of this slice to
9696   /// this new sequence of instructions.
9697   /// \pre this->Inst && this->Origin are valid Instructions and this
9698   /// object passed the legal check: LoadedSlice::isLegal returned true.
9699   /// \return The last instruction of the sequence used to load the slice.
9700   SDValue loadSlice() const {
9701     assert(Inst && Origin && "Unable to replace a non-existing slice.");
9702     const SDValue &OldBaseAddr = Origin->getBasePtr();
9703     SDValue BaseAddr = OldBaseAddr;
9704     // Get the offset in that chunk of bytes w.r.t. the endianess.
9705     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
9706     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
9707     if (Offset) {
9708       // BaseAddr = BaseAddr + Offset.
9709       EVT ArithType = BaseAddr.getValueType();
9710       SDLoc DL(Origin);
9711       BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
9712                               DAG->getConstant(Offset, DL, ArithType));
9713     }
9714
9715     // Create the type of the loaded slice according to its size.
9716     EVT SliceType = getLoadedType();
9717
9718     // Create the load for the slice.
9719     SDValue LastInst = DAG->getLoad(
9720         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
9721         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
9722         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
9723     // If the final type is not the same as the loaded type, this means that
9724     // we have to pad with zero. Create a zero extend for that.
9725     EVT FinalType = Inst->getValueType(0);
9726     if (SliceType != FinalType)
9727       LastInst =
9728           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
9729     return LastInst;
9730   }
9731
9732   /// \brief Check if this slice can be merged with an expensive cross register
9733   /// bank copy. E.g.,
9734   /// i = load i32
9735   /// f = bitcast i32 i to float
9736   bool canMergeExpensiveCrossRegisterBankCopy() const {
9737     if (!Inst || !Inst->hasOneUse())
9738       return false;
9739     SDNode *Use = *Inst->use_begin();
9740     if (Use->getOpcode() != ISD::BITCAST)
9741       return false;
9742     assert(DAG && "Missing context");
9743     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9744     EVT ResVT = Use->getValueType(0);
9745     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9746     const TargetRegisterClass *ArgRC =
9747         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9748     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9749       return false;
9750
9751     // At this point, we know that we perform a cross-register-bank copy.
9752     // Check if it is expensive.
9753     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9754     // Assume bitcasts are cheap, unless both register classes do not
9755     // explicitly share a common sub class.
9756     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9757       return false;
9758
9759     // Check if it will be merged with the load.
9760     // 1. Check the alignment constraint.
9761     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9762         ResVT.getTypeForEVT(*DAG->getContext()));
9763
9764     if (RequiredAlignment > getAlignment())
9765       return false;
9766
9767     // 2. Check that the load is a legal operation for that type.
9768     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9769       return false;
9770
9771     // 3. Check that we do not have a zext in the way.
9772     if (Inst->getValueType(0) != getLoadedType())
9773       return false;
9774
9775     return true;
9776   }
9777 };
9778 }
9779
9780 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9781 /// \p UsedBits looks like 0..0 1..1 0..0.
9782 static bool areUsedBitsDense(const APInt &UsedBits) {
9783   // If all the bits are one, this is dense!
9784   if (UsedBits.isAllOnesValue())
9785     return true;
9786
9787   // Get rid of the unused bits on the right.
9788   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9789   // Get rid of the unused bits on the left.
9790   if (NarrowedUsedBits.countLeadingZeros())
9791     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9792   // Check that the chunk of bits is completely used.
9793   return NarrowedUsedBits.isAllOnesValue();
9794 }
9795
9796 /// \brief Check whether or not \p First and \p Second are next to each other
9797 /// in memory. This means that there is no hole between the bits loaded
9798 /// by \p First and the bits loaded by \p Second.
9799 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9800                                      const LoadedSlice &Second) {
9801   assert(First.Origin == Second.Origin && First.Origin &&
9802          "Unable to match different memory origins.");
9803   APInt UsedBits = First.getUsedBits();
9804   assert((UsedBits & Second.getUsedBits()) == 0 &&
9805          "Slices are not supposed to overlap.");
9806   UsedBits |= Second.getUsedBits();
9807   return areUsedBitsDense(UsedBits);
9808 }
9809
9810 /// \brief Adjust the \p GlobalLSCost according to the target
9811 /// paring capabilities and the layout of the slices.
9812 /// \pre \p GlobalLSCost should account for at least as many loads as
9813 /// there is in the slices in \p LoadedSlices.
9814 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9815                                  LoadedSlice::Cost &GlobalLSCost) {
9816   unsigned NumberOfSlices = LoadedSlices.size();
9817   // If there is less than 2 elements, no pairing is possible.
9818   if (NumberOfSlices < 2)
9819     return;
9820
9821   // Sort the slices so that elements that are likely to be next to each
9822   // other in memory are next to each other in the list.
9823   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9824             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9825     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9826     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9827   });
9828   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9829   // First (resp. Second) is the first (resp. Second) potentially candidate
9830   // to be placed in a paired load.
9831   const LoadedSlice *First = nullptr;
9832   const LoadedSlice *Second = nullptr;
9833   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9834                 // Set the beginning of the pair.
9835                                                            First = Second) {
9836
9837     Second = &LoadedSlices[CurrSlice];
9838
9839     // If First is NULL, it means we start a new pair.
9840     // Get to the next slice.
9841     if (!First)
9842       continue;
9843
9844     EVT LoadedType = First->getLoadedType();
9845
9846     // If the types of the slices are different, we cannot pair them.
9847     if (LoadedType != Second->getLoadedType())
9848       continue;
9849
9850     // Check if the target supplies paired loads for this type.
9851     unsigned RequiredAlignment = 0;
9852     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9853       // move to the next pair, this type is hopeless.
9854       Second = nullptr;
9855       continue;
9856     }
9857     // Check if we meet the alignment requirement.
9858     if (RequiredAlignment > First->getAlignment())
9859       continue;
9860
9861     // Check that both loads are next to each other in memory.
9862     if (!areSlicesNextToEachOther(*First, *Second))
9863       continue;
9864
9865     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9866     --GlobalLSCost.Loads;
9867     // Move to the next pair.
9868     Second = nullptr;
9869   }
9870 }
9871
9872 /// \brief Check the profitability of all involved LoadedSlice.
9873 /// Currently, it is considered profitable if there is exactly two
9874 /// involved slices (1) which are (2) next to each other in memory, and
9875 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9876 ///
9877 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9878 /// the elements themselves.
9879 ///
9880 /// FIXME: When the cost model will be mature enough, we can relax
9881 /// constraints (1) and (2).
9882 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9883                                 const APInt &UsedBits, bool ForCodeSize) {
9884   unsigned NumberOfSlices = LoadedSlices.size();
9885   if (StressLoadSlicing)
9886     return NumberOfSlices > 1;
9887
9888   // Check (1).
9889   if (NumberOfSlices != 2)
9890     return false;
9891
9892   // Check (2).
9893   if (!areUsedBitsDense(UsedBits))
9894     return false;
9895
9896   // Check (3).
9897   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9898   // The original code has one big load.
9899   OrigCost.Loads = 1;
9900   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9901     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9902     // Accumulate the cost of all the slices.
9903     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9904     GlobalSlicingCost += SliceCost;
9905
9906     // Account as cost in the original configuration the gain obtained
9907     // with the current slices.
9908     OrigCost.addSliceGain(LS);
9909   }
9910
9911   // If the target supports paired load, adjust the cost accordingly.
9912   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9913   return OrigCost > GlobalSlicingCost;
9914 }
9915
9916 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9917 /// operations, split it in the various pieces being extracted.
9918 ///
9919 /// This sort of thing is introduced by SROA.
9920 /// This slicing takes care not to insert overlapping loads.
9921 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9922 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9923   if (Level < AfterLegalizeDAG)
9924     return false;
9925
9926   LoadSDNode *LD = cast<LoadSDNode>(N);
9927   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9928       !LD->getValueType(0).isInteger())
9929     return false;
9930
9931   // Keep track of already used bits to detect overlapping values.
9932   // In that case, we will just abort the transformation.
9933   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9934
9935   SmallVector<LoadedSlice, 4> LoadedSlices;
9936
9937   // Check if this load is used as several smaller chunks of bits.
9938   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9939   // of computation for each trunc.
9940   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9941        UI != UIEnd; ++UI) {
9942     // Skip the uses of the chain.
9943     if (UI.getUse().getResNo() != 0)
9944       continue;
9945
9946     SDNode *User = *UI;
9947     unsigned Shift = 0;
9948
9949     // Check if this is a trunc(lshr).
9950     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9951         isa<ConstantSDNode>(User->getOperand(1))) {
9952       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9953       User = *User->use_begin();
9954     }
9955
9956     // At this point, User is a Truncate, iff we encountered, trunc or
9957     // trunc(lshr).
9958     if (User->getOpcode() != ISD::TRUNCATE)
9959       return false;
9960
9961     // The width of the type must be a power of 2 and greater than 8-bits.
9962     // Otherwise the load cannot be represented in LLVM IR.
9963     // Moreover, if we shifted with a non-8-bits multiple, the slice
9964     // will be across several bytes. We do not support that.
9965     unsigned Width = User->getValueSizeInBits(0);
9966     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9967       return 0;
9968
9969     // Build the slice for this chain of computations.
9970     LoadedSlice LS(User, LD, Shift, &DAG);
9971     APInt CurrentUsedBits = LS.getUsedBits();
9972
9973     // Check if this slice overlaps with another.
9974     if ((CurrentUsedBits & UsedBits) != 0)
9975       return false;
9976     // Update the bits used globally.
9977     UsedBits |= CurrentUsedBits;
9978
9979     // Check if the new slice would be legal.
9980     if (!LS.isLegal())
9981       return false;
9982
9983     // Record the slice.
9984     LoadedSlices.push_back(LS);
9985   }
9986
9987   // Abort slicing if it does not seem to be profitable.
9988   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9989     return false;
9990
9991   ++SlicedLoads;
9992
9993   // Rewrite each chain to use an independent load.
9994   // By construction, each chain can be represented by a unique load.
9995
9996   // Prepare the argument for the new token factor for all the slices.
9997   SmallVector<SDValue, 8> ArgChains;
9998   for (SmallVectorImpl<LoadedSlice>::const_iterator
9999            LSIt = LoadedSlices.begin(),
10000            LSItEnd = LoadedSlices.end();
10001        LSIt != LSItEnd; ++LSIt) {
10002     SDValue SliceInst = LSIt->loadSlice();
10003     CombineTo(LSIt->Inst, SliceInst, true);
10004     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
10005       SliceInst = SliceInst.getOperand(0);
10006     assert(SliceInst->getOpcode() == ISD::LOAD &&
10007            "It takes more than a zext to get to the loaded slice!!");
10008     ArgChains.push_back(SliceInst.getValue(1));
10009   }
10010
10011   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
10012                               ArgChains);
10013   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
10014   return true;
10015 }
10016
10017 /// Check to see if V is (and load (ptr), imm), where the load is having
10018 /// specific bytes cleared out.  If so, return the byte size being masked out
10019 /// and the shift amount.
10020 static std::pair<unsigned, unsigned>
10021 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
10022   std::pair<unsigned, unsigned> Result(0, 0);
10023
10024   // Check for the structure we're looking for.
10025   if (V->getOpcode() != ISD::AND ||
10026       !isa<ConstantSDNode>(V->getOperand(1)) ||
10027       !ISD::isNormalLoad(V->getOperand(0).getNode()))
10028     return Result;
10029
10030   // Check the chain and pointer.
10031   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
10032   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
10033
10034   // The store should be chained directly to the load or be an operand of a
10035   // tokenfactor.
10036   if (LD == Chain.getNode())
10037     ; // ok.
10038   else if (Chain->getOpcode() != ISD::TokenFactor)
10039     return Result; // Fail.
10040   else {
10041     bool isOk = false;
10042     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
10043       if (Chain->getOperand(i).getNode() == LD) {
10044         isOk = true;
10045         break;
10046       }
10047     if (!isOk) return Result;
10048   }
10049
10050   // This only handles simple types.
10051   if (V.getValueType() != MVT::i16 &&
10052       V.getValueType() != MVT::i32 &&
10053       V.getValueType() != MVT::i64)
10054     return Result;
10055
10056   // Check the constant mask.  Invert it so that the bits being masked out are
10057   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
10058   // follow the sign bit for uniformity.
10059   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
10060   unsigned NotMaskLZ = countLeadingZeros(NotMask);
10061   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
10062   unsigned NotMaskTZ = countTrailingZeros(NotMask);
10063   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
10064   if (NotMaskLZ == 64) return Result;  // All zero mask.
10065
10066   // See if we have a continuous run of bits.  If so, we have 0*1+0*
10067   if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
10068     return Result;
10069
10070   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
10071   if (V.getValueType() != MVT::i64 && NotMaskLZ)
10072     NotMaskLZ -= 64-V.getValueSizeInBits();
10073
10074   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
10075   switch (MaskedBytes) {
10076   case 1:
10077   case 2:
10078   case 4: break;
10079   default: return Result; // All one mask, or 5-byte mask.
10080   }
10081
10082   // Verify that the first bit starts at a multiple of mask so that the access
10083   // is aligned the same as the access width.
10084   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
10085
10086   Result.first = MaskedBytes;
10087   Result.second = NotMaskTZ/8;
10088   return Result;
10089 }
10090
10091
10092 /// Check to see if IVal is something that provides a value as specified by
10093 /// MaskInfo. If so, replace the specified store with a narrower store of
10094 /// truncated IVal.
10095 static SDNode *
10096 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
10097                                 SDValue IVal, StoreSDNode *St,
10098                                 DAGCombiner *DC) {
10099   unsigned NumBytes = MaskInfo.first;
10100   unsigned ByteShift = MaskInfo.second;
10101   SelectionDAG &DAG = DC->getDAG();
10102
10103   // Check to see if IVal is all zeros in the part being masked in by the 'or'
10104   // that uses this.  If not, this is not a replacement.
10105   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
10106                                   ByteShift*8, (ByteShift+NumBytes)*8);
10107   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
10108
10109   // Check that it is legal on the target to do this.  It is legal if the new
10110   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
10111   // legalization.
10112   MVT VT = MVT::getIntegerVT(NumBytes*8);
10113   if (!DC->isTypeLegal(VT))
10114     return nullptr;
10115
10116   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
10117   // shifted by ByteShift and truncated down to NumBytes.
10118   if (ByteShift) {
10119     SDLoc DL(IVal);
10120     IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
10121                        DAG.getConstant(ByteShift*8, DL,
10122                                     DC->getShiftAmountTy(IVal.getValueType())));
10123   }
10124
10125   // Figure out the offset for the store and the alignment of the access.
10126   unsigned StOffset;
10127   unsigned NewAlign = St->getAlignment();
10128
10129   if (DAG.getTargetLoweringInfo().isLittleEndian())
10130     StOffset = ByteShift;
10131   else
10132     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
10133
10134   SDValue Ptr = St->getBasePtr();
10135   if (StOffset) {
10136     SDLoc DL(IVal);
10137     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(),
10138                       Ptr, DAG.getConstant(StOffset, DL, Ptr.getValueType()));
10139     NewAlign = MinAlign(NewAlign, StOffset);
10140   }
10141
10142   // Truncate down to the new size.
10143   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
10144
10145   ++OpsNarrowed;
10146   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
10147                       St->getPointerInfo().getWithOffset(StOffset),
10148                       false, false, NewAlign).getNode();
10149 }
10150
10151
10152 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
10153 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
10154 /// narrowing the load and store if it would end up being a win for performance
10155 /// or code size.
10156 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
10157   StoreSDNode *ST  = cast<StoreSDNode>(N);
10158   if (ST->isVolatile())
10159     return SDValue();
10160
10161   SDValue Chain = ST->getChain();
10162   SDValue Value = ST->getValue();
10163   SDValue Ptr   = ST->getBasePtr();
10164   EVT VT = Value.getValueType();
10165
10166   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
10167     return SDValue();
10168
10169   unsigned Opc = Value.getOpcode();
10170
10171   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
10172   // is a byte mask indicating a consecutive number of bytes, check to see if
10173   // Y is known to provide just those bytes.  If so, we try to replace the
10174   // load + replace + store sequence with a single (narrower) store, which makes
10175   // the load dead.
10176   if (Opc == ISD::OR) {
10177     std::pair<unsigned, unsigned> MaskedLoad;
10178     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
10179     if (MaskedLoad.first)
10180       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10181                                                   Value.getOperand(1), ST,this))
10182         return SDValue(NewST, 0);
10183
10184     // Or is commutative, so try swapping X and Y.
10185     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
10186     if (MaskedLoad.first)
10187       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
10188                                                   Value.getOperand(0), ST,this))
10189         return SDValue(NewST, 0);
10190   }
10191
10192   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
10193       Value.getOperand(1).getOpcode() != ISD::Constant)
10194     return SDValue();
10195
10196   SDValue N0 = Value.getOperand(0);
10197   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
10198       Chain == SDValue(N0.getNode(), 1)) {
10199     LoadSDNode *LD = cast<LoadSDNode>(N0);
10200     if (LD->getBasePtr() != Ptr ||
10201         LD->getPointerInfo().getAddrSpace() !=
10202         ST->getPointerInfo().getAddrSpace())
10203       return SDValue();
10204
10205     // Find the type to narrow it the load / op / store to.
10206     SDValue N1 = Value.getOperand(1);
10207     unsigned BitWidth = N1.getValueSizeInBits();
10208     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
10209     if (Opc == ISD::AND)
10210       Imm ^= APInt::getAllOnesValue(BitWidth);
10211     if (Imm == 0 || Imm.isAllOnesValue())
10212       return SDValue();
10213     unsigned ShAmt = Imm.countTrailingZeros();
10214     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
10215     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
10216     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10217     // The narrowing should be profitable, the load/store operation should be
10218     // legal (or custom) and the store size should be equal to the NewVT width.
10219     while (NewBW < BitWidth &&
10220            (NewVT.getStoreSizeInBits() != NewBW ||
10221             !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
10222             !TLI.isNarrowingProfitable(VT, NewVT))) {
10223       NewBW = NextPowerOf2(NewBW);
10224       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
10225     }
10226     if (NewBW >= BitWidth)
10227       return SDValue();
10228
10229     // If the lsb changed does not start at the type bitwidth boundary,
10230     // start at the previous one.
10231     if (ShAmt % NewBW)
10232       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
10233     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
10234                                    std::min(BitWidth, ShAmt + NewBW));
10235     if ((Imm & Mask) == Imm) {
10236       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
10237       if (Opc == ISD::AND)
10238         NewImm ^= APInt::getAllOnesValue(NewBW);
10239       uint64_t PtrOff = ShAmt / 8;
10240       // For big endian targets, we need to adjust the offset to the pointer to
10241       // load the correct bytes.
10242       if (TLI.isBigEndian())
10243         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
10244
10245       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
10246       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
10247       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
10248         return SDValue();
10249
10250       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
10251                                    Ptr.getValueType(), Ptr,
10252                                    DAG.getConstant(PtrOff, SDLoc(LD),
10253                                                    Ptr.getValueType()));
10254       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
10255                                   LD->getChain(), NewPtr,
10256                                   LD->getPointerInfo().getWithOffset(PtrOff),
10257                                   LD->isVolatile(), LD->isNonTemporal(),
10258                                   LD->isInvariant(), NewAlign,
10259                                   LD->getAAInfo());
10260       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
10261                                    DAG.getConstant(NewImm, SDLoc(Value),
10262                                                    NewVT));
10263       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
10264                                    NewVal, NewPtr,
10265                                    ST->getPointerInfo().getWithOffset(PtrOff),
10266                                    false, false, NewAlign);
10267
10268       AddToWorklist(NewPtr.getNode());
10269       AddToWorklist(NewLD.getNode());
10270       AddToWorklist(NewVal.getNode());
10271       WorklistRemover DeadNodes(*this);
10272       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
10273       ++OpsNarrowed;
10274       return NewST;
10275     }
10276   }
10277
10278   return SDValue();
10279 }
10280
10281 /// For a given floating point load / store pair, if the load value isn't used
10282 /// by any other operations, then consider transforming the pair to integer
10283 /// load / store operations if the target deems the transformation profitable.
10284 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
10285   StoreSDNode *ST  = cast<StoreSDNode>(N);
10286   SDValue Chain = ST->getChain();
10287   SDValue Value = ST->getValue();
10288   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
10289       Value.hasOneUse() &&
10290       Chain == SDValue(Value.getNode(), 1)) {
10291     LoadSDNode *LD = cast<LoadSDNode>(Value);
10292     EVT VT = LD->getMemoryVT();
10293     if (!VT.isFloatingPoint() ||
10294         VT != ST->getMemoryVT() ||
10295         LD->isNonTemporal() ||
10296         ST->isNonTemporal() ||
10297         LD->getPointerInfo().getAddrSpace() != 0 ||
10298         ST->getPointerInfo().getAddrSpace() != 0)
10299       return SDValue();
10300
10301     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
10302     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
10303         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
10304         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
10305         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
10306       return SDValue();
10307
10308     unsigned LDAlign = LD->getAlignment();
10309     unsigned STAlign = ST->getAlignment();
10310     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
10311     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
10312     if (LDAlign < ABIAlign || STAlign < ABIAlign)
10313       return SDValue();
10314
10315     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
10316                                 LD->getChain(), LD->getBasePtr(),
10317                                 LD->getPointerInfo(),
10318                                 false, false, false, LDAlign);
10319
10320     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
10321                                  NewLD, ST->getBasePtr(),
10322                                  ST->getPointerInfo(),
10323                                  false, false, STAlign);
10324
10325     AddToWorklist(NewLD.getNode());
10326     AddToWorklist(NewST.getNode());
10327     WorklistRemover DeadNodes(*this);
10328     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
10329     ++LdStFP2Int;
10330     return NewST;
10331   }
10332
10333   return SDValue();
10334 }
10335
10336 namespace {
10337 /// Helper struct to parse and store a memory address as base + index + offset.
10338 /// We ignore sign extensions when it is safe to do so.
10339 /// The following two expressions are not equivalent. To differentiate we need
10340 /// to store whether there was a sign extension involved in the index
10341 /// computation.
10342 ///  (load (i64 add (i64 copyfromreg %c)
10343 ///                 (i64 signextend (add (i8 load %index)
10344 ///                                      (i8 1))))
10345 /// vs
10346 ///
10347 /// (load (i64 add (i64 copyfromreg %c)
10348 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
10349 ///                                         (i32 1)))))
10350 struct BaseIndexOffset {
10351   SDValue Base;
10352   SDValue Index;
10353   int64_t Offset;
10354   bool IsIndexSignExt;
10355
10356   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
10357
10358   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
10359                   bool IsIndexSignExt) :
10360     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
10361
10362   bool equalBaseIndex(const BaseIndexOffset &Other) {
10363     return Other.Base == Base && Other.Index == Index &&
10364       Other.IsIndexSignExt == IsIndexSignExt;
10365   }
10366
10367   /// Parses tree in Ptr for base, index, offset addresses.
10368   static BaseIndexOffset match(SDValue Ptr) {
10369     bool IsIndexSignExt = false;
10370
10371     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
10372     // instruction, then it could be just the BASE or everything else we don't
10373     // know how to handle. Just use Ptr as BASE and give up.
10374     if (Ptr->getOpcode() != ISD::ADD)
10375       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10376
10377     // We know that we have at least an ADD instruction. Try to pattern match
10378     // the simple case of BASE + OFFSET.
10379     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
10380       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
10381       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
10382                               IsIndexSignExt);
10383     }
10384
10385     // Inside a loop the current BASE pointer is calculated using an ADD and a
10386     // MUL instruction. In this case Ptr is the actual BASE pointer.
10387     // (i64 add (i64 %array_ptr)
10388     //          (i64 mul (i64 %induction_var)
10389     //                   (i64 %element_size)))
10390     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
10391       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10392
10393     // Look at Base + Index + Offset cases.
10394     SDValue Base = Ptr->getOperand(0);
10395     SDValue IndexOffset = Ptr->getOperand(1);
10396
10397     // Skip signextends.
10398     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
10399       IndexOffset = IndexOffset->getOperand(0);
10400       IsIndexSignExt = true;
10401     }
10402
10403     // Either the case of Base + Index (no offset) or something else.
10404     if (IndexOffset->getOpcode() != ISD::ADD)
10405       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
10406
10407     // Now we have the case of Base + Index + offset.
10408     SDValue Index = IndexOffset->getOperand(0);
10409     SDValue Offset = IndexOffset->getOperand(1);
10410
10411     if (!isa<ConstantSDNode>(Offset))
10412       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
10413
10414     // Ignore signextends.
10415     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
10416       Index = Index->getOperand(0);
10417       IsIndexSignExt = true;
10418     } else IsIndexSignExt = false;
10419
10420     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
10421     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
10422   }
10423 };
10424 } // namespace
10425
10426 bool DAGCombiner::MergeStoresOfConstantsOrVecElts(
10427                   SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT,
10428                   unsigned NumElem, bool IsConstantSrc, bool UseVector) {
10429   // Make sure we have something to merge.
10430   if (NumElem < 2)
10431     return false;
10432
10433   int64_t ElementSizeBytes = MemVT.getSizeInBits() / 8;
10434   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10435   unsigned LatestNodeUsed = 0;
10436
10437   for (unsigned i=0; i < NumElem; ++i) {
10438     // Find a chain for the new wide-store operand. Notice that some
10439     // of the store nodes that we found may not be selected for inclusion
10440     // in the wide store. The chain we use needs to be the chain of the
10441     // latest store node which is *used* and replaced by the wide store.
10442     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10443       LatestNodeUsed = i;
10444   }
10445
10446   // The latest Node in the DAG.
10447   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10448   SDLoc DL(StoreNodes[0].MemNode);
10449
10450   SDValue StoredVal;
10451   if (UseVector) {
10452     // Find a legal type for the vector store.
10453     EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10454     assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
10455     if (IsConstantSrc) {
10456       // A vector store with a constant source implies that the constant is
10457       // zero; we only handle merging stores of constant zeros because the zero
10458       // can be materialized without a load.
10459       // It may be beneficial to loosen this restriction to allow non-zero
10460       // store merging.
10461       StoredVal = DAG.getConstant(0, DL, Ty);
10462     } else {
10463       SmallVector<SDValue, 8> Ops;
10464       for (unsigned i = 0; i < NumElem ; ++i) {
10465         StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10466         SDValue Val = St->getValue();
10467         // All of the operands of a BUILD_VECTOR must have the same type.
10468         if (Val.getValueType() != MemVT)
10469           return false;
10470         Ops.push_back(Val);
10471       }
10472
10473       // Build the extracted vector elements back into a vector.
10474       StoredVal = DAG.getNode(ISD::BUILD_VECTOR, DL, Ty, Ops);
10475     }
10476   } else {
10477     // We should always use a vector store when merging extracted vector
10478     // elements, so this path implies a store of constants.
10479     assert(IsConstantSrc && "Merged vector elements should use vector store");
10480
10481     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10482     APInt StoreInt(StoreBW, 0);
10483
10484     // Construct a single integer constant which is made of the smaller
10485     // constant inputs.
10486     bool IsLE = TLI.isLittleEndian();
10487     for (unsigned i = 0; i < NumElem ; ++i) {
10488       unsigned Idx = IsLE ? (NumElem - 1 - i) : i;
10489       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
10490       SDValue Val = St->getValue();
10491       StoreInt <<= ElementSizeBytes*8;
10492       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
10493         StoreInt |= C->getAPIntValue().zext(StoreBW);
10494       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
10495         StoreInt |= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
10496       } else {
10497         llvm_unreachable("Invalid constant element type");
10498       }
10499     }
10500
10501     // Create the new Load and Store operations.
10502     EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10503     StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
10504   }
10505
10506   SDValue NewStore = DAG.getStore(LatestOp->getChain(), DL, StoredVal,
10507                                   FirstInChain->getBasePtr(),
10508                                   FirstInChain->getPointerInfo(),
10509                                   false, false,
10510                                   FirstInChain->getAlignment());
10511
10512   // Replace the last store with the new store
10513   CombineTo(LatestOp, NewStore);
10514   // Erase all other stores.
10515   for (unsigned i = 0; i < NumElem ; ++i) {
10516     if (StoreNodes[i].MemNode == LatestOp)
10517       continue;
10518     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10519     // ReplaceAllUsesWith will replace all uses that existed when it was
10520     // called, but graph optimizations may cause new ones to appear. For
10521     // example, the case in pr14333 looks like
10522     //
10523     //  St's chain -> St -> another store -> X
10524     //
10525     // And the only difference from St to the other store is the chain.
10526     // When we change it's chain to be St's chain they become identical,
10527     // get CSEed and the net result is that X is now a use of St.
10528     // Since we know that St is redundant, just iterate.
10529     while (!St->use_empty())
10530       DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
10531     deleteAndRecombine(St);
10532   }
10533
10534   return true;
10535 }
10536
10537 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
10538   if (OptLevel == CodeGenOpt::None)
10539     return false;
10540
10541   EVT MemVT = St->getMemoryVT();
10542   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
10543   bool NoVectors = DAG.getMachineFunction().getFunction()->hasFnAttribute(
10544       Attribute::NoImplicitFloat);
10545
10546   // Don't merge vectors into wider inputs.
10547   if (MemVT.isVector() || !MemVT.isSimple())
10548     return false;
10549
10550   // Perform an early exit check. Do not bother looking at stored values that
10551   // are not constants, loads, or extracted vector elements.
10552   SDValue StoredVal = St->getValue();
10553   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
10554   bool IsConstantSrc = isa<ConstantSDNode>(StoredVal) ||
10555                        isa<ConstantFPSDNode>(StoredVal);
10556   bool IsExtractVecEltSrc = (StoredVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT);
10557
10558   if (!IsConstantSrc && !IsLoadSrc && !IsExtractVecEltSrc)
10559     return false;
10560
10561   // Only look at ends of store sequences.
10562   SDValue Chain = SDValue(St, 0);
10563   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
10564     return false;
10565
10566   // This holds the base pointer, index, and the offset in bytes from the base
10567   // pointer.
10568   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
10569
10570   // We must have a base and an offset.
10571   if (!BasePtr.Base.getNode())
10572     return false;
10573
10574   // Do not handle stores to undef base pointers.
10575   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
10576     return false;
10577
10578   // Save the LoadSDNodes that we find in the chain.
10579   // We need to make sure that these nodes do not interfere with
10580   // any of the store nodes.
10581   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
10582
10583   // Save the StoreSDNodes that we find in the chain.
10584   SmallVector<MemOpLink, 8> StoreNodes;
10585
10586   // Walk up the chain and look for nodes with offsets from the same
10587   // base pointer. Stop when reaching an instruction with a different kind
10588   // or instruction which has a different base pointer.
10589   unsigned Seq = 0;
10590   StoreSDNode *Index = St;
10591   while (Index) {
10592     // If the chain has more than one use, then we can't reorder the mem ops.
10593     if (Index != St && !SDValue(Index, 0)->hasOneUse())
10594       break;
10595
10596     // Find the base pointer and offset for this memory node.
10597     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
10598
10599     // Check that the base pointer is the same as the original one.
10600     if (!Ptr.equalBaseIndex(BasePtr))
10601       break;
10602
10603     // Check that the alignment is the same.
10604     if (Index->getAlignment() != St->getAlignment())
10605       break;
10606
10607     // The memory operands must not be volatile.
10608     if (Index->isVolatile() || Index->isIndexed())
10609       break;
10610
10611     // No truncation.
10612     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
10613       if (St->isTruncatingStore())
10614         break;
10615
10616     // The stored memory type must be the same.
10617     if (Index->getMemoryVT() != MemVT)
10618       break;
10619
10620     // We do not allow unaligned stores because we want to prevent overriding
10621     // stores.
10622     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
10623       break;
10624
10625     // We found a potential memory operand to merge.
10626     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
10627
10628     // Find the next memory operand in the chain. If the next operand in the
10629     // chain is a store then move up and continue the scan with the next
10630     // memory operand. If the next operand is a load save it and use alias
10631     // information to check if it interferes with anything.
10632     SDNode *NextInChain = Index->getChain().getNode();
10633     while (1) {
10634       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
10635         // We found a store node. Use it for the next iteration.
10636         Index = STn;
10637         break;
10638       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
10639         if (Ldn->isVolatile()) {
10640           Index = nullptr;
10641           break;
10642         }
10643
10644         // Save the load node for later. Continue the scan.
10645         AliasLoadNodes.push_back(Ldn);
10646         NextInChain = Ldn->getChain().getNode();
10647         continue;
10648       } else {
10649         Index = nullptr;
10650         break;
10651       }
10652     }
10653   }
10654
10655   // Check if there is anything to merge.
10656   if (StoreNodes.size() < 2)
10657     return false;
10658
10659   // Sort the memory operands according to their distance from the base pointer.
10660   std::sort(StoreNodes.begin(), StoreNodes.end(),
10661             [](MemOpLink LHS, MemOpLink RHS) {
10662     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
10663            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
10664             LHS.SequenceNum > RHS.SequenceNum);
10665   });
10666
10667   // Scan the memory operations on the chain and find the first non-consecutive
10668   // store memory address.
10669   unsigned LastConsecutiveStore = 0;
10670   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
10671   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
10672
10673     // Check that the addresses are consecutive starting from the second
10674     // element in the list of stores.
10675     if (i > 0) {
10676       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
10677       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10678         break;
10679     }
10680
10681     bool Alias = false;
10682     // Check if this store interferes with any of the loads that we found.
10683     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
10684       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
10685         Alias = true;
10686         break;
10687       }
10688     // We found a load that alias with this store. Stop the sequence.
10689     if (Alias)
10690       break;
10691
10692     // Mark this node as useful.
10693     LastConsecutiveStore = i;
10694   }
10695
10696   // The node with the lowest store address.
10697   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
10698
10699   // Store the constants into memory as one consecutive store.
10700   if (IsConstantSrc) {
10701     unsigned LastLegalType = 0;
10702     unsigned LastLegalVectorType = 0;
10703     bool NonZero = false;
10704     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10705       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10706       SDValue StoredVal = St->getValue();
10707
10708       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
10709         NonZero |= !C->isNullValue();
10710       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
10711         NonZero |= !C->getConstantFPValue()->isNullValue();
10712       } else {
10713         // Non-constant.
10714         break;
10715       }
10716
10717       // Find a legal type for the constant store.
10718       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10719       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10720       if (TLI.isTypeLegal(StoreTy))
10721         LastLegalType = i+1;
10722       // Or check whether a truncstore is legal.
10723       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10724                TargetLowering::TypePromoteInteger) {
10725         EVT LegalizedStoredValueTy =
10726           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
10727         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
10728           LastLegalType = i+1;
10729       }
10730
10731       // Find a legal type for the vector store.
10732       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10733       if (TLI.isTypeLegal(Ty))
10734         LastLegalVectorType = i + 1;
10735     }
10736
10737     // We only use vectors if the constant is known to be zero and the
10738     // function is not marked with the noimplicitfloat attribute.
10739     if (NonZero || NoVectors)
10740       LastLegalVectorType = 0;
10741
10742     // Check if we found a legal integer type to store.
10743     if (LastLegalType == 0 && LastLegalVectorType == 0)
10744       return false;
10745
10746     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
10747     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
10748
10749     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10750                                            true, UseVector);
10751   }
10752
10753   // When extracting multiple vector elements, try to store them
10754   // in one vector store rather than a sequence of scalar stores.
10755   if (IsExtractVecEltSrc) {
10756     unsigned NumElem = 0;
10757     for (unsigned i = 0; i < LastConsecutiveStore + 1; ++i) {
10758       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10759       SDValue StoredVal = St->getValue();
10760       // This restriction could be loosened.
10761       // Bail out if any stored values are not elements extracted from a vector.
10762       // It should be possible to handle mixed sources, but load sources need
10763       // more careful handling (see the block of code below that handles
10764       // consecutive loads).
10765       if (StoredVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10766         return false;
10767
10768       // Find a legal type for the vector store.
10769       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10770       if (TLI.isTypeLegal(Ty))
10771         NumElem = i + 1;
10772     }
10773
10774     return MergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
10775                                            false, true);
10776   }
10777
10778   // Below we handle the case of multiple consecutive stores that
10779   // come from multiple consecutive loads. We merge them into a single
10780   // wide load and a single wide store.
10781
10782   // Look for load nodes which are used by the stored values.
10783   SmallVector<MemOpLink, 8> LoadNodes;
10784
10785   // Find acceptable loads. Loads need to have the same chain (token factor),
10786   // must not be zext, volatile, indexed, and they must be consecutive.
10787   BaseIndexOffset LdBasePtr;
10788   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
10789     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
10790     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
10791     if (!Ld) break;
10792
10793     // Loads must only have one use.
10794     if (!Ld->hasNUsesOfValue(1, 0))
10795       break;
10796
10797     // Check that the alignment is the same as the stores.
10798     if (Ld->getAlignment() != St->getAlignment())
10799       break;
10800
10801     // The memory operands must not be volatile.
10802     if (Ld->isVolatile() || Ld->isIndexed())
10803       break;
10804
10805     // We do not accept ext loads.
10806     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10807       break;
10808
10809     // The stored memory type must be the same.
10810     if (Ld->getMemoryVT() != MemVT)
10811       break;
10812
10813     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10814     // If this is not the first ptr that we check.
10815     if (LdBasePtr.Base.getNode()) {
10816       // The base ptr must be the same.
10817       if (!LdPtr.equalBaseIndex(LdBasePtr))
10818         break;
10819     } else {
10820       // Check that all other base pointers are the same as this one.
10821       LdBasePtr = LdPtr;
10822     }
10823
10824     // We found a potential memory operand to merge.
10825     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10826   }
10827
10828   if (LoadNodes.size() < 2)
10829     return false;
10830
10831   // If we have load/store pair instructions and we only have two values,
10832   // don't bother.
10833   unsigned RequiredAlignment;
10834   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10835       St->getAlignment() >= RequiredAlignment)
10836     return false;
10837
10838   // Scan the memory operations on the chain and find the first non-consecutive
10839   // load memory address. These variables hold the index in the store node
10840   // array.
10841   unsigned LastConsecutiveLoad = 0;
10842   // This variable refers to the size and not index in the array.
10843   unsigned LastLegalVectorType = 0;
10844   unsigned LastLegalIntegerType = 0;
10845   StartAddress = LoadNodes[0].OffsetFromBase;
10846   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10847   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10848     // All loads much share the same chain.
10849     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10850       break;
10851
10852     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10853     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10854       break;
10855     LastConsecutiveLoad = i;
10856
10857     // Find a legal type for the vector store.
10858     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10859     if (TLI.isTypeLegal(StoreTy))
10860       LastLegalVectorType = i + 1;
10861
10862     // Find a legal type for the integer store.
10863     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10864     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10865     if (TLI.isTypeLegal(StoreTy))
10866       LastLegalIntegerType = i + 1;
10867     // Or check whether a truncstore and extload is legal.
10868     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10869              TargetLowering::TypePromoteInteger) {
10870       EVT LegalizedStoredValueTy =
10871         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10872       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10873           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10874           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10875           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10876         LastLegalIntegerType = i+1;
10877     }
10878   }
10879
10880   // Only use vector types if the vector type is larger than the integer type.
10881   // If they are the same, use integers.
10882   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10883   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10884
10885   // We add +1 here because the LastXXX variables refer to location while
10886   // the NumElem refers to array/index size.
10887   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10888   NumElem = std::min(LastLegalType, NumElem);
10889
10890   if (NumElem < 2)
10891     return false;
10892
10893   // The latest Node in the DAG.
10894   unsigned LatestNodeUsed = 0;
10895   for (unsigned i=1; i<NumElem; ++i) {
10896     // Find a chain for the new wide-store operand. Notice that some
10897     // of the store nodes that we found may not be selected for inclusion
10898     // in the wide store. The chain we use needs to be the chain of the
10899     // latest store node which is *used* and replaced by the wide store.
10900     if (StoreNodes[i].SequenceNum < StoreNodes[LatestNodeUsed].SequenceNum)
10901       LatestNodeUsed = i;
10902   }
10903
10904   LSBaseSDNode *LatestOp = StoreNodes[LatestNodeUsed].MemNode;
10905
10906   // Find if it is better to use vectors or integers to load and store
10907   // to memory.
10908   EVT JointMemOpVT;
10909   if (UseVectorTy) {
10910     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10911   } else {
10912     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10913     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10914   }
10915
10916   SDLoc LoadDL(LoadNodes[0].MemNode);
10917   SDLoc StoreDL(StoreNodes[0].MemNode);
10918
10919   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10920   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10921                                 FirstLoad->getChain(),
10922                                 FirstLoad->getBasePtr(),
10923                                 FirstLoad->getPointerInfo(),
10924                                 false, false, false,
10925                                 FirstLoad->getAlignment());
10926
10927   SDValue NewStore = DAG.getStore(LatestOp->getChain(), StoreDL, NewLoad,
10928                                   FirstInChain->getBasePtr(),
10929                                   FirstInChain->getPointerInfo(), false, false,
10930                                   FirstInChain->getAlignment());
10931
10932   // Replace one of the loads with the new load.
10933   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10934   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10935                                 SDValue(NewLoad.getNode(), 1));
10936
10937   // Remove the rest of the load chains.
10938   for (unsigned i = 1; i < NumElem ; ++i) {
10939     // Replace all chain users of the old load nodes with the chain of the new
10940     // load node.
10941     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10942     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10943   }
10944
10945   // Replace the last store with the new store.
10946   CombineTo(LatestOp, NewStore);
10947   // Erase all other stores.
10948   for (unsigned i = 0; i < NumElem ; ++i) {
10949     // Remove all Store nodes.
10950     if (StoreNodes[i].MemNode == LatestOp)
10951       continue;
10952     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10953     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10954     deleteAndRecombine(St);
10955   }
10956
10957   return true;
10958 }
10959
10960 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10961   StoreSDNode *ST  = cast<StoreSDNode>(N);
10962   SDValue Chain = ST->getChain();
10963   SDValue Value = ST->getValue();
10964   SDValue Ptr   = ST->getBasePtr();
10965
10966   // If this is a store of a bit convert, store the input value if the
10967   // resultant store does not need a higher alignment than the original.
10968   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10969       ST->isUnindexed()) {
10970     unsigned OrigAlign = ST->getAlignment();
10971     EVT SVT = Value.getOperand(0).getValueType();
10972     unsigned Align = TLI.getDataLayout()->
10973       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10974     if (Align <= OrigAlign &&
10975         ((!LegalOperations && !ST->isVolatile()) ||
10976          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10977       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10978                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10979                           ST->isNonTemporal(), OrigAlign,
10980                           ST->getAAInfo());
10981   }
10982
10983   // Turn 'store undef, Ptr' -> nothing.
10984   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10985     return Chain;
10986
10987   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10988   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10989     // NOTE: If the original store is volatile, this transform must not increase
10990     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10991     // processor operation but an i64 (which is not legal) requires two.  So the
10992     // transform should not be done in this case.
10993     if (Value.getOpcode() != ISD::TargetConstantFP) {
10994       SDValue Tmp;
10995       switch (CFP->getSimpleValueType(0).SimpleTy) {
10996       default: llvm_unreachable("Unknown FP type");
10997       case MVT::f16:    // We don't do this for these yet.
10998       case MVT::f80:
10999       case MVT::f128:
11000       case MVT::ppcf128:
11001         break;
11002       case MVT::f32:
11003         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
11004             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11005           ;
11006           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
11007                               bitcastToAPInt().getZExtValue(), SDLoc(CFP),
11008                               MVT::i32);
11009           return DAG.getStore(Chain, SDLoc(N), Tmp,
11010                               Ptr, ST->getMemOperand());
11011         }
11012         break;
11013       case MVT::f64:
11014         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
11015              !ST->isVolatile()) ||
11016             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
11017           ;
11018           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
11019                                 getZExtValue(), SDLoc(CFP), MVT::i64);
11020           return DAG.getStore(Chain, SDLoc(N), Tmp,
11021                               Ptr, ST->getMemOperand());
11022         }
11023
11024         if (!ST->isVolatile() &&
11025             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
11026           // Many FP stores are not made apparent until after legalize, e.g. for
11027           // argument passing.  Since this is so common, custom legalize the
11028           // 64-bit integer store into two 32-bit stores.
11029           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
11030           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
11031           SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
11032           if (TLI.isBigEndian()) std::swap(Lo, Hi);
11033
11034           unsigned Alignment = ST->getAlignment();
11035           bool isVolatile = ST->isVolatile();
11036           bool isNonTemporal = ST->isNonTemporal();
11037           AAMDNodes AAInfo = ST->getAAInfo();
11038
11039           SDLoc DL(N);
11040
11041           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
11042                                      Ptr, ST->getPointerInfo(),
11043                                      isVolatile, isNonTemporal,
11044                                      ST->getAlignment(), AAInfo);
11045           Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
11046                             DAG.getConstant(4, DL, Ptr.getValueType()));
11047           Alignment = MinAlign(Alignment, 4U);
11048           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
11049                                      Ptr, ST->getPointerInfo().getWithOffset(4),
11050                                      isVolatile, isNonTemporal,
11051                                      Alignment, AAInfo);
11052           return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
11053                              St0, St1);
11054         }
11055
11056         break;
11057       }
11058     }
11059   }
11060
11061   // Try to infer better alignment information than the store already has.
11062   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
11063     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
11064       if (Align > ST->getAlignment()) {
11065         SDValue NewStore =
11066                DAG.getTruncStore(Chain, SDLoc(N), Value,
11067                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
11068                                  ST->isVolatile(), ST->isNonTemporal(), Align,
11069                                  ST->getAAInfo());
11070         if (NewStore.getNode() != N)
11071           return CombineTo(ST, NewStore, true);
11072       }
11073     }
11074   }
11075
11076   // Try transforming a pair floating point load / store ops to integer
11077   // load / store ops.
11078   SDValue NewST = TransformFPLoadStorePair(N);
11079   if (NewST.getNode())
11080     return NewST;
11081
11082   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
11083                                                   : DAG.getSubtarget().useAA();
11084 #ifndef NDEBUG
11085   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11086       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11087     UseAA = false;
11088 #endif
11089   if (UseAA && ST->isUnindexed()) {
11090     // Walk up chain skipping non-aliasing memory nodes.
11091     SDValue BetterChain = FindBetterChain(N, Chain);
11092
11093     // If there is a better chain.
11094     if (Chain != BetterChain) {
11095       SDValue ReplStore;
11096
11097       // Replace the chain to avoid dependency.
11098       if (ST->isTruncatingStore()) {
11099         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
11100                                       ST->getMemoryVT(), ST->getMemOperand());
11101       } else {
11102         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
11103                                  ST->getMemOperand());
11104       }
11105
11106       // Create token to keep both nodes around.
11107       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
11108                                   MVT::Other, Chain, ReplStore);
11109
11110       // Make sure the new and old chains are cleaned up.
11111       AddToWorklist(Token.getNode());
11112
11113       // Don't add users to work list.
11114       return CombineTo(N, Token, false);
11115     }
11116   }
11117
11118   // Try transforming N to an indexed store.
11119   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
11120     return SDValue(N, 0);
11121
11122   // FIXME: is there such a thing as a truncating indexed store?
11123   if (ST->isTruncatingStore() && ST->isUnindexed() &&
11124       Value.getValueType().isInteger()) {
11125     // See if we can simplify the input to this truncstore with knowledge that
11126     // only the low bits are being used.  For example:
11127     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
11128     SDValue Shorter =
11129       GetDemandedBits(Value,
11130                       APInt::getLowBitsSet(
11131                         Value.getValueType().getScalarType().getSizeInBits(),
11132                         ST->getMemoryVT().getScalarType().getSizeInBits()));
11133     AddToWorklist(Value.getNode());
11134     if (Shorter.getNode())
11135       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
11136                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
11137
11138     // Otherwise, see if we can simplify the operation with
11139     // SimplifyDemandedBits, which only works if the value has a single use.
11140     if (SimplifyDemandedBits(Value,
11141                         APInt::getLowBitsSet(
11142                           Value.getValueType().getScalarType().getSizeInBits(),
11143                           ST->getMemoryVT().getScalarType().getSizeInBits())))
11144       return SDValue(N, 0);
11145   }
11146
11147   // If this is a load followed by a store to the same location, then the store
11148   // is dead/noop.
11149   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
11150     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
11151         ST->isUnindexed() && !ST->isVolatile() &&
11152         // There can't be any side effects between the load and store, such as
11153         // a call or store.
11154         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
11155       // The store is dead, remove it.
11156       return Chain;
11157     }
11158   }
11159
11160   // If this is a store followed by a store with the same value to the same
11161   // location, then the store is dead/noop.
11162   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
11163     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
11164         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
11165         ST1->isUnindexed() && !ST1->isVolatile()) {
11166       // The store is dead, remove it.
11167       return Chain;
11168     }
11169   }
11170
11171   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
11172   // truncating store.  We can do this even if this is already a truncstore.
11173   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
11174       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
11175       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
11176                             ST->getMemoryVT())) {
11177     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
11178                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
11179   }
11180
11181   // Only perform this optimization before the types are legal, because we
11182   // don't want to perform this optimization on every DAGCombine invocation.
11183   if (!LegalTypes) {
11184     bool EverChanged = false;
11185
11186     do {
11187       // There can be multiple store sequences on the same chain.
11188       // Keep trying to merge store sequences until we are unable to do so
11189       // or until we merge the last store on the chain.
11190       bool Changed = MergeConsecutiveStores(ST);
11191       EverChanged |= Changed;
11192       if (!Changed) break;
11193     } while (ST->getOpcode() != ISD::DELETED_NODE);
11194
11195     if (EverChanged)
11196       return SDValue(N, 0);
11197   }
11198
11199   return ReduceLoadOpStoreWidth(N);
11200 }
11201
11202 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
11203   SDValue InVec = N->getOperand(0);
11204   SDValue InVal = N->getOperand(1);
11205   SDValue EltNo = N->getOperand(2);
11206   SDLoc dl(N);
11207
11208   // If the inserted element is an UNDEF, just use the input vector.
11209   if (InVal.getOpcode() == ISD::UNDEF)
11210     return InVec;
11211
11212   EVT VT = InVec.getValueType();
11213
11214   // If we can't generate a legal BUILD_VECTOR, exit
11215   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
11216     return SDValue();
11217
11218   // Check that we know which element is being inserted
11219   if (!isa<ConstantSDNode>(EltNo))
11220     return SDValue();
11221   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11222
11223   // Canonicalize insert_vector_elt dag nodes.
11224   // Example:
11225   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
11226   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
11227   //
11228   // Do this only if the child insert_vector node has one use; also
11229   // do this only if indices are both constants and Idx1 < Idx0.
11230   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
11231       && isa<ConstantSDNode>(InVec.getOperand(2))) {
11232     unsigned OtherElt =
11233       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
11234     if (Elt < OtherElt) {
11235       // Swap nodes.
11236       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
11237                                   InVec.getOperand(0), InVal, EltNo);
11238       AddToWorklist(NewOp.getNode());
11239       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
11240                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
11241     }
11242   }
11243
11244   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
11245   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
11246   // vector elements.
11247   SmallVector<SDValue, 8> Ops;
11248   // Do not combine these two vectors if the output vector will not replace
11249   // the input vector.
11250   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
11251     Ops.append(InVec.getNode()->op_begin(),
11252                InVec.getNode()->op_end());
11253   } else if (InVec.getOpcode() == ISD::UNDEF) {
11254     unsigned NElts = VT.getVectorNumElements();
11255     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
11256   } else {
11257     return SDValue();
11258   }
11259
11260   // Insert the element
11261   if (Elt < Ops.size()) {
11262     // All the operands of BUILD_VECTOR must have the same type;
11263     // we enforce that here.
11264     EVT OpVT = Ops[0].getValueType();
11265     if (InVal.getValueType() != OpVT)
11266       InVal = OpVT.bitsGT(InVal.getValueType()) ?
11267                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
11268                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
11269     Ops[Elt] = InVal;
11270   }
11271
11272   // Return the new vector
11273   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
11274 }
11275
11276 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
11277     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
11278   EVT ResultVT = EVE->getValueType(0);
11279   EVT VecEltVT = InVecVT.getVectorElementType();
11280   unsigned Align = OriginalLoad->getAlignment();
11281   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
11282       VecEltVT.getTypeForEVT(*DAG.getContext()));
11283
11284   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
11285     return SDValue();
11286
11287   Align = NewAlign;
11288
11289   SDValue NewPtr = OriginalLoad->getBasePtr();
11290   SDValue Offset;
11291   EVT PtrType = NewPtr.getValueType();
11292   MachinePointerInfo MPI;
11293   SDLoc DL(EVE);
11294   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
11295     int Elt = ConstEltNo->getZExtValue();
11296     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
11297     if (TLI.isBigEndian())
11298       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
11299     Offset = DAG.getConstant(PtrOff, DL, PtrType);
11300     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
11301   } else {
11302     Offset = DAG.getNode(
11303         ISD::MUL, DL, EltNo.getValueType(), EltNo,
11304         DAG.getConstant(VecEltVT.getStoreSize(), DL, EltNo.getValueType()));
11305     if (TLI.isBigEndian())
11306       Offset = DAG.getNode(
11307           ISD::SUB, DL, EltNo.getValueType(),
11308           DAG.getConstant(InVecVT.getStoreSize(), DL, EltNo.getValueType()),
11309           Offset);
11310     MPI = OriginalLoad->getPointerInfo();
11311   }
11312   NewPtr = DAG.getNode(ISD::ADD, DL, PtrType, NewPtr, Offset);
11313
11314   // The replacement we need to do here is a little tricky: we need to
11315   // replace an extractelement of a load with a load.
11316   // Use ReplaceAllUsesOfValuesWith to do the replacement.
11317   // Note that this replacement assumes that the extractvalue is the only
11318   // use of the load; that's okay because we don't want to perform this
11319   // transformation in other cases anyway.
11320   SDValue Load;
11321   SDValue Chain;
11322   if (ResultVT.bitsGT(VecEltVT)) {
11323     // If the result type of vextract is wider than the load, then issue an
11324     // extending load instead.
11325     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
11326                                                   VecEltVT)
11327                                    ? ISD::ZEXTLOAD
11328                                    : ISD::EXTLOAD;
11329     Load = DAG.getExtLoad(
11330         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
11331         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11332         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11333     Chain = Load.getValue(1);
11334   } else {
11335     Load = DAG.getLoad(
11336         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
11337         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
11338         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
11339     Chain = Load.getValue(1);
11340     if (ResultVT.bitsLT(VecEltVT))
11341       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
11342     else
11343       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
11344   }
11345   WorklistRemover DeadNodes(*this);
11346   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
11347   SDValue To[] = { Load, Chain };
11348   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
11349   // Since we're explicitly calling ReplaceAllUses, add the new node to the
11350   // worklist explicitly as well.
11351   AddToWorklist(Load.getNode());
11352   AddUsersToWorklist(Load.getNode()); // Add users too
11353   // Make sure to revisit this node to clean it up; it will usually be dead.
11354   AddToWorklist(EVE);
11355   ++OpsNarrowed;
11356   return SDValue(EVE, 0);
11357 }
11358
11359 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
11360   // (vextract (scalar_to_vector val, 0) -> val
11361   SDValue InVec = N->getOperand(0);
11362   EVT VT = InVec.getValueType();
11363   EVT NVT = N->getValueType(0);
11364
11365   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
11366     // Check if the result type doesn't match the inserted element type. A
11367     // SCALAR_TO_VECTOR may truncate the inserted element and the
11368     // EXTRACT_VECTOR_ELT may widen the extracted vector.
11369     SDValue InOp = InVec.getOperand(0);
11370     if (InOp.getValueType() != NVT) {
11371       assert(InOp.getValueType().isInteger() && NVT.isInteger());
11372       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
11373     }
11374     return InOp;
11375   }
11376
11377   SDValue EltNo = N->getOperand(1);
11378   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
11379
11380   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
11381   // We only perform this optimization before the op legalization phase because
11382   // we may introduce new vector instructions which are not backed by TD
11383   // patterns. For example on AVX, extracting elements from a wide vector
11384   // without using extract_subvector. However, if we can find an underlying
11385   // scalar value, then we can always use that.
11386   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
11387       && ConstEltNo) {
11388     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11389     int NumElem = VT.getVectorNumElements();
11390     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
11391     // Find the new index to extract from.
11392     int OrigElt = SVOp->getMaskElt(Elt);
11393
11394     // Extracting an undef index is undef.
11395     if (OrigElt == -1)
11396       return DAG.getUNDEF(NVT);
11397
11398     // Select the right vector half to extract from.
11399     SDValue SVInVec;
11400     if (OrigElt < NumElem) {
11401       SVInVec = InVec->getOperand(0);
11402     } else {
11403       SVInVec = InVec->getOperand(1);
11404       OrigElt -= NumElem;
11405     }
11406
11407     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
11408       SDValue InOp = SVInVec.getOperand(OrigElt);
11409       if (InOp.getValueType() != NVT) {
11410         assert(InOp.getValueType().isInteger() && NVT.isInteger());
11411         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
11412       }
11413
11414       return InOp;
11415     }
11416
11417     // FIXME: We should handle recursing on other vector shuffles and
11418     // scalar_to_vector here as well.
11419
11420     if (!LegalOperations) {
11421       EVT IndexTy = TLI.getVectorIdxTy();
11422       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT, SVInVec,
11423                          DAG.getConstant(OrigElt, SDLoc(SVOp), IndexTy));
11424     }
11425   }
11426
11427   bool BCNumEltsChanged = false;
11428   EVT ExtVT = VT.getVectorElementType();
11429   EVT LVT = ExtVT;
11430
11431   // If the result of load has to be truncated, then it's not necessarily
11432   // profitable.
11433   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
11434     return SDValue();
11435
11436   if (InVec.getOpcode() == ISD::BITCAST) {
11437     // Don't duplicate a load with other uses.
11438     if (!InVec.hasOneUse())
11439       return SDValue();
11440
11441     EVT BCVT = InVec.getOperand(0).getValueType();
11442     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
11443       return SDValue();
11444     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
11445       BCNumEltsChanged = true;
11446     InVec = InVec.getOperand(0);
11447     ExtVT = BCVT.getVectorElementType();
11448   }
11449
11450   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
11451   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
11452       ISD::isNormalLoad(InVec.getNode()) &&
11453       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
11454     SDValue Index = N->getOperand(1);
11455     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
11456       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
11457                                                            OrigLoad);
11458   }
11459
11460   // Perform only after legalization to ensure build_vector / vector_shuffle
11461   // optimizations have already been done.
11462   if (!LegalOperations) return SDValue();
11463
11464   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
11465   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
11466   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
11467
11468   if (ConstEltNo) {
11469     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
11470
11471     LoadSDNode *LN0 = nullptr;
11472     const ShuffleVectorSDNode *SVN = nullptr;
11473     if (ISD::isNormalLoad(InVec.getNode())) {
11474       LN0 = cast<LoadSDNode>(InVec);
11475     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
11476                InVec.getOperand(0).getValueType() == ExtVT &&
11477                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
11478       // Don't duplicate a load with other uses.
11479       if (!InVec.hasOneUse())
11480         return SDValue();
11481
11482       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
11483     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
11484       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
11485       // =>
11486       // (load $addr+1*size)
11487
11488       // Don't duplicate a load with other uses.
11489       if (!InVec.hasOneUse())
11490         return SDValue();
11491
11492       // If the bit convert changed the number of elements, it is unsafe
11493       // to examine the mask.
11494       if (BCNumEltsChanged)
11495         return SDValue();
11496
11497       // Select the input vector, guarding against out of range extract vector.
11498       unsigned NumElems = VT.getVectorNumElements();
11499       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
11500       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
11501
11502       if (InVec.getOpcode() == ISD::BITCAST) {
11503         // Don't duplicate a load with other uses.
11504         if (!InVec.hasOneUse())
11505           return SDValue();
11506
11507         InVec = InVec.getOperand(0);
11508       }
11509       if (ISD::isNormalLoad(InVec.getNode())) {
11510         LN0 = cast<LoadSDNode>(InVec);
11511         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
11512         EltNo = DAG.getConstant(Elt, SDLoc(EltNo), EltNo.getValueType());
11513       }
11514     }
11515
11516     // Make sure we found a non-volatile load and the extractelement is
11517     // the only use.
11518     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
11519       return SDValue();
11520
11521     // If Idx was -1 above, Elt is going to be -1, so just return undef.
11522     if (Elt == -1)
11523       return DAG.getUNDEF(LVT);
11524
11525     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
11526   }
11527
11528   return SDValue();
11529 }
11530
11531 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
11532 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
11533   // We perform this optimization post type-legalization because
11534   // the type-legalizer often scalarizes integer-promoted vectors.
11535   // Performing this optimization before may create bit-casts which
11536   // will be type-legalized to complex code sequences.
11537   // We perform this optimization only before the operation legalizer because we
11538   // may introduce illegal operations.
11539   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
11540     return SDValue();
11541
11542   unsigned NumInScalars = N->getNumOperands();
11543   SDLoc dl(N);
11544   EVT VT = N->getValueType(0);
11545
11546   // Check to see if this is a BUILD_VECTOR of a bunch of values
11547   // which come from any_extend or zero_extend nodes. If so, we can create
11548   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
11549   // optimizations. We do not handle sign-extend because we can't fill the sign
11550   // using shuffles.
11551   EVT SourceType = MVT::Other;
11552   bool AllAnyExt = true;
11553
11554   for (unsigned i = 0; i != NumInScalars; ++i) {
11555     SDValue In = N->getOperand(i);
11556     // Ignore undef inputs.
11557     if (In.getOpcode() == ISD::UNDEF) continue;
11558
11559     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
11560     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
11561
11562     // Abort if the element is not an extension.
11563     if (!ZeroExt && !AnyExt) {
11564       SourceType = MVT::Other;
11565       break;
11566     }
11567
11568     // The input is a ZeroExt or AnyExt. Check the original type.
11569     EVT InTy = In.getOperand(0).getValueType();
11570
11571     // Check that all of the widened source types are the same.
11572     if (SourceType == MVT::Other)
11573       // First time.
11574       SourceType = InTy;
11575     else if (InTy != SourceType) {
11576       // Multiple income types. Abort.
11577       SourceType = MVT::Other;
11578       break;
11579     }
11580
11581     // Check if all of the extends are ANY_EXTENDs.
11582     AllAnyExt &= AnyExt;
11583   }
11584
11585   // In order to have valid types, all of the inputs must be extended from the
11586   // same source type and all of the inputs must be any or zero extend.
11587   // Scalar sizes must be a power of two.
11588   EVT OutScalarTy = VT.getScalarType();
11589   bool ValidTypes = SourceType != MVT::Other &&
11590                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
11591                  isPowerOf2_32(SourceType.getSizeInBits());
11592
11593   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
11594   // turn into a single shuffle instruction.
11595   if (!ValidTypes)
11596     return SDValue();
11597
11598   bool isLE = TLI.isLittleEndian();
11599   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
11600   assert(ElemRatio > 1 && "Invalid element size ratio");
11601   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
11602                                DAG.getConstant(0, SDLoc(N), SourceType);
11603
11604   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
11605   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
11606
11607   // Populate the new build_vector
11608   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11609     SDValue Cast = N->getOperand(i);
11610     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
11611             Cast.getOpcode() == ISD::ZERO_EXTEND ||
11612             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
11613     SDValue In;
11614     if (Cast.getOpcode() == ISD::UNDEF)
11615       In = DAG.getUNDEF(SourceType);
11616     else
11617       In = Cast->getOperand(0);
11618     unsigned Index = isLE ? (i * ElemRatio) :
11619                             (i * ElemRatio + (ElemRatio - 1));
11620
11621     assert(Index < Ops.size() && "Invalid index");
11622     Ops[Index] = In;
11623   }
11624
11625   // The type of the new BUILD_VECTOR node.
11626   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
11627   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
11628          "Invalid vector size");
11629   // Check if the new vector type is legal.
11630   if (!isTypeLegal(VecVT)) return SDValue();
11631
11632   // Make the new BUILD_VECTOR.
11633   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
11634
11635   // The new BUILD_VECTOR node has the potential to be further optimized.
11636   AddToWorklist(BV.getNode());
11637   // Bitcast to the desired type.
11638   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
11639 }
11640
11641 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
11642   EVT VT = N->getValueType(0);
11643
11644   unsigned NumInScalars = N->getNumOperands();
11645   SDLoc dl(N);
11646
11647   EVT SrcVT = MVT::Other;
11648   unsigned Opcode = ISD::DELETED_NODE;
11649   unsigned NumDefs = 0;
11650
11651   for (unsigned i = 0; i != NumInScalars; ++i) {
11652     SDValue In = N->getOperand(i);
11653     unsigned Opc = In.getOpcode();
11654
11655     if (Opc == ISD::UNDEF)
11656       continue;
11657
11658     // If all scalar values are floats and converted from integers.
11659     if (Opcode == ISD::DELETED_NODE &&
11660         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
11661       Opcode = Opc;
11662     }
11663
11664     if (Opc != Opcode)
11665       return SDValue();
11666
11667     EVT InVT = In.getOperand(0).getValueType();
11668
11669     // If all scalar values are typed differently, bail out. It's chosen to
11670     // simplify BUILD_VECTOR of integer types.
11671     if (SrcVT == MVT::Other)
11672       SrcVT = InVT;
11673     if (SrcVT != InVT)
11674       return SDValue();
11675     NumDefs++;
11676   }
11677
11678   // If the vector has just one element defined, it's not worth to fold it into
11679   // a vectorized one.
11680   if (NumDefs < 2)
11681     return SDValue();
11682
11683   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
11684          && "Should only handle conversion from integer to float.");
11685   assert(SrcVT != MVT::Other && "Cannot determine source type!");
11686
11687   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
11688
11689   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
11690     return SDValue();
11691
11692   // Just because the floating-point vector type is legal does not necessarily
11693   // mean that the corresponding integer vector type is.
11694   if (!isTypeLegal(NVT))
11695     return SDValue();
11696
11697   SmallVector<SDValue, 8> Opnds;
11698   for (unsigned i = 0; i != NumInScalars; ++i) {
11699     SDValue In = N->getOperand(i);
11700
11701     if (In.getOpcode() == ISD::UNDEF)
11702       Opnds.push_back(DAG.getUNDEF(SrcVT));
11703     else
11704       Opnds.push_back(In.getOperand(0));
11705   }
11706   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
11707   AddToWorklist(BV.getNode());
11708
11709   return DAG.getNode(Opcode, dl, VT, BV);
11710 }
11711
11712 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
11713   unsigned NumInScalars = N->getNumOperands();
11714   SDLoc dl(N);
11715   EVT VT = N->getValueType(0);
11716
11717   // A vector built entirely of undefs is undef.
11718   if (ISD::allOperandsUndef(N))
11719     return DAG.getUNDEF(VT);
11720
11721   if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
11722     return V;
11723
11724   if (SDValue V = reduceBuildVecConvertToConvertBuildVec(N))
11725     return V;
11726
11727   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
11728   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
11729   // at most two distinct vectors, turn this into a shuffle node.
11730
11731   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
11732   if (!isTypeLegal(VT))
11733     return SDValue();
11734
11735   // May only combine to shuffle after legalize if shuffle is legal.
11736   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
11737     return SDValue();
11738
11739   SDValue VecIn1, VecIn2;
11740   bool UsesZeroVector = false;
11741   for (unsigned i = 0; i != NumInScalars; ++i) {
11742     SDValue Op = N->getOperand(i);
11743     // Ignore undef inputs.
11744     if (Op.getOpcode() == ISD::UNDEF) continue;
11745
11746     // See if we can combine this build_vector into a blend with a zero vector.
11747     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
11748         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
11749         (Op.getOpcode() == ISD::ConstantFP &&
11750         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
11751       UsesZeroVector = true;
11752       continue;
11753     }
11754
11755     // If this input is something other than a EXTRACT_VECTOR_ELT with a
11756     // constant index, bail out.
11757     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
11758         !isa<ConstantSDNode>(Op.getOperand(1))) {
11759       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11760       break;
11761     }
11762
11763     // We allow up to two distinct input vectors.
11764     SDValue ExtractedFromVec = Op.getOperand(0);
11765     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
11766       continue;
11767
11768     if (!VecIn1.getNode()) {
11769       VecIn1 = ExtractedFromVec;
11770     } else if (!VecIn2.getNode() && !UsesZeroVector) {
11771       VecIn2 = ExtractedFromVec;
11772     } else {
11773       // Too many inputs.
11774       VecIn1 = VecIn2 = SDValue(nullptr, 0);
11775       break;
11776     }
11777   }
11778
11779   // If everything is good, we can make a shuffle operation.
11780   if (VecIn1.getNode()) {
11781     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
11782     SmallVector<int, 8> Mask;
11783     for (unsigned i = 0; i != NumInScalars; ++i) {
11784       unsigned Opcode = N->getOperand(i).getOpcode();
11785       if (Opcode == ISD::UNDEF) {
11786         Mask.push_back(-1);
11787         continue;
11788       }
11789
11790       // Operands can also be zero.
11791       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
11792         assert(UsesZeroVector &&
11793                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
11794                "Unexpected node found!");
11795         Mask.push_back(NumInScalars+i);
11796         continue;
11797       }
11798
11799       // If extracting from the first vector, just use the index directly.
11800       SDValue Extract = N->getOperand(i);
11801       SDValue ExtVal = Extract.getOperand(1);
11802       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
11803       if (Extract.getOperand(0) == VecIn1) {
11804         Mask.push_back(ExtIndex);
11805         continue;
11806       }
11807
11808       // Otherwise, use InIdx + InputVecSize
11809       Mask.push_back(InNumElements + ExtIndex);
11810     }
11811
11812     // Avoid introducing illegal shuffles with zero.
11813     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11814       return SDValue();
11815
11816     // We can't generate a shuffle node with mismatched input and output types.
11817     // Attempt to transform a single input vector to the correct type.
11818     if ((VT != VecIn1.getValueType())) {
11819       // If the input vector type has a different base type to the output
11820       // vector type, bail out.
11821       EVT VTElemType = VT.getVectorElementType();
11822       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11823           (VecIn2.getNode() &&
11824            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11825         return SDValue();
11826
11827       // If the input vector is too small, widen it.
11828       // We only support widening of vectors which are half the size of the
11829       // output registers. For example XMM->YMM widening on X86 with AVX.
11830       EVT VecInT = VecIn1.getValueType();
11831       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11832         // If we only have one small input, widen it by adding undef values.
11833         if (!VecIn2.getNode())
11834           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11835                                DAG.getUNDEF(VecIn1.getValueType()));
11836         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11837           // If we have two small inputs of the same type, try to concat them.
11838           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11839           VecIn2 = SDValue(nullptr, 0);
11840         } else
11841           return SDValue();
11842       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11843         // If the input vector is too large, try to split it.
11844         // We don't support having two input vectors that are too large.
11845         // If the zero vector was used, we can not split the vector,
11846         // since we'd need 3 inputs.
11847         if (UsesZeroVector || VecIn2.getNode())
11848           return SDValue();
11849
11850         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11851           return SDValue();
11852
11853         // Try to replace VecIn1 with two extract_subvectors
11854         // No need to update the masks, they should still be correct.
11855         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11856           DAG.getConstant(VT.getVectorNumElements(), dl, TLI.getVectorIdxTy()));
11857         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11858           DAG.getConstant(0, dl, TLI.getVectorIdxTy()));
11859       } else
11860         return SDValue();
11861     }
11862
11863     if (UsesZeroVector)
11864       VecIn2 = VT.isInteger() ? DAG.getConstant(0, dl, VT) :
11865                                 DAG.getConstantFP(0.0, dl, VT);
11866     else
11867       // If VecIn2 is unused then change it to undef.
11868       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11869
11870     // Check that we were able to transform all incoming values to the same
11871     // type.
11872     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11873         VecIn1.getValueType() != VT)
11874           return SDValue();
11875
11876     // Return the new VECTOR_SHUFFLE node.
11877     SDValue Ops[2];
11878     Ops[0] = VecIn1;
11879     Ops[1] = VecIn2;
11880     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11881   }
11882
11883   return SDValue();
11884 }
11885
11886 static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
11887   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
11888   EVT OpVT = N->getOperand(0).getValueType();
11889
11890   // If the operands are legal vectors, leave them alone.
11891   if (TLI.isTypeLegal(OpVT))
11892     return SDValue();
11893
11894   SDLoc DL(N);
11895   EVT VT = N->getValueType(0);
11896   SmallVector<SDValue, 8> Ops;
11897
11898   EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
11899   SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11900
11901   // Keep track of what we encounter.
11902   bool AnyInteger = false;
11903   bool AnyFP = false;
11904   for (const SDValue &Op : N->ops()) {
11905     if (ISD::BITCAST == Op.getOpcode() &&
11906         !Op.getOperand(0).getValueType().isVector())
11907       Ops.push_back(Op.getOperand(0));
11908     else if (ISD::UNDEF == Op.getOpcode())
11909       Ops.push_back(ScalarUndef);
11910     else
11911       return SDValue();
11912
11913     // Note whether we encounter an integer or floating point scalar.
11914     // If it's neither, bail out, it could be something weird like x86mmx.
11915     EVT LastOpVT = Ops.back().getValueType();
11916     if (LastOpVT.isFloatingPoint())
11917       AnyFP = true;
11918     else if (LastOpVT.isInteger())
11919       AnyInteger = true;
11920     else
11921       return SDValue();
11922   }
11923
11924   // If any of the operands is a floating point scalar bitcast to a vector,
11925   // use floating point types throughout, and bitcast everything.  
11926   // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
11927   if (AnyFP) {
11928     SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
11929     ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
11930     if (AnyInteger) {
11931       for (SDValue &Op : Ops) {
11932         if (Op.getValueType() == SVT)
11933           continue;
11934         if (Op.getOpcode() == ISD::UNDEF)
11935           Op = ScalarUndef;
11936         else
11937           Op = DAG.getNode(ISD::BITCAST, DL, SVT, Op);
11938       }
11939     }
11940   }
11941
11942   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
11943                                VT.getSizeInBits() / SVT.getSizeInBits());
11944   return DAG.getNode(ISD::BITCAST, DL, VT,
11945                      DAG.getNode(ISD::BUILD_VECTOR, DL, VecVT, Ops));
11946 }
11947
11948 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11949   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11950   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11951   // inputs come from at most two distinct vectors, turn this into a shuffle
11952   // node.
11953
11954   // If we only have one input vector, we don't need to do any concatenation.
11955   if (N->getNumOperands() == 1)
11956     return N->getOperand(0);
11957
11958   // Check if all of the operands are undefs.
11959   EVT VT = N->getValueType(0);
11960   if (ISD::allOperandsUndef(N))
11961     return DAG.getUNDEF(VT);
11962
11963   // Optimize concat_vectors where all but the first of the vectors are undef.
11964   if (std::all_of(std::next(N->op_begin()), N->op_end(), [](const SDValue &Op) {
11965         return Op.getOpcode() == ISD::UNDEF;
11966       })) {
11967     SDValue In = N->getOperand(0);
11968     assert(In.getValueType().isVector() && "Must concat vectors");
11969
11970     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11971     if (In->getOpcode() == ISD::BITCAST &&
11972         !In->getOperand(0)->getValueType(0).isVector()) {
11973       SDValue Scalar = In->getOperand(0);
11974
11975       // If the bitcast type isn't legal, it might be a trunc of a legal type;
11976       // look through the trunc so we can still do the transform:
11977       //   concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
11978       if (Scalar->getOpcode() == ISD::TRUNCATE &&
11979           !TLI.isTypeLegal(Scalar.getValueType()) &&
11980           TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
11981         Scalar = Scalar->getOperand(0);
11982
11983       EVT SclTy = Scalar->getValueType(0);
11984
11985       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11986         return SDValue();
11987
11988       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11989                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11990       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11991         return SDValue();
11992
11993       SDLoc dl = SDLoc(N);
11994       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11995       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11996     }
11997   }
11998
11999   // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
12000   // We have already tested above for an UNDEF only concatenation.
12001   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
12002   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
12003   auto IsBuildVectorOrUndef = [](const SDValue &Op) {
12004     return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
12005   };
12006   bool AllBuildVectorsOrUndefs =
12007       std::all_of(N->op_begin(), N->op_end(), IsBuildVectorOrUndef);
12008   if (AllBuildVectorsOrUndefs) {
12009     SmallVector<SDValue, 8> Opnds;
12010     EVT SVT = VT.getScalarType();
12011
12012     EVT MinVT = SVT;
12013     if (!SVT.isFloatingPoint()) {
12014       // If BUILD_VECTOR are from built from integer, they may have different
12015       // operand types. Get the smallest type and truncate all operands to it.
12016       bool FoundMinVT = false;
12017       for (const SDValue &Op : N->ops())
12018         if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12019           EVT OpSVT = Op.getOperand(0)->getValueType(0);
12020           MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
12021           FoundMinVT = true;
12022         }
12023       assert(FoundMinVT && "Concat vector type mismatch");
12024     }
12025
12026     for (const SDValue &Op : N->ops()) {
12027       EVT OpVT = Op.getValueType();
12028       unsigned NumElts = OpVT.getVectorNumElements();
12029
12030       if (ISD::UNDEF == Op.getOpcode())
12031         Opnds.append(NumElts, DAG.getUNDEF(MinVT));
12032
12033       if (ISD::BUILD_VECTOR == Op.getOpcode()) {
12034         if (SVT.isFloatingPoint()) {
12035           assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
12036           Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
12037         } else {
12038           for (unsigned i = 0; i != NumElts; ++i)
12039             Opnds.push_back(
12040                 DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
12041         }
12042       }
12043     }
12044
12045     assert(VT.getVectorNumElements() == Opnds.size() &&
12046            "Concat vector type mismatch");
12047     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
12048   }
12049
12050   // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
12051   if (SDValue V = combineConcatVectorOfScalars(N, DAG))
12052     return V;
12053
12054   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
12055   // nodes often generate nop CONCAT_VECTOR nodes.
12056   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
12057   // place the incoming vectors at the exact same location.
12058   SDValue SingleSource = SDValue();
12059   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
12060
12061   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
12062     SDValue Op = N->getOperand(i);
12063
12064     if (Op.getOpcode() == ISD::UNDEF)
12065       continue;
12066
12067     // Check if this is the identity extract:
12068     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
12069       return SDValue();
12070
12071     // Find the single incoming vector for the extract_subvector.
12072     if (SingleSource.getNode()) {
12073       if (Op.getOperand(0) != SingleSource)
12074         return SDValue();
12075     } else {
12076       SingleSource = Op.getOperand(0);
12077
12078       // Check the source type is the same as the type of the result.
12079       // If not, this concat may extend the vector, so we can not
12080       // optimize it away.
12081       if (SingleSource.getValueType() != N->getValueType(0))
12082         return SDValue();
12083     }
12084
12085     unsigned IdentityIndex = i * PartNumElem;
12086     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
12087     // The extract index must be constant.
12088     if (!CS)
12089       return SDValue();
12090
12091     // Check that we are reading from the identity index.
12092     if (CS->getZExtValue() != IdentityIndex)
12093       return SDValue();
12094   }
12095
12096   if (SingleSource.getNode())
12097     return SingleSource;
12098
12099   return SDValue();
12100 }
12101
12102 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
12103   EVT NVT = N->getValueType(0);
12104   SDValue V = N->getOperand(0);
12105
12106   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
12107     // Combine:
12108     //    (extract_subvec (concat V1, V2, ...), i)
12109     // Into:
12110     //    Vi if possible
12111     // Only operand 0 is checked as 'concat' assumes all inputs of the same
12112     // type.
12113     if (V->getOperand(0).getValueType() != NVT)
12114       return SDValue();
12115     unsigned Idx = N->getConstantOperandVal(1);
12116     unsigned NumElems = NVT.getVectorNumElements();
12117     assert((Idx % NumElems) == 0 &&
12118            "IDX in concat is not a multiple of the result vector length.");
12119     return V->getOperand(Idx / NumElems);
12120   }
12121
12122   // Skip bitcasting
12123   if (V->getOpcode() == ISD::BITCAST)
12124     V = V.getOperand(0);
12125
12126   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
12127     SDLoc dl(N);
12128     // Handle only simple case where vector being inserted and vector
12129     // being extracted are of same type, and are half size of larger vectors.
12130     EVT BigVT = V->getOperand(0).getValueType();
12131     EVT SmallVT = V->getOperand(1).getValueType();
12132     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
12133       return SDValue();
12134
12135     // Only handle cases where both indexes are constants with the same type.
12136     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
12137     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
12138
12139     if (InsIdx && ExtIdx &&
12140         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
12141         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
12142       // Combine:
12143       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
12144       // Into:
12145       //    indices are equal or bit offsets are equal => V1
12146       //    otherwise => (extract_subvec V1, ExtIdx)
12147       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
12148           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
12149         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
12150       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
12151                          DAG.getNode(ISD::BITCAST, dl,
12152                                      N->getOperand(0).getValueType(),
12153                                      V->getOperand(0)), N->getOperand(1));
12154     }
12155   }
12156
12157   return SDValue();
12158 }
12159
12160 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
12161                                                  SDValue V, SelectionDAG &DAG) {
12162   SDLoc DL(V);
12163   EVT VT = V.getValueType();
12164
12165   switch (V.getOpcode()) {
12166   default:
12167     return V;
12168
12169   case ISD::CONCAT_VECTORS: {
12170     EVT OpVT = V->getOperand(0).getValueType();
12171     int OpSize = OpVT.getVectorNumElements();
12172     SmallBitVector OpUsedElements(OpSize, false);
12173     bool FoundSimplification = false;
12174     SmallVector<SDValue, 4> NewOps;
12175     NewOps.reserve(V->getNumOperands());
12176     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
12177       SDValue Op = V->getOperand(i);
12178       bool OpUsed = false;
12179       for (int j = 0; j < OpSize; ++j)
12180         if (UsedElements[i * OpSize + j]) {
12181           OpUsedElements[j] = true;
12182           OpUsed = true;
12183         }
12184       NewOps.push_back(
12185           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
12186                  : DAG.getUNDEF(OpVT));
12187       FoundSimplification |= Op == NewOps.back();
12188       OpUsedElements.reset();
12189     }
12190     if (FoundSimplification)
12191       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
12192     return V;
12193   }
12194
12195   case ISD::INSERT_SUBVECTOR: {
12196     SDValue BaseV = V->getOperand(0);
12197     SDValue SubV = V->getOperand(1);
12198     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
12199     if (!IdxN)
12200       return V;
12201
12202     int SubSize = SubV.getValueType().getVectorNumElements();
12203     int Idx = IdxN->getZExtValue();
12204     bool SubVectorUsed = false;
12205     SmallBitVector SubUsedElements(SubSize, false);
12206     for (int i = 0; i < SubSize; ++i)
12207       if (UsedElements[i + Idx]) {
12208         SubVectorUsed = true;
12209         SubUsedElements[i] = true;
12210         UsedElements[i + Idx] = false;
12211       }
12212
12213     // Now recurse on both the base and sub vectors.
12214     SDValue SimplifiedSubV =
12215         SubVectorUsed
12216             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
12217             : DAG.getUNDEF(SubV.getValueType());
12218     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
12219     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
12220       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
12221                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
12222     return V;
12223   }
12224   }
12225 }
12226
12227 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
12228                                        SDValue N1, SelectionDAG &DAG) {
12229   EVT VT = SVN->getValueType(0);
12230   int NumElts = VT.getVectorNumElements();
12231   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
12232   for (int M : SVN->getMask())
12233     if (M >= 0 && M < NumElts)
12234       N0UsedElements[M] = true;
12235     else if (M >= NumElts)
12236       N1UsedElements[M - NumElts] = true;
12237
12238   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
12239   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
12240   if (S0 == N0 && S1 == N1)
12241     return SDValue();
12242
12243   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
12244 }
12245
12246 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
12247 // or turn a shuffle of a single concat into simpler shuffle then concat.
12248 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
12249   EVT VT = N->getValueType(0);
12250   unsigned NumElts = VT.getVectorNumElements();
12251
12252   SDValue N0 = N->getOperand(0);
12253   SDValue N1 = N->getOperand(1);
12254   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12255
12256   SmallVector<SDValue, 4> Ops;
12257   EVT ConcatVT = N0.getOperand(0).getValueType();
12258   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
12259   unsigned NumConcats = NumElts / NumElemsPerConcat;
12260
12261   // Special case: shuffle(concat(A,B)) can be more efficiently represented
12262   // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
12263   // half vector elements.
12264   if (NumElemsPerConcat * 2 == NumElts && N1.getOpcode() == ISD::UNDEF &&
12265       std::all_of(SVN->getMask().begin() + NumElemsPerConcat,
12266                   SVN->getMask().end(), [](int i) { return i == -1; })) {
12267     N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0), N0.getOperand(1),
12268                               ArrayRef<int>(SVN->getMask().begin(), NumElemsPerConcat));
12269     N1 = DAG.getUNDEF(ConcatVT);
12270     return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
12271   }
12272
12273   // Look at every vector that's inserted. We're looking for exact
12274   // subvector-sized copies from a concatenated vector
12275   for (unsigned I = 0; I != NumConcats; ++I) {
12276     // Make sure we're dealing with a copy.
12277     unsigned Begin = I * NumElemsPerConcat;
12278     bool AllUndef = true, NoUndef = true;
12279     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
12280       if (SVN->getMaskElt(J) >= 0)
12281         AllUndef = false;
12282       else
12283         NoUndef = false;
12284     }
12285
12286     if (NoUndef) {
12287       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
12288         return SDValue();
12289
12290       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
12291         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
12292           return SDValue();
12293
12294       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
12295       if (FirstElt < N0.getNumOperands())
12296         Ops.push_back(N0.getOperand(FirstElt));
12297       else
12298         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
12299
12300     } else if (AllUndef) {
12301       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
12302     } else { // Mixed with general masks and undefs, can't do optimization.
12303       return SDValue();
12304     }
12305   }
12306
12307   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
12308 }
12309
12310 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
12311   EVT VT = N->getValueType(0);
12312   unsigned NumElts = VT.getVectorNumElements();
12313
12314   SDValue N0 = N->getOperand(0);
12315   SDValue N1 = N->getOperand(1);
12316
12317   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
12318
12319   // Canonicalize shuffle undef, undef -> undef
12320   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
12321     return DAG.getUNDEF(VT);
12322
12323   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
12324
12325   // Canonicalize shuffle v, v -> v, undef
12326   if (N0 == N1) {
12327     SmallVector<int, 8> NewMask;
12328     for (unsigned i = 0; i != NumElts; ++i) {
12329       int Idx = SVN->getMaskElt(i);
12330       if (Idx >= (int)NumElts) Idx -= NumElts;
12331       NewMask.push_back(Idx);
12332     }
12333     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
12334                                 &NewMask[0]);
12335   }
12336
12337   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
12338   if (N0.getOpcode() == ISD::UNDEF) {
12339     SmallVector<int, 8> NewMask;
12340     for (unsigned i = 0; i != NumElts; ++i) {
12341       int Idx = SVN->getMaskElt(i);
12342       if (Idx >= 0) {
12343         if (Idx >= (int)NumElts)
12344           Idx -= NumElts;
12345         else
12346           Idx = -1; // remove reference to lhs
12347       }
12348       NewMask.push_back(Idx);
12349     }
12350     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
12351                                 &NewMask[0]);
12352   }
12353
12354   // Remove references to rhs if it is undef
12355   if (N1.getOpcode() == ISD::UNDEF) {
12356     bool Changed = false;
12357     SmallVector<int, 8> NewMask;
12358     for (unsigned i = 0; i != NumElts; ++i) {
12359       int Idx = SVN->getMaskElt(i);
12360       if (Idx >= (int)NumElts) {
12361         Idx = -1;
12362         Changed = true;
12363       }
12364       NewMask.push_back(Idx);
12365     }
12366     if (Changed)
12367       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
12368   }
12369
12370   // If it is a splat, check if the argument vector is another splat or a
12371   // build_vector.
12372   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
12373     SDNode *V = N0.getNode();
12374
12375     // If this is a bit convert that changes the element type of the vector but
12376     // not the number of vector elements, look through it.  Be careful not to
12377     // look though conversions that change things like v4f32 to v2f64.
12378     if (V->getOpcode() == ISD::BITCAST) {
12379       SDValue ConvInput = V->getOperand(0);
12380       if (ConvInput.getValueType().isVector() &&
12381           ConvInput.getValueType().getVectorNumElements() == NumElts)
12382         V = ConvInput.getNode();
12383     }
12384
12385     if (V->getOpcode() == ISD::BUILD_VECTOR) {
12386       assert(V->getNumOperands() == NumElts &&
12387              "BUILD_VECTOR has wrong number of operands");
12388       SDValue Base;
12389       bool AllSame = true;
12390       for (unsigned i = 0; i != NumElts; ++i) {
12391         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
12392           Base = V->getOperand(i);
12393           break;
12394         }
12395       }
12396       // Splat of <u, u, u, u>, return <u, u, u, u>
12397       if (!Base.getNode())
12398         return N0;
12399       for (unsigned i = 0; i != NumElts; ++i) {
12400         if (V->getOperand(i) != Base) {
12401           AllSame = false;
12402           break;
12403         }
12404       }
12405       // Splat of <x, x, x, x>, return <x, x, x, x>
12406       if (AllSame)
12407         return N0;
12408
12409       // Canonicalize any other splat as a build_vector.
12410       const SDValue &Splatted = V->getOperand(SVN->getSplatIndex());
12411       SmallVector<SDValue, 8> Ops(NumElts, Splatted);
12412       SDValue NewBV = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
12413                                   V->getValueType(0), Ops);
12414
12415       // We may have jumped through bitcasts, so the type of the
12416       // BUILD_VECTOR may not match the type of the shuffle.
12417       if (V->getValueType(0) != VT)
12418         NewBV = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, NewBV);
12419       return NewBV;
12420     }
12421   }
12422
12423   // There are various patterns used to build up a vector from smaller vectors,
12424   // subvectors, or elements. Scan chains of these and replace unused insertions
12425   // or components with undef.
12426   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
12427     return S;
12428
12429   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12430       Level < AfterLegalizeVectorOps &&
12431       (N1.getOpcode() == ISD::UNDEF ||
12432       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
12433        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
12434     SDValue V = partitionShuffleOfConcats(N, DAG);
12435
12436     if (V.getNode())
12437       return V;
12438   }
12439
12440   // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
12441   // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
12442   if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
12443     SmallVector<SDValue, 8> Ops;
12444     for (int M : SVN->getMask()) {
12445       SDValue Op = DAG.getUNDEF(VT.getScalarType());
12446       if (M >= 0) {
12447         int Idx = M % NumElts;
12448         SDValue &S = (M < (int)NumElts ? N0 : N1);
12449         if (S.getOpcode() == ISD::BUILD_VECTOR && S.hasOneUse()) {
12450           Op = S.getOperand(Idx);
12451         } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR && S.hasOneUse()) {
12452           if (Idx == 0)
12453             Op = S.getOperand(0);
12454         } else {
12455           // Operand can't be combined - bail out.
12456           break;
12457         }
12458       }
12459       Ops.push_back(Op);
12460     }
12461     if (Ops.size() == VT.getVectorNumElements()) {
12462       // BUILD_VECTOR requires all inputs to be of the same type, find the
12463       // maximum type and extend them all.
12464       EVT SVT = VT.getScalarType();
12465       if (SVT.isInteger())
12466         for (SDValue &Op : Ops)
12467           SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
12468       if (SVT != VT.getScalarType())
12469         for (SDValue &Op : Ops)
12470           Op = TLI.isZExtFree(Op.getValueType(), SVT)
12471                    ? DAG.getZExtOrTrunc(Op, SDLoc(N), SVT)
12472                    : DAG.getSExtOrTrunc(Op, SDLoc(N), SVT);
12473       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Ops);
12474     }
12475   }
12476
12477   // If this shuffle only has a single input that is a bitcasted shuffle,
12478   // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
12479   // back to their original types.
12480   if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
12481       N1.getOpcode() == ISD::UNDEF && Level < AfterLegalizeVectorOps &&
12482       TLI.isTypeLegal(VT)) {
12483
12484     // Peek through the bitcast only if there is one user.
12485     SDValue BC0 = N0;
12486     while (BC0.getOpcode() == ISD::BITCAST) {
12487       if (!BC0.hasOneUse())
12488         break;
12489       BC0 = BC0.getOperand(0);
12490     }
12491
12492     auto ScaleShuffleMask = [](ArrayRef<int> Mask, int Scale) {
12493       if (Scale == 1)
12494         return SmallVector<int, 8>(Mask.begin(), Mask.end());
12495
12496       SmallVector<int, 8> NewMask;
12497       for (int M : Mask)
12498         for (int s = 0; s != Scale; ++s)
12499           NewMask.push_back(M < 0 ? -1 : Scale * M + s);
12500       return NewMask;
12501     };
12502
12503     if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
12504       EVT SVT = VT.getScalarType();
12505       EVT InnerVT = BC0->getValueType(0);
12506       EVT InnerSVT = InnerVT.getScalarType();
12507
12508       // Determine which shuffle works with the smaller scalar type.
12509       EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
12510       EVT ScaleSVT = ScaleVT.getScalarType();
12511
12512       if (TLI.isTypeLegal(ScaleVT) &&
12513           0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
12514           0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
12515
12516         int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12517         int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
12518
12519         // Scale the shuffle masks to the smaller scalar type.
12520         ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
12521         SmallVector<int, 8> InnerMask =
12522             ScaleShuffleMask(InnerSVN->getMask(), InnerScale);
12523         SmallVector<int, 8> OuterMask =
12524             ScaleShuffleMask(SVN->getMask(), OuterScale);
12525
12526         // Merge the shuffle masks.
12527         SmallVector<int, 8> NewMask;
12528         for (int M : OuterMask)
12529           NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
12530
12531         // Test for shuffle mask legality over both commutations.
12532         SDValue SV0 = BC0->getOperand(0);
12533         SDValue SV1 = BC0->getOperand(1);
12534         bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12535         if (!LegalMask) {
12536           std::swap(SV0, SV1);
12537           ShuffleVectorSDNode::commuteMask(NewMask);
12538           LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
12539         }
12540
12541         if (LegalMask) {
12542           SV0 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV0);
12543           SV1 = DAG.getNode(ISD::BITCAST, SDLoc(N), ScaleVT, SV1);
12544           return DAG.getNode(
12545               ISD::BITCAST, SDLoc(N), VT,
12546               DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
12547         }
12548       }
12549     }
12550   }
12551
12552   // Canonicalize shuffles according to rules:
12553   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
12554   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
12555   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
12556   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
12557       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
12558       TLI.isTypeLegal(VT)) {
12559     // The incoming shuffle must be of the same type as the result of the
12560     // current shuffle.
12561     assert(N1->getOperand(0).getValueType() == VT &&
12562            "Shuffle types don't match");
12563
12564     SDValue SV0 = N1->getOperand(0);
12565     SDValue SV1 = N1->getOperand(1);
12566     bool HasSameOp0 = N0 == SV0;
12567     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
12568     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
12569       // Commute the operands of this shuffle so that next rule
12570       // will trigger.
12571       return DAG.getCommutedVectorShuffle(*SVN);
12572   }
12573
12574   // Try to fold according to rules:
12575   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12576   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12577   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12578   // Don't try to fold shuffles with illegal type.
12579   // Only fold if this shuffle is the only user of the other shuffle.
12580   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && N->isOnlyUserOf(N0.getNode()) &&
12581       Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
12582     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
12583
12584     // The incoming shuffle must be of the same type as the result of the
12585     // current shuffle.
12586     assert(OtherSV->getOperand(0).getValueType() == VT &&
12587            "Shuffle types don't match");
12588
12589     SDValue SV0, SV1;
12590     SmallVector<int, 4> Mask;
12591     // Compute the combined shuffle mask for a shuffle with SV0 as the first
12592     // operand, and SV1 as the second operand.
12593     for (unsigned i = 0; i != NumElts; ++i) {
12594       int Idx = SVN->getMaskElt(i);
12595       if (Idx < 0) {
12596         // Propagate Undef.
12597         Mask.push_back(Idx);
12598         continue;
12599       }
12600
12601       SDValue CurrentVec;
12602       if (Idx < (int)NumElts) {
12603         // This shuffle index refers to the inner shuffle N0. Lookup the inner
12604         // shuffle mask to identify which vector is actually referenced.
12605         Idx = OtherSV->getMaskElt(Idx);
12606         if (Idx < 0) {
12607           // Propagate Undef.
12608           Mask.push_back(Idx);
12609           continue;
12610         }
12611
12612         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
12613                                            : OtherSV->getOperand(1);
12614       } else {
12615         // This shuffle index references an element within N1.
12616         CurrentVec = N1;
12617       }
12618
12619       // Simple case where 'CurrentVec' is UNDEF.
12620       if (CurrentVec.getOpcode() == ISD::UNDEF) {
12621         Mask.push_back(-1);
12622         continue;
12623       }
12624
12625       // Canonicalize the shuffle index. We don't know yet if CurrentVec
12626       // will be the first or second operand of the combined shuffle.
12627       Idx = Idx % NumElts;
12628       if (!SV0.getNode() || SV0 == CurrentVec) {
12629         // Ok. CurrentVec is the left hand side.
12630         // Update the mask accordingly.
12631         SV0 = CurrentVec;
12632         Mask.push_back(Idx);
12633         continue;
12634       }
12635
12636       // Bail out if we cannot convert the shuffle pair into a single shuffle.
12637       if (SV1.getNode() && SV1 != CurrentVec)
12638         return SDValue();
12639
12640       // Ok. CurrentVec is the right hand side.
12641       // Update the mask accordingly.
12642       SV1 = CurrentVec;
12643       Mask.push_back(Idx + NumElts);
12644     }
12645
12646     // Check if all indices in Mask are Undef. In case, propagate Undef.
12647     bool isUndefMask = true;
12648     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
12649       isUndefMask &= Mask[i] < 0;
12650
12651     if (isUndefMask)
12652       return DAG.getUNDEF(VT);
12653
12654     if (!SV0.getNode())
12655       SV0 = DAG.getUNDEF(VT);
12656     if (!SV1.getNode())
12657       SV1 = DAG.getUNDEF(VT);
12658
12659     // Avoid introducing shuffles with illegal mask.
12660     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
12661       ShuffleVectorSDNode::commuteMask(Mask);
12662
12663       if (!TLI.isShuffleMaskLegal(Mask, VT))
12664         return SDValue();
12665
12666       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
12667       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
12668       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
12669       std::swap(SV0, SV1);
12670     }
12671
12672     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
12673     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
12674     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
12675     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
12676   }
12677
12678   return SDValue();
12679 }
12680
12681 SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
12682   SDValue InVal = N->getOperand(0);
12683   EVT VT = N->getValueType(0);
12684
12685   // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
12686   // with a VECTOR_SHUFFLE.
12687   if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
12688     SDValue InVec = InVal->getOperand(0);
12689     SDValue EltNo = InVal->getOperand(1);
12690
12691     // FIXME: We could support implicit truncation if the shuffle can be
12692     // scaled to a smaller vector scalar type.
12693     ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo);
12694     if (C0 && VT == InVec.getValueType() &&
12695         VT.getScalarType() == InVal.getValueType()) {
12696       SmallVector<int, 8> NewMask(VT.getVectorNumElements(), -1);
12697       int Elt = C0->getZExtValue();
12698       NewMask[0] = Elt;
12699
12700       if (TLI.isShuffleMaskLegal(NewMask, VT))
12701         return DAG.getVectorShuffle(VT, SDLoc(N), InVec, DAG.getUNDEF(VT),
12702                                     NewMask);
12703     }
12704   }
12705
12706   return SDValue();
12707 }
12708
12709 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
12710   SDValue N0 = N->getOperand(0);
12711   SDValue N2 = N->getOperand(2);
12712
12713   // If the input vector is a concatenation, and the insert replaces
12714   // one of the halves, we can optimize into a single concat_vectors.
12715   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
12716       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
12717     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
12718     EVT VT = N->getValueType(0);
12719
12720     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12721     // (concat_vectors Z, Y)
12722     if (InsIdx == 0)
12723       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12724                          N->getOperand(1), N0.getOperand(1));
12725
12726     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
12727     // (concat_vectors X, Z)
12728     if (InsIdx == VT.getVectorNumElements()/2)
12729       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
12730                          N0.getOperand(0), N->getOperand(1));
12731   }
12732
12733   return SDValue();
12734 }
12735
12736 SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
12737   SDValue N0 = N->getOperand(0);
12738
12739   // fold (fp_to_fp16 (fp16_to_fp op)) -> op
12740   if (N0->getOpcode() == ISD::FP16_TO_FP)
12741     return N0->getOperand(0);
12742
12743   return SDValue();
12744 }
12745
12746 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
12747 /// with the destination vector and a zero vector.
12748 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
12749 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
12750 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
12751   EVT VT = N->getValueType(0);
12752   SDValue LHS = N->getOperand(0);
12753   SDValue RHS = N->getOperand(1);
12754   SDLoc dl(N);
12755
12756   // Make sure we're not running after operation legalization where it 
12757   // may have custom lowered the vector shuffles.
12758   if (LegalOperations)
12759     return SDValue();
12760
12761   if (N->getOpcode() != ISD::AND)
12762     return SDValue();
12763
12764   if (RHS.getOpcode() == ISD::BITCAST)
12765     RHS = RHS.getOperand(0);
12766
12767   if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
12768     SmallVector<int, 8> Indices;
12769     unsigned NumElts = RHS.getNumOperands();
12770
12771     for (unsigned i = 0; i != NumElts; ++i) {
12772       SDValue Elt = RHS.getOperand(i);
12773       if (!isa<ConstantSDNode>(Elt))
12774         return SDValue();
12775
12776       if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
12777         Indices.push_back(i);
12778       else if (cast<ConstantSDNode>(Elt)->isNullValue())
12779         Indices.push_back(NumElts+i);
12780       else
12781         return SDValue();
12782     }
12783
12784     // Let's see if the target supports this vector_shuffle.
12785     EVT RVT = RHS.getValueType();
12786     if (!TLI.isVectorClearMaskLegal(Indices, RVT))
12787       return SDValue();
12788
12789     // Return the new VECTOR_SHUFFLE node.
12790     EVT EltVT = RVT.getVectorElementType();
12791     SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
12792                                    DAG.getConstant(0, dl, EltVT));
12793     SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, dl, RVT, ZeroOps);
12794     LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
12795     SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
12796     return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
12797   }
12798
12799   return SDValue();
12800 }
12801
12802 /// Visit a binary vector operation, like ADD.
12803 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
12804   assert(N->getValueType(0).isVector() &&
12805          "SimplifyVBinOp only works on vectors!");
12806
12807   SDValue LHS = N->getOperand(0);
12808   SDValue RHS = N->getOperand(1);
12809
12810   if (SDValue Shuffle = XformToShuffleWithZero(N))
12811     return Shuffle;
12812
12813   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
12814   // this operation.
12815   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
12816       RHS.getOpcode() == ISD::BUILD_VECTOR) {
12817     // Check if both vectors are constants. If not bail out.
12818     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
12819           cast<BuildVectorSDNode>(RHS)->isConstant()))
12820       return SDValue();
12821
12822     SmallVector<SDValue, 8> Ops;
12823     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
12824       SDValue LHSOp = LHS.getOperand(i);
12825       SDValue RHSOp = RHS.getOperand(i);
12826
12827       // Can't fold divide by zero.
12828       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
12829           N->getOpcode() == ISD::FDIV) {
12830         if ((RHSOp.getOpcode() == ISD::Constant &&
12831              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
12832             (RHSOp.getOpcode() == ISD::ConstantFP &&
12833              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
12834           break;
12835       }
12836
12837       EVT VT = LHSOp.getValueType();
12838       EVT RVT = RHSOp.getValueType();
12839       if (RVT != VT) {
12840         // Integer BUILD_VECTOR operands may have types larger than the element
12841         // size (e.g., when the element type is not legal).  Prior to type
12842         // legalization, the types may not match between the two BUILD_VECTORS.
12843         // Truncate one of the operands to make them match.
12844         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
12845           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
12846         } else {
12847           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
12848           VT = RVT;
12849         }
12850       }
12851       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
12852                                    LHSOp, RHSOp);
12853       if (FoldOp.getOpcode() != ISD::UNDEF &&
12854           FoldOp.getOpcode() != ISD::Constant &&
12855           FoldOp.getOpcode() != ISD::ConstantFP)
12856         break;
12857       Ops.push_back(FoldOp);
12858       AddToWorklist(FoldOp.getNode());
12859     }
12860
12861     if (Ops.size() == LHS.getNumOperands())
12862       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
12863   }
12864
12865   // Type legalization might introduce new shuffles in the DAG.
12866   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
12867   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
12868   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
12869       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
12870       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
12871       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
12872     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
12873     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
12874
12875     if (SVN0->getMask().equals(SVN1->getMask())) {
12876       EVT VT = N->getValueType(0);
12877       SDValue UndefVector = LHS.getOperand(1);
12878       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
12879                                      LHS.getOperand(0), RHS.getOperand(0));
12880       AddUsersToWorklist(N);
12881       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
12882                                   &SVN0->getMask()[0]);
12883     }
12884   }
12885
12886   return SDValue();
12887 }
12888
12889 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
12890                                     SDValue N1, SDValue N2){
12891   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
12892
12893   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
12894                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
12895
12896   // If we got a simplified select_cc node back from SimplifySelectCC, then
12897   // break it down into a new SETCC node, and a new SELECT node, and then return
12898   // the SELECT node, since we were called with a SELECT node.
12899   if (SCC.getNode()) {
12900     // Check to see if we got a select_cc back (to turn into setcc/select).
12901     // Otherwise, just return whatever node we got back, like fabs.
12902     if (SCC.getOpcode() == ISD::SELECT_CC) {
12903       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
12904                                   N0.getValueType(),
12905                                   SCC.getOperand(0), SCC.getOperand(1),
12906                                   SCC.getOperand(4));
12907       AddToWorklist(SETCC.getNode());
12908       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
12909                            SCC.getOperand(2), SCC.getOperand(3));
12910     }
12911
12912     return SCC;
12913   }
12914   return SDValue();
12915 }
12916
12917 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
12918 /// being selected between, see if we can simplify the select.  Callers of this
12919 /// should assume that TheSelect is deleted if this returns true.  As such, they
12920 /// should return the appropriate thing (e.g. the node) back to the top-level of
12921 /// the DAG combiner loop to avoid it being looked at.
12922 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
12923                                     SDValue RHS) {
12924
12925   // fold (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12926   // The select + setcc is redundant, because fsqrt returns NaN for X < -0.
12927   if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
12928     if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
12929       // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
12930       SDValue Sqrt = RHS;
12931       ISD::CondCode CC;
12932       SDValue CmpLHS;
12933       const ConstantFPSDNode *NegZero = nullptr;
12934
12935       if (TheSelect->getOpcode() == ISD::SELECT_CC) {
12936         CC = dyn_cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
12937         CmpLHS = TheSelect->getOperand(0);
12938         NegZero = isConstOrConstSplatFP(TheSelect->getOperand(1));
12939       } else {
12940         // SELECT or VSELECT
12941         SDValue Cmp = TheSelect->getOperand(0);
12942         if (Cmp.getOpcode() == ISD::SETCC) {
12943           CC = dyn_cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
12944           CmpLHS = Cmp.getOperand(0);
12945           NegZero = isConstOrConstSplatFP(Cmp.getOperand(1));
12946         }
12947       }
12948       if (NegZero && NegZero->isNegative() && NegZero->isZero() &&
12949           Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
12950           CC == ISD::SETULT || CC == ISD::SETLT)) {
12951         // We have: (select (setcc x, -0.0, *lt), NaN, (fsqrt x))
12952         CombineTo(TheSelect, Sqrt);
12953         return true;
12954       }
12955     }
12956   }
12957   // Cannot simplify select with vector condition
12958   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
12959
12960   // If this is a select from two identical things, try to pull the operation
12961   // through the select.
12962   if (LHS.getOpcode() != RHS.getOpcode() ||
12963       !LHS.hasOneUse() || !RHS.hasOneUse())
12964     return false;
12965
12966   // If this is a load and the token chain is identical, replace the select
12967   // of two loads with a load through a select of the address to load from.
12968   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
12969   // constants have been dropped into the constant pool.
12970   if (LHS.getOpcode() == ISD::LOAD) {
12971     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
12972     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
12973
12974     // Token chains must be identical.
12975     if (LHS.getOperand(0) != RHS.getOperand(0) ||
12976         // Do not let this transformation reduce the number of volatile loads.
12977         LLD->isVolatile() || RLD->isVolatile() ||
12978         // FIXME: If either is a pre/post inc/dec load,
12979         // we'd need to split out the address adjustment.
12980         LLD->isIndexed() || RLD->isIndexed() ||
12981         // If this is an EXTLOAD, the VT's must match.
12982         LLD->getMemoryVT() != RLD->getMemoryVT() ||
12983         // If this is an EXTLOAD, the kind of extension must match.
12984         (LLD->getExtensionType() != RLD->getExtensionType() &&
12985          // The only exception is if one of the extensions is anyext.
12986          LLD->getExtensionType() != ISD::EXTLOAD &&
12987          RLD->getExtensionType() != ISD::EXTLOAD) ||
12988         // FIXME: this discards src value information.  This is
12989         // over-conservative. It would be beneficial to be able to remember
12990         // both potential memory locations.  Since we are discarding
12991         // src value info, don't do the transformation if the memory
12992         // locations are not in the default address space.
12993         LLD->getPointerInfo().getAddrSpace() != 0 ||
12994         RLD->getPointerInfo().getAddrSpace() != 0 ||
12995         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
12996                                       LLD->getBasePtr().getValueType()))
12997       return false;
12998
12999     // Check that the select condition doesn't reach either load.  If so,
13000     // folding this will induce a cycle into the DAG.  If not, this is safe to
13001     // xform, so create a select of the addresses.
13002     SDValue Addr;
13003     if (TheSelect->getOpcode() == ISD::SELECT) {
13004       SDNode *CondNode = TheSelect->getOperand(0).getNode();
13005       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
13006           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
13007         return false;
13008       // The loads must not depend on one another.
13009       if (LLD->isPredecessorOf(RLD) ||
13010           RLD->isPredecessorOf(LLD))
13011         return false;
13012       Addr = DAG.getSelect(SDLoc(TheSelect),
13013                            LLD->getBasePtr().getValueType(),
13014                            TheSelect->getOperand(0), LLD->getBasePtr(),
13015                            RLD->getBasePtr());
13016     } else {  // Otherwise SELECT_CC
13017       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
13018       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
13019
13020       if ((LLD->hasAnyUseOfValue(1) &&
13021            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
13022           (RLD->hasAnyUseOfValue(1) &&
13023            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
13024         return false;
13025
13026       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
13027                          LLD->getBasePtr().getValueType(),
13028                          TheSelect->getOperand(0),
13029                          TheSelect->getOperand(1),
13030                          LLD->getBasePtr(), RLD->getBasePtr(),
13031                          TheSelect->getOperand(4));
13032     }
13033
13034     SDValue Load;
13035     // It is safe to replace the two loads if they have different alignments,
13036     // but the new load must be the minimum (most restrictive) alignment of the
13037     // inputs.
13038     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
13039     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
13040     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
13041       Load = DAG.getLoad(TheSelect->getValueType(0),
13042                          SDLoc(TheSelect),
13043                          // FIXME: Discards pointer and AA info.
13044                          LLD->getChain(), Addr, MachinePointerInfo(),
13045                          LLD->isVolatile(), LLD->isNonTemporal(),
13046                          isInvariant, Alignment);
13047     } else {
13048       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
13049                             RLD->getExtensionType() : LLD->getExtensionType(),
13050                             SDLoc(TheSelect),
13051                             TheSelect->getValueType(0),
13052                             // FIXME: Discards pointer and AA info.
13053                             LLD->getChain(), Addr, MachinePointerInfo(),
13054                             LLD->getMemoryVT(), LLD->isVolatile(),
13055                             LLD->isNonTemporal(), isInvariant, Alignment);
13056     }
13057
13058     // Users of the select now use the result of the load.
13059     CombineTo(TheSelect, Load);
13060
13061     // Users of the old loads now use the new load's chain.  We know the
13062     // old-load value is dead now.
13063     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
13064     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
13065     return true;
13066   }
13067
13068   return false;
13069 }
13070
13071 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
13072 /// where 'cond' is the comparison specified by CC.
13073 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
13074                                       SDValue N2, SDValue N3,
13075                                       ISD::CondCode CC, bool NotExtCompare) {
13076   // (x ? y : y) -> y.
13077   if (N2 == N3) return N2;
13078
13079   EVT VT = N2.getValueType();
13080   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
13081   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
13082   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
13083
13084   // Determine if the condition we're dealing with is constant
13085   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
13086                               N0, N1, CC, DL, false);
13087   if (SCC.getNode()) AddToWorklist(SCC.getNode());
13088   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
13089
13090   // fold select_cc true, x, y -> x
13091   if (SCCC && !SCCC->isNullValue())
13092     return N2;
13093   // fold select_cc false, x, y -> y
13094   if (SCCC && SCCC->isNullValue())
13095     return N3;
13096
13097   // Check to see if we can simplify the select into an fabs node
13098   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
13099     // Allow either -0.0 or 0.0
13100     if (CFP->getValueAPF().isZero()) {
13101       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
13102       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
13103           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
13104           N2 == N3.getOperand(0))
13105         return DAG.getNode(ISD::FABS, DL, VT, N0);
13106
13107       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
13108       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
13109           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
13110           N2.getOperand(0) == N3)
13111         return DAG.getNode(ISD::FABS, DL, VT, N3);
13112     }
13113   }
13114
13115   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
13116   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
13117   // in it.  This is a win when the constant is not otherwise available because
13118   // it replaces two constant pool loads with one.  We only do this if the FP
13119   // type is known to be legal, because if it isn't, then we are before legalize
13120   // types an we want the other legalization to happen first (e.g. to avoid
13121   // messing with soft float) and if the ConstantFP is not legal, because if
13122   // it is legal, we may not need to store the FP constant in a constant pool.
13123   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
13124     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
13125       if (TLI.isTypeLegal(N2.getValueType()) &&
13126           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
13127                TargetLowering::Legal &&
13128            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
13129            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
13130           // If both constants have multiple uses, then we won't need to do an
13131           // extra load, they are likely around in registers for other users.
13132           (TV->hasOneUse() || FV->hasOneUse())) {
13133         Constant *Elts[] = {
13134           const_cast<ConstantFP*>(FV->getConstantFPValue()),
13135           const_cast<ConstantFP*>(TV->getConstantFPValue())
13136         };
13137         Type *FPTy = Elts[0]->getType();
13138         const DataLayout &TD = *TLI.getDataLayout();
13139
13140         // Create a ConstantArray of the two constants.
13141         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
13142         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
13143                                             TD.getPrefTypeAlignment(FPTy));
13144         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
13145
13146         // Get the offsets to the 0 and 1 element of the array so that we can
13147         // select between them.
13148         SDValue Zero = DAG.getIntPtrConstant(0, DL);
13149         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
13150         SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
13151
13152         SDValue Cond = DAG.getSetCC(DL,
13153                                     getSetCCResultType(N0.getValueType()),
13154                                     N0, N1, CC);
13155         AddToWorklist(Cond.getNode());
13156         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
13157                                           Cond, One, Zero);
13158         AddToWorklist(CstOffset.getNode());
13159         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
13160                             CstOffset);
13161         AddToWorklist(CPIdx.getNode());
13162         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
13163                            MachinePointerInfo::getConstantPool(), false,
13164                            false, false, Alignment);
13165       }
13166     }
13167
13168   // Check to see if we can perform the "gzip trick", transforming
13169   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
13170   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
13171       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
13172        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
13173     EVT XType = N0.getValueType();
13174     EVT AType = N2.getValueType();
13175     if (XType.bitsGE(AType)) {
13176       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
13177       // single-bit constant.
13178       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
13179         unsigned ShCtV = N2C->getAPIntValue().logBase2();
13180         ShCtV = XType.getSizeInBits() - ShCtV - 1;
13181         SDValue ShCt = DAG.getConstant(ShCtV, SDLoc(N0),
13182                                        getShiftAmountTy(N0.getValueType()));
13183         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
13184                                     XType, N0, ShCt);
13185         AddToWorklist(Shift.getNode());
13186
13187         if (XType.bitsGT(AType)) {
13188           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13189           AddToWorklist(Shift.getNode());
13190         }
13191
13192         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13193       }
13194
13195       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
13196                                   XType, N0,
13197                                   DAG.getConstant(XType.getSizeInBits() - 1,
13198                                                   SDLoc(N0),
13199                                          getShiftAmountTy(N0.getValueType())));
13200       AddToWorklist(Shift.getNode());
13201
13202       if (XType.bitsGT(AType)) {
13203         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
13204         AddToWorklist(Shift.getNode());
13205       }
13206
13207       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
13208     }
13209   }
13210
13211   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
13212   // where y is has a single bit set.
13213   // A plaintext description would be, we can turn the SELECT_CC into an AND
13214   // when the condition can be materialized as an all-ones register.  Any
13215   // single bit-test can be materialized as an all-ones register with
13216   // shift-left and shift-right-arith.
13217   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
13218       N0->getValueType(0) == VT &&
13219       N1C && N1C->isNullValue() &&
13220       N2C && N2C->isNullValue()) {
13221     SDValue AndLHS = N0->getOperand(0);
13222     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
13223     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
13224       // Shift the tested bit over the sign bit.
13225       APInt AndMask = ConstAndRHS->getAPIntValue();
13226       SDValue ShlAmt =
13227         DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
13228                         getShiftAmountTy(AndLHS.getValueType()));
13229       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
13230
13231       // Now arithmetic right shift it all the way over, so the result is either
13232       // all-ones, or zero.
13233       SDValue ShrAmt =
13234         DAG.getConstant(AndMask.getBitWidth() - 1, SDLoc(Shl),
13235                         getShiftAmountTy(Shl.getValueType()));
13236       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
13237
13238       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
13239     }
13240   }
13241
13242   // fold select C, 16, 0 -> shl C, 4
13243   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
13244       TLI.getBooleanContents(N0.getValueType()) ==
13245           TargetLowering::ZeroOrOneBooleanContent) {
13246
13247     // If the caller doesn't want us to simplify this into a zext of a compare,
13248     // don't do it.
13249     if (NotExtCompare && N2C->getAPIntValue() == 1)
13250       return SDValue();
13251
13252     // Get a SetCC of the condition
13253     // NOTE: Don't create a SETCC if it's not legal on this target.
13254     if (!LegalOperations ||
13255         TLI.isOperationLegal(ISD::SETCC,
13256           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
13257       SDValue Temp, SCC;
13258       // cast from setcc result type to select result type
13259       if (LegalTypes) {
13260         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
13261                             N0, N1, CC);
13262         if (N2.getValueType().bitsLT(SCC.getValueType()))
13263           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
13264                                         N2.getValueType());
13265         else
13266           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13267                              N2.getValueType(), SCC);
13268       } else {
13269         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
13270         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
13271                            N2.getValueType(), SCC);
13272       }
13273
13274       AddToWorklist(SCC.getNode());
13275       AddToWorklist(Temp.getNode());
13276
13277       if (N2C->getAPIntValue() == 1)
13278         return Temp;
13279
13280       // shl setcc result by log2 n2c
13281       return DAG.getNode(
13282           ISD::SHL, DL, N2.getValueType(), Temp,
13283           DAG.getConstant(N2C->getAPIntValue().logBase2(), SDLoc(Temp),
13284                           getShiftAmountTy(Temp.getValueType())));
13285     }
13286   }
13287
13288   // Check to see if this is the equivalent of setcc
13289   // FIXME: Turn all of these into setcc if setcc if setcc is legal
13290   // otherwise, go ahead with the folds.
13291   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
13292     EVT XType = N0.getValueType();
13293     if (!LegalOperations ||
13294         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
13295       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
13296       if (Res.getValueType() != VT)
13297         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
13298       return Res;
13299     }
13300
13301     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
13302     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
13303         (!LegalOperations ||
13304          TLI.isOperationLegal(ISD::CTLZ, XType))) {
13305       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
13306       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
13307                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
13308                                          SDLoc(Ctlz),
13309                                        getShiftAmountTy(Ctlz.getValueType())));
13310     }
13311     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
13312     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
13313       SDLoc DL(N0);
13314       SDValue NegN0 = DAG.getNode(ISD::SUB, DL,
13315                                   XType, DAG.getConstant(0, DL, XType), N0);
13316       SDValue NotN0 = DAG.getNOT(DL, N0, XType);
13317       return DAG.getNode(ISD::SRL, DL, XType,
13318                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
13319                          DAG.getConstant(XType.getSizeInBits() - 1, DL,
13320                                          getShiftAmountTy(XType)));
13321     }
13322     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
13323     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
13324       SDLoc DL(N0);
13325       SDValue Sign = DAG.getNode(ISD::SRL, DL, XType, N0,
13326                                  DAG.getConstant(XType.getSizeInBits() - 1, DL,
13327                                          getShiftAmountTy(N0.getValueType())));
13328       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, DL,
13329                                                                     XType));
13330     }
13331   }
13332
13333   // Check to see if this is an integer abs.
13334   // select_cc setg[te] X,  0,  X, -X ->
13335   // select_cc setgt    X, -1,  X, -X ->
13336   // select_cc setl[te] X,  0, -X,  X ->
13337   // select_cc setlt    X,  1, -X,  X ->
13338   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
13339   if (N1C) {
13340     ConstantSDNode *SubC = nullptr;
13341     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
13342          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
13343         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
13344       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
13345     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
13346               (N1C->isOne() && CC == ISD::SETLT)) &&
13347              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
13348       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
13349
13350     EVT XType = N0.getValueType();
13351     if (SubC && SubC->isNullValue() && XType.isInteger()) {
13352       SDLoc DL(N0);
13353       SDValue Shift = DAG.getNode(ISD::SRA, DL, XType,
13354                                   N0,
13355                                   DAG.getConstant(XType.getSizeInBits() - 1, DL,
13356                                          getShiftAmountTy(N0.getValueType())));
13357       SDValue Add = DAG.getNode(ISD::ADD, DL,
13358                                 XType, N0, Shift);
13359       AddToWorklist(Shift.getNode());
13360       AddToWorklist(Add.getNode());
13361       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
13362     }
13363   }
13364
13365   return SDValue();
13366 }
13367
13368 /// This is a stub for TargetLowering::SimplifySetCC.
13369 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
13370                                    SDValue N1, ISD::CondCode Cond,
13371                                    SDLoc DL, bool foldBooleans) {
13372   TargetLowering::DAGCombinerInfo
13373     DagCombineInfo(DAG, Level, false, this);
13374   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
13375 }
13376
13377 /// Given an ISD::SDIV node expressing a divide by constant, return
13378 /// a DAG expression to select that will generate the same value by multiplying
13379 /// by a magic number.
13380 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13381 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
13382   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13383   if (!C)
13384     return SDValue();
13385
13386   // Avoid division by zero.
13387   if (!C->getAPIntValue())
13388     return SDValue();
13389
13390   std::vector<SDNode*> Built;
13391   SDValue S =
13392       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13393
13394   for (SDNode *N : Built)
13395     AddToWorklist(N);
13396   return S;
13397 }
13398
13399 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
13400 /// DAG expression that will generate the same value by right shifting.
13401 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
13402   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13403   if (!C)
13404     return SDValue();
13405
13406   // Avoid division by zero.
13407   if (!C->getAPIntValue())
13408     return SDValue();
13409
13410   std::vector<SDNode *> Built;
13411   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
13412
13413   for (SDNode *N : Built)
13414     AddToWorklist(N);
13415   return S;
13416 }
13417
13418 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
13419 /// expression that will generate the same value by multiplying by a magic
13420 /// number.
13421 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
13422 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
13423   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
13424   if (!C)
13425     return SDValue();
13426
13427   // Avoid division by zero.
13428   if (!C->getAPIntValue())
13429     return SDValue();
13430
13431   std::vector<SDNode*> Built;
13432   SDValue S =
13433       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
13434
13435   for (SDNode *N : Built)
13436     AddToWorklist(N);
13437   return S;
13438 }
13439
13440 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
13441   if (Level >= AfterLegalizeDAG)
13442     return SDValue();
13443
13444   // Expose the DAG combiner to the target combiner implementations.
13445   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13446
13447   unsigned Iterations = 0;
13448   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
13449     if (Iterations) {
13450       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13451       // For the reciprocal, we need to find the zero of the function:
13452       //   F(X) = A X - 1 [which has a zero at X = 1/A]
13453       //     =>
13454       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
13455       //     does not require additional intermediate precision]
13456       EVT VT = Op.getValueType();
13457       SDLoc DL(Op);
13458       SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
13459
13460       AddToWorklist(Est.getNode());
13461
13462       // Newton iterations: Est = Est + Est (1 - Arg * Est)
13463       for (unsigned i = 0; i < Iterations; ++i) {
13464         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
13465         AddToWorklist(NewEst.getNode());
13466
13467         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
13468         AddToWorklist(NewEst.getNode());
13469
13470         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13471         AddToWorklist(NewEst.getNode());
13472
13473         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
13474         AddToWorklist(Est.getNode());
13475       }
13476     }
13477     return Est;
13478   }
13479
13480   return SDValue();
13481 }
13482
13483 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13484 /// For the reciprocal sqrt, we need to find the zero of the function:
13485 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13486 ///     =>
13487 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
13488 /// As a result, we precompute A/2 prior to the iteration loop.
13489 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
13490                                           unsigned Iterations) {
13491   EVT VT = Arg.getValueType();
13492   SDLoc DL(Arg);
13493   SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
13494
13495   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
13496   // this entire sequence requires only one FP constant.
13497   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
13498   AddToWorklist(HalfArg.getNode());
13499
13500   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
13501   AddToWorklist(HalfArg.getNode());
13502
13503   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
13504   for (unsigned i = 0; i < Iterations; ++i) {
13505     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13506     AddToWorklist(NewEst.getNode());
13507
13508     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
13509     AddToWorklist(NewEst.getNode());
13510
13511     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
13512     AddToWorklist(NewEst.getNode());
13513
13514     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
13515     AddToWorklist(Est.getNode());
13516   }
13517   return Est;
13518 }
13519
13520 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
13521 /// For the reciprocal sqrt, we need to find the zero of the function:
13522 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
13523 ///     =>
13524 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
13525 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
13526                                           unsigned Iterations) {
13527   EVT VT = Arg.getValueType();
13528   SDLoc DL(Arg);
13529   SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
13530   SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
13531
13532   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
13533   for (unsigned i = 0; i < Iterations; ++i) {
13534     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
13535     AddToWorklist(HalfEst.getNode());
13536
13537     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
13538     AddToWorklist(Est.getNode());
13539
13540     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
13541     AddToWorklist(Est.getNode());
13542
13543     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
13544     AddToWorklist(Est.getNode());
13545
13546     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
13547     AddToWorklist(Est.getNode());
13548   }
13549   return Est;
13550 }
13551
13552 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
13553   if (Level >= AfterLegalizeDAG)
13554     return SDValue();
13555
13556   // Expose the DAG combiner to the target combiner implementations.
13557   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
13558   unsigned Iterations = 0;
13559   bool UseOneConstNR = false;
13560   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
13561     AddToWorklist(Est.getNode());
13562     if (Iterations) {
13563       Est = UseOneConstNR ?
13564         BuildRsqrtNROneConst(Op, Est, Iterations) :
13565         BuildRsqrtNRTwoConst(Op, Est, Iterations);
13566     }
13567     return Est;
13568   }
13569
13570   return SDValue();
13571 }
13572
13573 /// Return true if base is a frame index, which is known not to alias with
13574 /// anything but itself.  Provides base object and offset as results.
13575 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
13576                            const GlobalValue *&GV, const void *&CV) {
13577   // Assume it is a primitive operation.
13578   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
13579
13580   // If it's an adding a simple constant then integrate the offset.
13581   if (Base.getOpcode() == ISD::ADD) {
13582     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
13583       Base = Base.getOperand(0);
13584       Offset += C->getZExtValue();
13585     }
13586   }
13587
13588   // Return the underlying GlobalValue, and update the Offset.  Return false
13589   // for GlobalAddressSDNode since the same GlobalAddress may be represented
13590   // by multiple nodes with different offsets.
13591   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
13592     GV = G->getGlobal();
13593     Offset += G->getOffset();
13594     return false;
13595   }
13596
13597   // Return the underlying Constant value, and update the Offset.  Return false
13598   // for ConstantSDNodes since the same constant pool entry may be represented
13599   // by multiple nodes with different offsets.
13600   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
13601     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
13602                                          : (const void *)C->getConstVal();
13603     Offset += C->getOffset();
13604     return false;
13605   }
13606   // If it's any of the following then it can't alias with anything but itself.
13607   return isa<FrameIndexSDNode>(Base);
13608 }
13609
13610 /// Return true if there is any possibility that the two addresses overlap.
13611 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
13612   // If they are the same then they must be aliases.
13613   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
13614
13615   // If they are both volatile then they cannot be reordered.
13616   if (Op0->isVolatile() && Op1->isVolatile()) return true;
13617
13618   // Gather base node and offset information.
13619   SDValue Base1, Base2;
13620   int64_t Offset1, Offset2;
13621   const GlobalValue *GV1, *GV2;
13622   const void *CV1, *CV2;
13623   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
13624                                       Base1, Offset1, GV1, CV1);
13625   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
13626                                       Base2, Offset2, GV2, CV2);
13627
13628   // If they have a same base address then check to see if they overlap.
13629   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
13630     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13631              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13632
13633   // It is possible for different frame indices to alias each other, mostly
13634   // when tail call optimization reuses return address slots for arguments.
13635   // To catch this case, look up the actual index of frame indices to compute
13636   // the real alias relationship.
13637   if (isFrameIndex1 && isFrameIndex2) {
13638     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
13639     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
13640     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
13641     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
13642              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
13643   }
13644
13645   // Otherwise, if we know what the bases are, and they aren't identical, then
13646   // we know they cannot alias.
13647   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
13648     return false;
13649
13650   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
13651   // compared to the size and offset of the access, we may be able to prove they
13652   // do not alias.  This check is conservative for now to catch cases created by
13653   // splitting vector types.
13654   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
13655       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
13656       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
13657        Op1->getMemoryVT().getSizeInBits() >> 3) &&
13658       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
13659     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
13660     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
13661
13662     // There is no overlap between these relatively aligned accesses of similar
13663     // size, return no alias.
13664     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
13665         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
13666       return false;
13667   }
13668
13669   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
13670                    ? CombinerGlobalAA
13671                    : DAG.getSubtarget().useAA();
13672 #ifndef NDEBUG
13673   if (CombinerAAOnlyFunc.getNumOccurrences() &&
13674       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
13675     UseAA = false;
13676 #endif
13677   if (UseAA &&
13678       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
13679     // Use alias analysis information.
13680     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
13681                                  Op1->getSrcValueOffset());
13682     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
13683         Op0->getSrcValueOffset() - MinOffset;
13684     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
13685         Op1->getSrcValueOffset() - MinOffset;
13686     AliasAnalysis::AliasResult AAResult =
13687         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
13688                                          Overlap1,
13689                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
13690                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
13691                                          Overlap2,
13692                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
13693     if (AAResult == AliasAnalysis::NoAlias)
13694       return false;
13695   }
13696
13697   // Otherwise we have to assume they alias.
13698   return true;
13699 }
13700
13701 /// Walk up chain skipping non-aliasing memory nodes,
13702 /// looking for aliasing nodes and adding them to the Aliases vector.
13703 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
13704                                    SmallVectorImpl<SDValue> &Aliases) {
13705   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
13706   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
13707
13708   // Get alias information for node.
13709   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
13710
13711   // Starting off.
13712   Chains.push_back(OriginalChain);
13713   unsigned Depth = 0;
13714
13715   // Look at each chain and determine if it is an alias.  If so, add it to the
13716   // aliases list.  If not, then continue up the chain looking for the next
13717   // candidate.
13718   while (!Chains.empty()) {
13719     SDValue Chain = Chains.back();
13720     Chains.pop_back();
13721
13722     // For TokenFactor nodes, look at each operand and only continue up the
13723     // chain until we find two aliases.  If we've seen two aliases, assume we'll
13724     // find more and revert to original chain since the xform is unlikely to be
13725     // profitable.
13726     //
13727     // FIXME: The depth check could be made to return the last non-aliasing
13728     // chain we found before we hit a tokenfactor rather than the original
13729     // chain.
13730     if (Depth > 6 || Aliases.size() == 2) {
13731       Aliases.clear();
13732       Aliases.push_back(OriginalChain);
13733       return;
13734     }
13735
13736     // Don't bother if we've been before.
13737     if (!Visited.insert(Chain.getNode()).second)
13738       continue;
13739
13740     switch (Chain.getOpcode()) {
13741     case ISD::EntryToken:
13742       // Entry token is ideal chain operand, but handled in FindBetterChain.
13743       break;
13744
13745     case ISD::LOAD:
13746     case ISD::STORE: {
13747       // Get alias information for Chain.
13748       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
13749           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
13750
13751       // If chain is alias then stop here.
13752       if (!(IsLoad && IsOpLoad) &&
13753           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
13754         Aliases.push_back(Chain);
13755       } else {
13756         // Look further up the chain.
13757         Chains.push_back(Chain.getOperand(0));
13758         ++Depth;
13759       }
13760       break;
13761     }
13762
13763     case ISD::TokenFactor:
13764       // We have to check each of the operands of the token factor for "small"
13765       // token factors, so we queue them up.  Adding the operands to the queue
13766       // (stack) in reverse order maintains the original order and increases the
13767       // likelihood that getNode will find a matching token factor (CSE.)
13768       if (Chain.getNumOperands() > 16) {
13769         Aliases.push_back(Chain);
13770         break;
13771       }
13772       for (unsigned n = Chain.getNumOperands(); n;)
13773         Chains.push_back(Chain.getOperand(--n));
13774       ++Depth;
13775       break;
13776
13777     default:
13778       // For all other instructions we will just have to take what we can get.
13779       Aliases.push_back(Chain);
13780       break;
13781     }
13782   }
13783
13784   // We need to be careful here to also search for aliases through the
13785   // value operand of a store, etc. Consider the following situation:
13786   //   Token1 = ...
13787   //   L1 = load Token1, %52
13788   //   S1 = store Token1, L1, %51
13789   //   L2 = load Token1, %52+8
13790   //   S2 = store Token1, L2, %51+8
13791   //   Token2 = Token(S1, S2)
13792   //   L3 = load Token2, %53
13793   //   S3 = store Token2, L3, %52
13794   //   L4 = load Token2, %53+8
13795   //   S4 = store Token2, L4, %52+8
13796   // If we search for aliases of S3 (which loads address %52), and we look
13797   // only through the chain, then we'll miss the trivial dependence on L1
13798   // (which also loads from %52). We then might change all loads and
13799   // stores to use Token1 as their chain operand, which could result in
13800   // copying %53 into %52 before copying %52 into %51 (which should
13801   // happen first).
13802   //
13803   // The problem is, however, that searching for such data dependencies
13804   // can become expensive, and the cost is not directly related to the
13805   // chain depth. Instead, we'll rule out such configurations here by
13806   // insisting that we've visited all chain users (except for users
13807   // of the original chain, which is not necessary). When doing this,
13808   // we need to look through nodes we don't care about (otherwise, things
13809   // like register copies will interfere with trivial cases).
13810
13811   SmallVector<const SDNode *, 16> Worklist;
13812   for (const SDNode *N : Visited)
13813     if (N != OriginalChain.getNode())
13814       Worklist.push_back(N);
13815
13816   while (!Worklist.empty()) {
13817     const SDNode *M = Worklist.pop_back_val();
13818
13819     // We have already visited M, and want to make sure we've visited any uses
13820     // of M that we care about. For uses that we've not visisted, and don't
13821     // care about, queue them to the worklist.
13822
13823     for (SDNode::use_iterator UI = M->use_begin(),
13824          UIE = M->use_end(); UI != UIE; ++UI)
13825       if (UI.getUse().getValueType() == MVT::Other &&
13826           Visited.insert(*UI).second) {
13827         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
13828           // We've not visited this use, and we care about it (it could have an
13829           // ordering dependency with the original node).
13830           Aliases.clear();
13831           Aliases.push_back(OriginalChain);
13832           return;
13833         }
13834
13835         // We've not visited this use, but we don't care about it. Mark it as
13836         // visited and enqueue it to the worklist.
13837         Worklist.push_back(*UI);
13838       }
13839   }
13840 }
13841
13842 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
13843 /// (aliasing node.)
13844 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
13845   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
13846
13847   // Accumulate all the aliases to this node.
13848   GatherAllAliases(N, OldChain, Aliases);
13849
13850   // If no operands then chain to entry token.
13851   if (Aliases.size() == 0)
13852     return DAG.getEntryNode();
13853
13854   // If a single operand then chain to it.  We don't need to revisit it.
13855   if (Aliases.size() == 1)
13856     return Aliases[0];
13857
13858   // Construct a custom tailored token factor.
13859   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
13860 }
13861
13862 /// This is the entry point for the file.
13863 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
13864                            CodeGenOpt::Level OptLevel) {
13865   /// This is the main entry point to this class.
13866   DAGCombiner(*this, AA, OptLevel).Run(Level);
13867 }