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